mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into feat/3d-rendered-paints
This commit is contained in:
commit
1b38f8cf7f
204 files changed
+11972
-2076
No files matched your search
@@ -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 (<os>)` 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 (<os>)` leg runs the other `cargo xtask ci` steps beside
|
||||
# them, with a dependency cache of its own. `gate (<os>)` passes when the build and every
|
||||
# test leg that ran passed; `lint (<os>)` 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 (<os>)` leg
|
||||
# runs the other `cargo xtask ci` steps beside them, with a dependency cache of its own.
|
||||
# `gate (<os>)` passes when the build and every test leg that ran passed; `lint (<os>)` 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
|
||||
|
||||
@@ -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.')
|
||||
@@ -1,8 +1,12 @@
|
||||
name: SonarCloud
|
||||
|
||||
# Main is analyzed once a day, at the commit the nightly builds: Stage 2 admits a nightly only on
|
||||
# that commit's own analysis, and nightly-dispatch.yml waits for it before dispatching the signer.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
workflow_run:
|
||||
workflows: [VectorCraft unsigned nightly]
|
||||
types: [requested]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
@@ -12,16 +16,44 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
# A main run is the analysis a nightly waits for; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
nightly-commit:
|
||||
name: Nightly commit is main's head
|
||||
# A workflow_run checks out and analyzes main's head, so main must not have moved since the
|
||||
# nightly started.
|
||||
if: github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Require main's head to be the nightly's commit
|
||||
env:
|
||||
NIGHTLY_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
RUN_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
if [ "$NIGHTLY_SHA" != "$RUN_SHA" ]; then
|
||||
echo "::error::main moved from $NIGHTLY_SHA to $RUN_SHA after the nightly started; this run would not analyze the nightly's commit"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sonarcloud:
|
||||
needs: nightly-commit
|
||||
if: ${{ !cancelled() && contains(fromJSON('["success","skipped"]'), needs.nightly-commit.result) }}
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
|
||||
# archive stays within hosted-runner memory (craft-common-actions#333).
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# Each test writes its own raw coverage profile, about 80 GB per shard at 4 shards, which
|
||||
# fills the runner. 8 shards halve that. Go back to the default once
|
||||
# storytold/craft-common-actions#486 merges.
|
||||
shards: 8
|
||||
python-coverage-source: .github/scripts
|
||||
python-coverage-script: .github/scripts/tests/test_release_rpm_smoke.py
|
||||
secrets: inherit
|
||||
Generated
+186
-93
@@ -1256,7 +1256,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1298,7 +1298,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1319,7 +1319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1331,7 +1331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1339,7 +1339,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1364,7 +1364,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1383,7 +1383,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1401,8 +1401,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
]
|
||||
@@ -1410,7 +1411,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1418,7 +1419,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1427,12 +1428,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1452,7 +1453,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1468,7 +1469,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1478,7 +1479,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1486,7 +1487,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1512,7 +1513,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1528,7 +1529,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1536,7 +1537,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1555,7 +1556,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"craft-dxf",
|
||||
@@ -1565,7 +1566,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1577,7 +1578,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1587,12 +1588,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1602,7 +1603,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1617,7 +1618,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1636,7 +1637,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1645,7 +1646,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1668,12 +1669,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1681,7 +1682,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1689,7 +1690,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1702,7 +1703,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1732,7 +1733,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1759,7 +1760,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1777,7 +1778,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1785,7 +1786,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1796,7 +1797,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1811,7 +1812,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1825,7 +1826,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1843,7 +1844,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1855,7 +1856,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1866,7 +1867,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1876,7 +1877,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1885,7 +1886,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1901,7 +1902,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-texture",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1910,7 +1911,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1921,7 +1922,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1933,7 +1934,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1947,6 +1948,7 @@ dependencies = [
|
||||
"futures-lite",
|
||||
"js-sys",
|
||||
"log",
|
||||
"notify",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
@@ -1966,7 +1968,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1975,7 +1977,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1999,7 +2001,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2010,7 +2012,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -2024,7 +2026,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -2035,7 +2037,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2048,7 +2050,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2057,7 +2059,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2076,7 +2078,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2093,7 +2095,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2104,7 +2106,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2125,7 +2127,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2137,7 +2139,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2162,7 +2164,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2170,7 +2172,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2185,7 +2187,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2200,7 +2202,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2210,7 +2212,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2219,7 +2221,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2234,12 +2236,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2253,7 +2255,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2270,7 +2272,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2308,7 +2310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2319,7 +2321,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2337,7 +2339,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2358,7 +2360,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2379,7 +2381,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2393,12 +2395,13 @@ dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2430,7 +2433,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2441,7 +2444,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2451,7 +2454,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2462,7 +2465,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2470,7 +2473,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2502,7 +2505,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2971,7 +2974,6 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"smithay-clipboard",
|
||||
"web-time",
|
||||
"webbrowser",
|
||||
"windows-sys 0.61.2",
|
||||
"winit",
|
||||
]
|
||||
@@ -3862,7 +3864,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3871,7 +3873,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3889,7 +3891,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3907,12 +3909,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4474,6 +4476,26 @@ dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify"
|
||||
version = "0.11.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"inotify-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify-sys"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
@@ -4892,10 +4914,30 @@ dependencies = [
|
||||
"accesskit_consumer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
|
||||
dependencies = [
|
||||
"kqueue-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue-sys"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -5052,7 +5094,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -5194,6 +5236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -5359,6 +5402,35 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify"
|
||||
version = "9.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5482d5bd11b91a337521980e5d52fe115bdccfb4c217099daaf0abd69159dc4e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"inotify",
|
||||
"kqueue",
|
||||
"libc",
|
||||
"log",
|
||||
"mio",
|
||||
"notify-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-services",
|
||||
"walkdir",
|
||||
"windows-sys 0.61.2",
|
||||
"xxhash-rust",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-types"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
@@ -5713,6 +5785,16 @@ dependencies = [
|
||||
"objc2-core-video",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-services"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-text"
|
||||
version = "0.3.2"
|
||||
@@ -7618,7 +7700,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6b67abe4b3deead5a1437dc6987a85b35afd40f6#6b67abe4b3deead5a1437dc6987a85b35afd40f6"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
@@ -8673,6 +8755,7 @@ dependencies = [
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"webbrowser",
|
||||
"windows",
|
||||
"winit",
|
||||
"winreg",
|
||||
@@ -8780,6 +8863,7 @@ name = "vectorcraft-doc"
|
||||
version = "0.25.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-i18n",
|
||||
"craft-image-codecs",
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
@@ -9010,6 +9094,7 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"vectorcraft-pathops 0.25.1",
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
@@ -9219,6 +9304,7 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.25.1",
|
||||
"vello_cpu",
|
||||
"windows-registry",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
@@ -9291,6 +9377,7 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"toml",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
@@ -10574,6 +10661,12 @@ dependencies = [
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5"
|
||||
|
||||
[[package]]
|
||||
name = "yeslogic-fontconfig-sys"
|
||||
version = "6.0.1"
|
||||
|
||||
+44
-43
@@ -10,60 +10,62 @@ license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# Digits typed in any script in numeric fields (`vectorcraft_doc::units`).
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the
|
||||
# R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not.
|
||||
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -203,16 +205,15 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
|
||||
# It stays at this rev until craft-libs#5222 merges.
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6b67abe4b3deead5a1437dc6987a85b35afd40f6", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -80,7 +80,54 @@ fn a_dialog_is_marked_while_it_shows_and_not_after() {
|
||||
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
|
||||
fn reveal(path: &str) -> Result<(), String> {
|
||||
explorer_safe(path)?;
|
||||
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
|
||||
spawn_detached(&mut reveal_command(path)).map(drop).map_err(|e| format!("can't show {path}: {e}"))
|
||||
}
|
||||
|
||||
/// The thread that waits for a process [`spawn_detached`] started; it returns the exit status.
|
||||
pub(crate) type Reaper = std::thread::JoinHandle<std::io::Result<std::process::ExitStatus>>;
|
||||
|
||||
/// Starts `c` without the caller waiting for it. On Windows dropping the `Child` closes its handle,
|
||||
/// so there is no reaper. Elsewhere a thread waits for the process, so it is reaped when it ends
|
||||
/// instead of staying a zombie until the app exits. The thread starts first, so a process is never
|
||||
/// started without a waiter.
|
||||
pub(crate) fn spawn_detached(c: &mut std::process::Command) -> std::io::Result<Option<Reaper>> {
|
||||
#[cfg(windows)]
|
||||
let started = c.spawn().map(|_| None);
|
||||
#[cfg(not(windows))]
|
||||
let started = {
|
||||
let (send, receive) = std::sync::mpsc::channel::<std::process::Child>();
|
||||
let reaper = std::thread::Builder::new().name("process reaper".into()).spawn(move || match receive.recv() {
|
||||
Ok(mut child) => child.wait(),
|
||||
Err(_) => Err(std::io::Error::other("the process did not start")),
|
||||
})?;
|
||||
let child = c.spawn()?;
|
||||
// The reaper holds the receiver until it gets the child, so this send always arrives.
|
||||
let _ = send.send(child);
|
||||
Ok(Some(reaper))
|
||||
};
|
||||
started
|
||||
}
|
||||
|
||||
/// Linux keeps `/proc/<pid>` in state `Z` for a process that ended until its parent waits for it.
|
||||
/// A pid the kernel has given to a new process since is not in state `Z`.
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
#[test]
|
||||
fn a_started_process_is_reaped_once_it_ends() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let mut c = std::process::Command::new("sh");
|
||||
c.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file);
|
||||
let reaper = spawn_detached(&mut c).unwrap().expect("a reaper on Linux");
|
||||
let status = reaper.join().unwrap().unwrap();
|
||||
let pid = std::fs::read_to_string(&pid_file).unwrap();
|
||||
let pid = pid.trim().to_string();
|
||||
assert!(!pid.is_empty(), "the process wrote its pid");
|
||||
// `/proc/<pid>/stat` is `pid (comm) state ...`; a missing file means the pid is free.
|
||||
let state = std::fs::read_to_string(format!("/proc/{pid}/stat"))
|
||||
.ok()
|
||||
.and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string)));
|
||||
assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie");
|
||||
assert_eq!(status.code(), Some(3), "the reaper reads the process's own exit");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -108,6 +155,50 @@ fn reveal_command(path: &str) -> std::process::Command {
|
||||
c
|
||||
}
|
||||
|
||||
/// Opens the `file:` URL of a file the app wrote (View PDF after Saving, Show in Browser) in the
|
||||
/// default web browser.
|
||||
fn open_file_url(url: &str) -> Result<(), String> {
|
||||
webbrowser::open(url).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
|
||||
/// Opens a link with the system's handler, without the caller waiting for it:
|
||||
/// `craft::platform::open::open_external` on macOS and Windows, xdg-open elsewhere ([`link_command`]).
|
||||
pub(crate) fn open_link(url: &str) -> Result<(), String> {
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
let mut c = link_command(url)?;
|
||||
c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||
spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
{
|
||||
craft::platform::open::open_external(url)
|
||||
}
|
||||
}
|
||||
|
||||
/// xdg-open with `url` as its only argument. xdg-open stops with "unexpected option" at any
|
||||
/// argument that starts with `-`, `--` included, which `craft::platform::open::open_external` puts
|
||||
/// before the URL, so a URL that starts with `-` is refused here instead. Remove this once
|
||||
/// craft-libs' `open_external` runs xdg-open without `--`.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
fn link_command(url: &str) -> Result<std::process::Command, String> {
|
||||
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::<Vec<_>>(), ["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<Vec<u8>, String> {
|
||||
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
|
||||
@@ -183,6 +274,8 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
// View PDF after Saving and Show in Browser open the file they wrote.
|
||||
open_file_url: Some(Box::new(open_file_url)),
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
@@ -219,7 +312,7 @@ fn open_file(path: &str) -> Result<(), String> {
|
||||
let mut c = std::process::Command::new("xdg-open");
|
||||
#[cfg(not(windows))]
|
||||
c.arg(path);
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
|
||||
spawn_detached(&mut c).map(drop).map_err(|e| format!("can't open {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off
|
||||
@@ -294,7 +387,7 @@ fn launch_application(app: &std::path::Path, path: &str) -> Result<bool, String>
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
|
||||
spawn_detached(&mut c).map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
|
||||
}
|
||||
|
||||
/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -68,6 +68,7 @@ mod single_instance;
|
||||
mod system_fonts;
|
||||
mod tablet;
|
||||
mod window_frame;
|
||||
mod window_system;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
@@ -91,7 +92,6 @@ use craft::ui::shell::embed;
|
||||
use craft::window::Prefix;
|
||||
use craft::window::policy::{TitleBarPref, decide_for};
|
||||
use craft::window::restore::Store;
|
||||
use craft::window::system::SystemWindows;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
@@ -117,20 +117,9 @@ const MIN_SIZE: [f32; 2] = [800.0, 500.0];
|
||||
/// framework maximizes the window when its default size would not fit the current screen.
|
||||
fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option<vectorcraft_ui_egui::state::LegacyWindow>, wayland: bool) {
|
||||
use craft::behavior::placement::{Defaults, Placement, place};
|
||||
use craft::behavior::{Monitor, MonitorKey};
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition};
|
||||
|
||||
let handles: Vec<_> = window.available_monitors().collect();
|
||||
let monitors: Vec<_> = handles
|
||||
.iter()
|
||||
.map(|monitor| {
|
||||
let size = monitor.size();
|
||||
let size = [size.width, size.height];
|
||||
let position = monitor.position();
|
||||
Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32)
|
||||
})
|
||||
.collect();
|
||||
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
|
||||
let (monitors, home) = window_system::monitor_layout(window).unwrap_or_default();
|
||||
let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland);
|
||||
let saved = store.get(craft::window::restore::MAIN).or_else(|| {
|
||||
let old = legacy?;
|
||||
@@ -439,6 +428,17 @@ fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo {
|
||||
ShellInfo::current().backend(backend)
|
||||
}
|
||||
|
||||
/// The UI runtime's install spec for the main window: the app's id, and every `http`, `https` or `mailto` link the
|
||||
/// app asks to open (Help menu, About, credits, the updater, an object's URL) handed to `open_link`, which is
|
||||
/// [`host_services::open_link`] in the app.
|
||||
fn main_window_spec(
|
||||
shell_info: ShellInfo,
|
||||
windows: Arc<dyn craft::window::system::WindowSystem>,
|
||||
open_link: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static,
|
||||
) -> InstallSpec {
|
||||
InstallSpec::new(shell_info, windows).app_id(vectorcraft_ui_egui::os_window::app_id()).open_links(open_link)
|
||||
}
|
||||
|
||||
/// The nightly channel this build is, as a string for the log.
|
||||
fn channel_name() -> &'static str {
|
||||
match build_flavor::COMPILED {
|
||||
@@ -885,10 +885,11 @@ fn main() -> std::process::ExitCode {
|
||||
if let Some(window) = &winit_window {
|
||||
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
|
||||
}
|
||||
let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows))
|
||||
.app_id(vectorcraft_ui_egui::os_window::app_id())
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
// A pen or a finger in contact counts as the primary button (`windows_stylus`).
|
||||
let spec =
|
||||
main_window_spec(shell_info, Arc::new(window_system::DesktopWindows::new(winit_window.as_ref())), host_services::open_link)
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
let spec = match start_pen(&winit_window) {
|
||||
Some(pen) => spec.pen(pen),
|
||||
None => spec,
|
||||
|
||||
@@ -459,21 +459,82 @@ mod system {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = printer;
|
||||
Command::new("open")
|
||||
.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension")
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string())
|
||||
let mut open = Command::new("open");
|
||||
open.arg("x-apple.systempreferences:com.apple.Print-Scan-Settings.extension");
|
||||
start_first([open]).map(drop).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
{
|
||||
if Command::new("system-config-printer").spawn().is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}"));
|
||||
Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
|
||||
start_first(setup_commands(printer)).map(drop).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands [`setup`] tries in order on Linux and the BSDs: the printer settings app, then the
|
||||
/// CUPS web page for `printer` (or the printer list) in the browser.
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
pub(super) fn setup_commands(printer: Option<&str>) -> [Command; 2] {
|
||||
let url = printer.map_or_else(|| "http://localhost:631/printers/".to_string(), |p| format!("http://localhost:631/printers/{p}"));
|
||||
let mut open = Command::new("xdg-open");
|
||||
open.arg(url);
|
||||
[Command::new("system-config-printer"), open]
|
||||
}
|
||||
|
||||
/// Starts the first of `commands` that starts, through [`crate::host_services::spawn_detached`], so
|
||||
/// it is reaped when it ends. Returns the last error when none starts.
|
||||
#[cfg(not(windows))]
|
||||
pub(super) fn start_first(commands: impl IntoIterator<Item = Command>) -> std::io::Result<Option<crate::host_services::Reaper>> {
|
||||
let mut last = std::io::Error::other("no command to start");
|
||||
for mut c in commands {
|
||||
match crate::host_services::spawn_detached(&mut c) {
|
||||
Ok(reaper) => return Ok(reaper),
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux keeps `/proc/<pid>` in state `Z` for a process that ended until its parent waits for it.
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
mod setup_tests {
|
||||
use super::system::{setup_commands, start_first};
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn printer_setup_tries_the_settings_app_then_the_cups_page() {
|
||||
let [app, page] = setup_commands(Some("Office Laser"));
|
||||
assert_eq!(app.get_program(), "system-config-printer");
|
||||
assert_eq!(app.get_args().count(), 0);
|
||||
assert_eq!(page.get_program(), "xdg-open");
|
||||
assert_eq!(page.get_args().collect::<Vec<_>>(), ["http://localhost:631/printers/Office Laser"]);
|
||||
let [_, list] = setup_commands(None);
|
||||
assert_eq!(list.get_args().collect::<Vec<_>>(), ["http://localhost:631/printers/"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_fallback_is_reaped_once_it_ends() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let mut fallback = Command::new("sh");
|
||||
fallback.arg("-c").arg("echo $$ > \"$1\"; exit 3").arg("sh").arg(&pid_file);
|
||||
let reaper = start_first([Command::new("vectorcraft-no-such-program"), fallback]).unwrap().expect("a reaper on Linux");
|
||||
let status = reaper.join().unwrap().unwrap();
|
||||
assert_eq!(status.code(), Some(3), "the fallback ran after the missing program");
|
||||
let pid = std::fs::read_to_string(&pid_file).unwrap();
|
||||
let pid = pid.trim();
|
||||
assert!(!pid.is_empty(), "the process wrote its pid");
|
||||
let state = std::fs::read_to_string(format!("/proc/{pid}/stat"))
|
||||
.ok()
|
||||
.and_then(|s| s.rsplit_once(") ").and_then(|(_, rest)| rest.split(' ').next().map(str::to_string)));
|
||||
assert_ne!(state.as_deref(), Some("Z"), "process {pid} is still a zombie");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_command_starting_the_last_error_is_returned() {
|
||||
// A missing program fails with NotFound; a directory fails with PermissionDenied.
|
||||
let err = start_first([Command::new("vectorcraft-no-such-program"), Command::new("/")]).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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::<String>::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::UiState> {
|
||||
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The desktop's monitors for window and popup placement: where each one is, its size and scale, and on Windows the
|
||||
//! part the taskbar leaves free.
|
||||
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::sync::{Arc, Mutex, PoisonError, Weak};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft::behavior::{Monitor, MonitorKey};
|
||||
use craft::window::system::{HeldButtons, WindowSystem};
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::windows_stylus::ContactWindows;
|
||||
|
||||
/// How long one listing of the monitors is used. Placement asks for the monitors several times a frame; a display
|
||||
/// that is added, removed or moved shows up in the first listing after this.
|
||||
const RELIST_AFTER: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The monitors in physical desktop pixels, and the index of the one showing `window` (else the primary one).
|
||||
/// `None` when winit stops on a display that went away while it was being listed (Windows).
|
||||
pub(super) fn monitor_layout(window: &Window) -> Option<(Vec<Monitor>, Option<usize>)> {
|
||||
let listing = std::panic::catch_unwind(AssertUnwindSafe(|| {
|
||||
let handles: Vec<_> = window.available_monitors().collect();
|
||||
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
|
||||
let monitors = handles
|
||||
.iter()
|
||||
.map(|handle| {
|
||||
let size = handle.size();
|
||||
let size = [size.width, size.height];
|
||||
let position = handle.position();
|
||||
let monitor = Monitor::new(
|
||||
MonitorKey::new(handle.name().unwrap_or_default(), size),
|
||||
[position.x, position.y],
|
||||
size,
|
||||
handle.scale_factor() as f32,
|
||||
);
|
||||
match work_px(&monitor) {
|
||||
Some((pos, size)) => monitor.with_work_px(pos, size),
|
||||
None => monitor,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(monitors, home)
|
||||
}));
|
||||
listing.map_err(|_| log::debug!("a display went away while the monitors were listed")).ok()
|
||||
}
|
||||
|
||||
/// The work area of the monitor whose top-left pixel is `monitor`'s, from `GetMonitorInfo`. winsafe comes with the
|
||||
/// wgpu renderer, which every desktop package builds with.
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
fn work_px(monitor: &Monitor) -> Option<([i32; 2], [u32; 2])> {
|
||||
use winsafe::{HMONITOR, POINT, co};
|
||||
let [x, y] = monitor.pos_px;
|
||||
let info = HMONITOR::MonitorFromPoint(POINT { x, y }, co::MONITOR::DEFAULTTONULL).GetMonitorInfo().ok()?;
|
||||
let work = info.rcWork;
|
||||
from_edges(work.left, work.top, work.right, work.bottom)
|
||||
}
|
||||
|
||||
/// Other platforms report no work area.
|
||||
#[cfg(not(all(windows, feature = "wgpu")))]
|
||||
fn work_px(_: &Monitor) -> Option<([i32; 2], [u32; 2])> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The top-left corner and size of the pixel rectangle with these edges; `None` for an empty or inverted one.
|
||||
#[cfg(any(all(windows, feature = "wgpu"), test))]
|
||||
fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2], [u32; 2])> {
|
||||
let width = u32::try_from(right.checked_sub(left)?).ok().filter(|w| *w > 0)?;
|
||||
let height = u32::try_from(bottom.checked_sub(top)?).ok().filter(|h| *h > 0)?;
|
||||
Some(([left, top], [width, height]))
|
||||
}
|
||||
|
||||
/// The platform's window services with a pen or a finger in contact counted as the primary button
|
||||
/// ([`ContactWindows`]), and the monitors listed through winit. On macOS no monitors are listed: winit
|
||||
/// gives each display's position in that display's own scale, so the pixel areas of displays with different scales
|
||||
/// overlap and placement could pick the wrong one. Elsewhere monitors with different scales are not listed either
|
||||
/// ([`one_scale`]).
|
||||
pub(super) struct DesktopWindows {
|
||||
list: Box<dyn Fn() -> Option<Vec<Monitor>> + Send + Sync>,
|
||||
now: Box<dyn Fn() -> Instant + Send + Sync>,
|
||||
/// The last listing that succeeded, and when it was made.
|
||||
listed: Mutex<Option<(Instant, Vec<Monitor>)>>,
|
||||
}
|
||||
|
||||
impl DesktopWindows {
|
||||
/// Lists the monitors of `window`'s desktop; none without a window, and none on macOS.
|
||||
pub(super) fn new(window: Option<&Arc<Window>>) -> Self {
|
||||
let window = if cfg!(target_os = "macos") { Weak::new() } else { window.map_or_else(Weak::new, Arc::downgrade) };
|
||||
Self::with(move || window.upgrade().and_then(|window| monitor_layout(&window)).map(|(monitors, _)| monitors), Instant::now)
|
||||
}
|
||||
|
||||
/// Lists the monitors with `list` (`None` when a listing fails), timed by `now`.
|
||||
fn with(list: impl Fn() -> Option<Vec<Monitor>> + Send + Sync + 'static, now: impl Fn() -> Instant + Send + Sync + 'static) -> Self {
|
||||
Self { list: Box::new(list), now: Box::new(now), listed: Mutex::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowSystem for DesktopWindows {
|
||||
fn desktop_pointer(&self) -> Option<[f32; 2]> {
|
||||
ContactWindows.desktop_pointer()
|
||||
}
|
||||
|
||||
fn buttons_held(&self) -> Option<HeldButtons> {
|
||||
ContactWindows.buttons_held()
|
||||
}
|
||||
|
||||
fn discard_marked_text(&self) -> bool {
|
||||
ContactWindows.discard_marked_text()
|
||||
}
|
||||
|
||||
fn command_held(&self) -> Option<bool> {
|
||||
ContactWindows.command_held()
|
||||
}
|
||||
|
||||
fn warp_pointer(&self, to: [f32; 2]) -> bool {
|
||||
ContactWindows.warp_pointer(to)
|
||||
}
|
||||
|
||||
/// The monitors of the last listing, listed again once [`RELIST_AFTER`] has passed. A listing that fails keeps
|
||||
/// the last one, and the next call lists again.
|
||||
fn monitors(&self) -> Vec<Monitor> {
|
||||
let now = (self.now)();
|
||||
let mut listed = self.listed.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((at, monitors)) = listed.as_ref()
|
||||
&& now.saturating_duration_since(*at) < RELIST_AFTER
|
||||
{
|
||||
return monitors.clone();
|
||||
}
|
||||
match (self.list)().map(one_scale) {
|
||||
Some(monitors) => {
|
||||
*listed = Some((now, monitors.clone()));
|
||||
monitors
|
||||
}
|
||||
None => listed.as_ref().map(|(_, monitors)| monitors.clone()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `monitors` when they all have one scale, else none. The framework finds the monitor a palette window is on by
|
||||
/// testing the window's corner, in the window's own points, at each monitor's scale, so with mixed scales a palette
|
||||
/// on one monitor can be matched to another and its popups kept in that monitor's work area. Without a listing,
|
||||
/// popups stay within the span of the app's windows and dialogs reopen where they were saved.
|
||||
fn one_scale(monitors: Vec<Monitor>) -> Vec<Monitor> {
|
||||
let mixed = monitors.windows(2).any(|pair| pair[0].scale != pair[1].scale);
|
||||
if mixed { Vec::new() } else { monitors }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft::behavior::placement::{Defaults, Placement, place};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn monitor(name: &str, pos: [i32; 2], size: [u32; 2], scale: f32) -> Monitor {
|
||||
Monitor::new(MonitorKey::new(name, size), pos, size, scale)
|
||||
}
|
||||
|
||||
/// A clock the test moves.
|
||||
fn clock() -> (Arc<Mutex<Instant>>, impl Fn() -> Instant + Send + Sync + 'static) {
|
||||
let time = Arc::new(Mutex::new(Instant::now()));
|
||||
let read = Arc::clone(&time);
|
||||
(time, move || *read.lock().unwrap())
|
||||
}
|
||||
|
||||
fn advance(time: &Mutex<Instant>, by: Duration) {
|
||||
let mut now = time.lock().unwrap();
|
||||
*now += by;
|
||||
}
|
||||
|
||||
/// The monitors come from the desktop listing, which runs once per [`RELIST_AFTER`] however often placement asks,
|
||||
/// and a display that changed shows up in the next listing.
|
||||
#[test]
|
||||
fn monitors_are_listed_once_a_second_and_follow_display_changes() {
|
||||
let listings = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&listings);
|
||||
let (time, now) = clock();
|
||||
let system = DesktopWindows::with(
|
||||
move || {
|
||||
let n = count.fetch_add(1, Ordering::SeqCst);
|
||||
let mut monitors = vec![monitor("A", [0, 0], [1920, 1080], 1.0)];
|
||||
if n > 0 {
|
||||
monitors.push(monitor("B", [1920, 0], [2560, 1440], 1.0));
|
||||
}
|
||||
Some(monitors)
|
||||
},
|
||||
now,
|
||||
);
|
||||
let names = |monitors: Vec<Monitor>| monitors.into_iter().map(|m| m.key.name).collect::<Vec<_>>();
|
||||
assert_eq!(names(system.monitors()), ["A"]);
|
||||
assert_eq!(names(system.monitors()), ["A"]);
|
||||
advance(&time, RELIST_AFTER - Duration::from_millis(1));
|
||||
assert_eq!(names(system.monitors()), ["A"]);
|
||||
assert_eq!(listings.load(Ordering::SeqCst), 1, "calls within the reuse time share one listing");
|
||||
advance(&time, Duration::from_millis(1));
|
||||
assert_eq!(names(system.monitors()), ["A", "B"], "the added display shows up in the next listing");
|
||||
assert_eq!(listings.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// A listing that fails (a display went away while it was listed) keeps the last monitors, and the next call
|
||||
/// lists again instead of waiting for the reuse time.
|
||||
#[test]
|
||||
fn a_failed_listing_keeps_the_last_monitors() {
|
||||
let listings = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&listings);
|
||||
let (time, now) = clock();
|
||||
let system =
|
||||
DesktopWindows::with(move || (count.fetch_add(1, Ordering::SeqCst) == 0).then(|| vec![monitor("A", [0, 0], [1920, 1080], 1.0)]), now);
|
||||
assert_eq!(system.monitors().len(), 1);
|
||||
advance(&time, RELIST_AFTER);
|
||||
assert_eq!(system.monitors().len(), 1, "the failed listing keeps the last one");
|
||||
assert_eq!(system.monitors().len(), 1);
|
||||
assert_eq!(listings.load(Ordering::SeqCst), 3, "each call after a failed listing lists again");
|
||||
}
|
||||
|
||||
/// A dialog saved on a monitor that is no longer connected (or at a place no monitor shows) reopens with its whole
|
||||
/// frame inside a connected monitor's work area, clear of the taskbar.
|
||||
#[test]
|
||||
fn a_dialog_saved_off_every_monitor_opens_inside_a_work_area() {
|
||||
let (_, now) = clock();
|
||||
let system = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0).with_work_px([0, 0], [1920, 1040])]), now);
|
||||
let mut saved = Placement::new([600.0, 400.0], 1.0);
|
||||
saved.position_px = Some([3000, 900]);
|
||||
let placed = place(Some(&saved), &system.monitors(), None, &Defaults::new([600.0, 400.0], [200.0, 100.0]));
|
||||
let [x, y] = placed.position_px.expect("the dialog keeps a position");
|
||||
let [width, height] = placed.normal.size;
|
||||
let frame = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width, height));
|
||||
let work = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1920.0, 1040.0));
|
||||
assert!(work.contains_rect(frame), "{frame:?} is inside {work:?}");
|
||||
}
|
||||
|
||||
/// Monitors with different scales are not listed, so a palette's popups on a scale-2 monitor beside a scale-1 one
|
||||
/// are not kept in the other monitor's work area; monitors that share a scale are listed.
|
||||
#[test]
|
||||
fn monitors_with_mixed_scales_are_not_listed() {
|
||||
let (_, now) = clock();
|
||||
let mixed = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0), monitor("B", [1920, 0], [3840, 2160], 2.0)]), now);
|
||||
assert!(mixed.monitors().is_empty(), "mixed scales list no monitors");
|
||||
let (_, now) = clock();
|
||||
let shared = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [3840, 2160], 1.5), monitor("B", [3840, 0], [3840, 2160], 1.5)]), now);
|
||||
assert_eq!(shared.monitors().len(), 2, "one scale lists every monitor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_area_edges_give_corner_and_size() {
|
||||
assert_eq!(from_edges(-1920, -200, 0, 840), Some(([-1920, -200], [1920, 1040])));
|
||||
assert_eq!(from_edges(0, 0, 0, 1040), None, "no width");
|
||||
assert_eq!(from_edges(100, 0, 0, 1040), None, "inverted");
|
||||
assert_eq!(from_edges(i32::MIN, 0, i32::MAX, 10), None, "overflowing width");
|
||||
}
|
||||
}
|
||||
@@ -28,13 +28,20 @@
|
||||
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
|
||||
//! comes from the tablet driver's Wintab interface instead, when it has one
|
||||
//! ([`crate::windows_wintab`]).
|
||||
//!
|
||||
//! The window host reads the mouse buttons Windows reports down ([`ContactWindows`]) to release a
|
||||
//! press whose release the window never received. A pen or a finger in contact is not a mouse
|
||||
//! button there, so [`msg_hook`] also notes each pointer in contact, and [`ContactWindows`] reports
|
||||
//! the primary button down while one is. Otherwise the press of a pen stroke is released on its
|
||||
//! first move.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
|
||||
use craft::behavior::PointerSample;
|
||||
use craft::behavior::{Monitor, PointerSample};
|
||||
use craft::ui::runtime::pen::PenSource;
|
||||
use craft::window::system::{HeldButtons, SystemWindows, WindowSystem};
|
||||
|
||||
/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
|
||||
/// `wParam`, a pen in contact with its barrel button pressed.
|
||||
@@ -44,6 +51,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
|
||||
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
|
||||
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
|
||||
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
|
||||
/// `POINTER_MESSAGE_FLAG_INCONTACT` (`winuser.h`): a pen or a finger touching the surface.
|
||||
const POINTER_MESSAGE_FLAG_INCONTACT: usize = 0x0004;
|
||||
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
|
||||
const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
@@ -67,6 +76,8 @@ const WM_POINTERDOWN: u32 = 0x0246;
|
||||
const WM_POINTERUP: u32 = 0x0247;
|
||||
const WM_POINTERENTER: u32 = 0x0249;
|
||||
const WM_POINTERLEAVE: u32 = 0x024A;
|
||||
/// `WM_POINTERCAPTURECHANGED` (`winuser.h`): another window took the pointer's capture.
|
||||
const WM_POINTERCAPTURECHANGED: u32 = 0x024C;
|
||||
|
||||
/// A pen's tilt along x and y and its barrel rotation, in radians.
|
||||
type Pose = ([f32; 2], f32);
|
||||
@@ -81,6 +92,84 @@ thread_local! {
|
||||
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
|
||||
static FEED: OnceLock<PenSource> = OnceLock::new();
|
||||
|
||||
/// The ids of the pointers in contact (pens and fingers), from [`msg_hook`].
|
||||
static CONTACTS: Mutex<Vec<u32>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The running platform's window services ([`SystemWindows`]), with the primary button reported
|
||||
/// down while a pen or a finger is in contact.
|
||||
pub struct ContactWindows;
|
||||
|
||||
impl WindowSystem for ContactWindows {
|
||||
fn desktop_pointer(&self) -> Option<[f32; 2]> {
|
||||
SystemWindows.desktop_pointer()
|
||||
}
|
||||
|
||||
fn buttons_held(&self) -> Option<HeldButtons> {
|
||||
let in_contact = !CONTACTS.lock().unwrap_or_else(PoisonError::into_inner).is_empty();
|
||||
with_contact(SystemWindows.buttons_held(), in_contact)
|
||||
}
|
||||
|
||||
fn discard_marked_text(&self) -> bool {
|
||||
SystemWindows.discard_marked_text()
|
||||
}
|
||||
|
||||
fn command_held(&self) -> Option<bool> {
|
||||
SystemWindows.command_held()
|
||||
}
|
||||
|
||||
fn warp_pointer(&self, to: [f32; 2]) -> bool {
|
||||
SystemWindows.warp_pointer(to)
|
||||
}
|
||||
|
||||
fn monitors(&self) -> Vec<Monitor> {
|
||||
SystemWindows.monitors()
|
||||
}
|
||||
}
|
||||
|
||||
/// The buttons `held` with the primary one added while a pointer is `in_contact`; `None` where the
|
||||
/// platform tells nothing.
|
||||
fn with_contact(held: Option<HeldButtons>, in_contact: bool) -> Option<HeldButtons> {
|
||||
held.map(|mut held| {
|
||||
if in_contact {
|
||||
held.insert(HeldButtons::PRIMARY);
|
||||
}
|
||||
held
|
||||
})
|
||||
}
|
||||
|
||||
/// The pointer a message with this `wParam` is about, and whether it is now in contact: a pointer
|
||||
/// that goes down or moves with `POINTER_MESSAGE_FLAG_INCONTACT` and no cancel is; one that hovers,
|
||||
/// is canceled, goes up, leaves or loses its capture to another window is not. `None` for any other
|
||||
/// message.
|
||||
fn contact_update(message: u32, wparam: usize) -> Option<(u32, bool)> {
|
||||
let id = (wparam & 0xffff) as u32;
|
||||
let flags = wparam >> 16;
|
||||
match message {
|
||||
WM_POINTERDOWN | WM_POINTERUPDATE => Some((id, flags & POINTER_MESSAGE_FLAG_INCONTACT != 0 && flags & POINTER_MESSAGE_FLAG_CANCELED == 0)),
|
||||
WM_POINTERUP | WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED => Some((id, false)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes in `contacts` the pointer that a message with this `wParam` puts in or out of contact
|
||||
/// ([`contact_update`]). A mouse message that a mouse made (`from_mouse`) ends every contact, so a
|
||||
/// contact whose end went to another window does not hold the primary button for the mouse.
|
||||
/// A pointer goes into contact only when `watched` returns true: the thread's hook that sees its
|
||||
/// sent leave and capture change is installed. Otherwise a later message of the contact tries
|
||||
/// again. Returns whether the message put a pointer in contact.
|
||||
fn follow_contact(contacts: &mut Vec<u32>, message: u32, wparam: usize, from_mouse: impl FnOnce() -> bool, watched: impl FnOnce() -> bool) -> bool {
|
||||
match contact_update(message, wparam) {
|
||||
Some((id, true)) if !contacts.contains(&id) && watched() => {
|
||||
contacts.push(id);
|
||||
return true;
|
||||
}
|
||||
Some((id, false)) => contacts.retain(|c| *c != id),
|
||||
None if MOUSE_MESSAGES.contains(&message) && !contacts.is_empty() && from_mouse() => contacts.clear(),
|
||||
_ => {}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The canvas's pen source, which [`msg_hook`] writes before winit handles each message.
|
||||
pub fn start() -> PenSource {
|
||||
FEED.get_or_init(PenSource::default).clone()
|
||||
@@ -99,6 +188,12 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
let Some(msg) = (unsafe { msg.cast::<MSG>().as_ref() }) else {
|
||||
return false;
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
// The contact's sent leave and capture change come through the thread's hook, so a contact is
|
||||
// noted only once the hook is installed.
|
||||
let watched = || crate::windows_wintab::hook_sent_messages(msg.time);
|
||||
follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), msg.message, msg.wParam.0, from_mouse, watched);
|
||||
let Some(pen) = FEED.get() else {
|
||||
return false;
|
||||
};
|
||||
@@ -119,8 +214,6 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) {
|
||||
// The barrel goes first: the contact's press reads it with the sample.
|
||||
pen.set_barrel(sample.is_some() && (msg.wParam.0 >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0);
|
||||
@@ -130,14 +223,15 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
}
|
||||
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// reports: the pressure it reports, 0 included, which a pen in contact can report as its tip touches
|
||||
/// down and lifts (#10231), 0 while it hovers, and a full press for a pen in contact that reports
|
||||
/// none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
|
||||
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
|
||||
/// within 0..1 and none when it is not a number.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
0..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
@@ -187,9 +281,13 @@ fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
|
||||
|
||||
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
|
||||
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
|
||||
/// [`msg_hook`] does for the messages it sees.
|
||||
/// [`msg_hook`] does for the messages it sees, and a pointer that leaves it or loses its capture is
|
||||
/// no longer in contact.
|
||||
#[cfg(windows)]
|
||||
pub fn sent_message(message: u32, wparam: usize) {
|
||||
if matches!(message, WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED) {
|
||||
follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), message, wparam, || false, || true);
|
||||
}
|
||||
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
|
||||
crate::windows_wintab::forget();
|
||||
}
|
||||
@@ -318,16 +416,86 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
fn a_pen_that_reports_pressure_keeps_zero_at_the_ends_of_a_stroke() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(
|
||||
pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure,
|
||||
0.0,
|
||||
"a tip that touches down or lifts with no pressure does not press fully"
|
||||
);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_ERASER, true, UPRIGHT, None), eraser_sample(0.0), "the eraser end too");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pointer_in_contact_holds_the_primary_button() {
|
||||
assert_eq!(with_contact(Some(HeldButtons::NONE), true), Some(HeldButtons::PRIMARY), "a pen stroke while no mouse button is down");
|
||||
assert_eq!(with_contact(Some(HeldButtons::NONE), false), Some(HeldButtons::NONE));
|
||||
let held = with_contact(Some(HeldButtons::SECONDARY), true).unwrap_or_default();
|
||||
assert!(held.contains(HeldButtons::PRIMARY) && held.contains(HeldButtons::SECONDARY), "the mouse's own buttons stay");
|
||||
assert_eq!(with_contact(None, true), None, "a platform that tells nothing still tells nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_stroke_is_in_contact_from_its_down_to_its_up() {
|
||||
let flags = |f: usize| (f << 16) | 7;
|
||||
let touching = flags(POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT);
|
||||
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
|
||||
let follow = |contacts: &mut Vec<u32>, message: u32, wparam: usize| follow_contact(contacts, message, wparam, no_mouse, || true);
|
||||
let mut contacts = vec![];
|
||||
follow(&mut contacts, WM_POINTERUPDATE, flags(POINTER_MESSAGE_FLAG_INRANGE));
|
||||
assert!(contacts.is_empty(), "a hovering pen is in no contact");
|
||||
assert!(follow(&mut contacts, WM_POINTERDOWN, touching), "the pen goes into contact");
|
||||
assert_eq!(contacts, [7], "the pen touches down");
|
||||
assert!(!follow(&mut contacts, WM_POINTERUPDATE, touching), "it is already in contact");
|
||||
assert_eq!(contacts, [7], "and stays in contact while it moves");
|
||||
follow(&mut contacts, WM_POINTERDOWN, (POINTER_MESSAGE_FLAG_INCONTACT << 16) | 9);
|
||||
follow(&mut contacts, WM_POINTERUP, flags(POINTER_MESSAGE_FLAG_INRANGE));
|
||||
assert_eq!(contacts, [9], "the pen goes up and a finger stays down");
|
||||
follow(&mut contacts, WM_POINTERUPDATE, ((POINTER_MESSAGE_FLAG_INCONTACT | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 9);
|
||||
assert!(contacts.is_empty(), "a canceled contact ends");
|
||||
follow(&mut contacts, WM_POINTERDOWN, touching);
|
||||
follow(&mut contacts, WM_POINTERLEAVE, 7);
|
||||
assert!(contacts.is_empty(), "a pointer that leaves the window ends its contact");
|
||||
follow(&mut contacts, WM_POINTERDOWN, touching);
|
||||
follow(&mut contacts, WM_POINTERCAPTURECHANGED, 7);
|
||||
assert!(contacts.is_empty(), "a pointer whose capture another window took ends its contact");
|
||||
|
||||
// WM_LBUTTONDOWN.
|
||||
follow(&mut contacts, WM_POINTERDOWN, touching);
|
||||
follow_contact(&mut contacts, 0x0201, 0, || false, || true);
|
||||
assert_eq!(contacts, [7], "a mouse message Windows made from the pen keeps the contact");
|
||||
follow_contact(&mut contacts, 0x0201, 0, || true, || true);
|
||||
assert!(contacts.is_empty(), "a press of the mouse ends a contact whose end never arrived");
|
||||
// WM_KEYDOWN.
|
||||
follow(&mut contacts, WM_POINTERDOWN, touching);
|
||||
follow_contact(&mut contacts, 0x0100, 0, || -> bool { panic!("not a mouse message") }, || true);
|
||||
assert_eq!(contacts, [7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_contact_is_noted_only_while_its_end_can_arrive() {
|
||||
let touching = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT) << 16) | 7;
|
||||
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
|
||||
let mut contacts = vec![];
|
||||
assert!(!follow_contact(&mut contacts, WM_POINTERDOWN, touching, no_mouse, || false), "the hook did not install");
|
||||
assert!(contacts.is_empty(), "a contact whose leave could not arrive is not noted");
|
||||
assert!(follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || true), "the next move tries again");
|
||||
assert_eq!(contacts, [7]);
|
||||
let asked = std::cell::Cell::new(false);
|
||||
follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || {
|
||||
asked.set(true);
|
||||
true
|
||||
});
|
||||
assert!(!asked.get(), "a pointer already in contact does not install the hook again");
|
||||
follow_contact(&mut contacts, WM_POINTERUP, 7, no_mouse, || -> bool { panic!("an up is not a contact") });
|
||||
assert!(contacts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mouse_messages_from_a_pen_or_a_touch_are_told_apart() {
|
||||
assert!(is_mouse(0), "a mouse");
|
||||
|
||||
@@ -625,7 +625,7 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen};
|
||||
pub use win::{forget, hook_sent_messages, msg_hook, pen_wheel, set_wheel_used, wheel_pen};
|
||||
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
@@ -758,8 +758,9 @@ mod win {
|
||||
/// The thread's hook on the messages Windows sends to its windows' procedures, which winit's
|
||||
/// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a
|
||||
/// top-level window of the app, <https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-activateapp>)
|
||||
/// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE`
|
||||
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>) go to
|
||||
/// closes the context ([`deactivate`]), and a pointer's `WM_POINTERENTER`, `WM_POINTERLEAVE`
|
||||
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>) and
|
||||
/// `WM_POINTERCAPTURECHANGED` go to
|
||||
/// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows
|
||||
/// they are sent to (<https://learn.microsoft.com/en-us/windows/win32/winmsg/callwndproc>).
|
||||
unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
@@ -1089,6 +1090,13 @@ mod win {
|
||||
settle();
|
||||
}
|
||||
|
||||
/// Installs [`call_wnd_proc`] for a pointer that went into contact at the message time `time`,
|
||||
/// so the pointer's sent `WM_POINTERLEAVE` and `WM_POINTERCAPTURECHANGED` reach
|
||||
/// [`crate::windows_stylus::sent_message`] whether or not a context opens ([`hook_thread`]).
|
||||
pub fn hook_sent_messages(time: u32) -> bool {
|
||||
hook_thread(time)
|
||||
}
|
||||
|
||||
/// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer
|
||||
/// id `pen` ([`Readings::owner_or`]).
|
||||
pub fn wheel_pen(pen: u32) -> u32 {
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
//! Block definitions and INSERT entities for the DXF writer.
|
||||
//!
|
||||
//! Temporary: `craft_dxf::drawing` at the pinned craft-libs revision writes only the model and
|
||||
//! paper space blocks. storytold/craft-libs#5381 adds `Block`, `Drawing::blocks` and
|
||||
//! `Codes::insert`; once it merges and the pin moves past it, this module is removed and
|
||||
//! `scene.rs` uses those instead. Until then [`write`] adds the user blocks to the file that
|
||||
//! `Drawing::write` returns, with the same group codes #5381 writes.
|
||||
|
||||
use craft_dxf::drawing::{Codes, Drawing, Handle, fixed};
|
||||
|
||||
/// A block definition: entities written once, which INSERT entities place ([`insert`]). Its base
|
||||
/// point is the origin.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Block {
|
||||
pub name: String,
|
||||
/// The handle of its BLOCK_RECORD (from R13), which owns its entities.
|
||||
pub record: Handle,
|
||||
/// The handles of its BLOCK and ENDBLK records.
|
||||
pub begin: Handle,
|
||||
pub end: Handle,
|
||||
/// The entities' group codes, written with `record` as their owner.
|
||||
pub entities: String,
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(c: &mut Codes, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
c.raw(0, kind);
|
||||
if c.v.handles() {
|
||||
c.handle(5, h);
|
||||
c.handle(330, owner);
|
||||
c.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// An INSERT entity owned by `owner` on `layer` that places block `block` at the origin, unscaled
|
||||
/// and unrotated. It has no color of its own (ByLayer).
|
||||
pub fn insert(c: &mut Codes, h: Handle, owner: Handle, layer: &str, block: &str) {
|
||||
object(c, "INSERT", h, owner, "AcDbEntity");
|
||||
c.str(8, layer);
|
||||
if c.v.handles() {
|
||||
c.raw(100, "AcDbBlockReference");
|
||||
}
|
||||
c.str(2, block);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
}
|
||||
|
||||
/// The whole file of `d` with `blocks` written after the model and paper space blocks.
|
||||
pub fn write(d: Drawing, blocks: &[Block]) -> String {
|
||||
let v = d.version;
|
||||
let out = d.write();
|
||||
if blocks.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let mut defs = Codes::new(v);
|
||||
for b in blocks {
|
||||
object(&mut defs, "BLOCK", b.begin, b.record, "AcDbEntity");
|
||||
defs.raw(8, "0");
|
||||
if v.handles() {
|
||||
defs.raw(100, "AcDbBlockBegin");
|
||||
}
|
||||
defs.str(2, &b.name);
|
||||
defs.int(70, 0);
|
||||
defs.xyz(10, 0.0, 0.0);
|
||||
defs.str(3, &b.name);
|
||||
defs.raw(1, "");
|
||||
defs.append(&b.entities);
|
||||
object(&mut defs, "ENDBLK", b.end, b.record, "AcDbEntity");
|
||||
defs.raw(8, "0");
|
||||
if v.handles() {
|
||||
defs.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
}
|
||||
let defs = defs.into_string();
|
||||
if !v.handles() {
|
||||
// R12 has no model and paper space blocks: its BLOCKS section holds the user blocks only.
|
||||
let at = " 0\nSECTION\n 2\nENTITIES\n";
|
||||
return match out.find(at) {
|
||||
Some(i) => format!("{} 0\nSECTION\n 2\nBLOCKS\n{defs} 0\nENDSEC\n{}", &out[..i], &out[i..]),
|
||||
None => out,
|
||||
};
|
||||
}
|
||||
let mut records = Codes::new(v);
|
||||
for b in blocks {
|
||||
object(&mut records, "BLOCK_RECORD", b.record, fixed::BLOCK_RECORD_TABLE, "AcDbSymbolTableRecord");
|
||||
records.raw(100, "AcDbBlockTableRecord");
|
||||
records.str(2, &b.name);
|
||||
if v.r2000() {
|
||||
records.handle(340, Handle(0));
|
||||
records.int(70, 0);
|
||||
records.int(280, 1);
|
||||
records.int(281, 0);
|
||||
}
|
||||
}
|
||||
let records = records.into_string();
|
||||
let (Some(table), Some(blocks_at)) = (out.find(" 0\nTABLE\n 2\nBLOCK_RECORD\n"), out.find(" 0\nSECTION\n 2\nBLOCKS\n")) else {
|
||||
return out;
|
||||
};
|
||||
let count = " 70\n2\n";
|
||||
let (Some(c), Some(t_end), Some(b_end)) = (
|
||||
out[table..].find(count).map(|i| table + i),
|
||||
out[table..].find(" 0\nENDTAB\n").map(|i| table + i),
|
||||
out[blocks_at..].find(" 0\nENDSEC\n").map(|i| blocks_at + i),
|
||||
) else {
|
||||
return out;
|
||||
};
|
||||
let mut s = String::with_capacity(out.len() + records.len() + defs.len());
|
||||
s.push_str(&out[..c]);
|
||||
s.push_str(&format!(" 70\n{}\n", 2 + blocks.len()));
|
||||
s.push_str(&out[c + count.len()..t_end]);
|
||||
s.push_str(&records);
|
||||
s.push_str(&out[t_end..b_end]);
|
||||
s.push_str(&defs);
|
||||
s.push_str(&out[b_end..]);
|
||||
s
|
||||
}
|
||||
@@ -245,9 +245,11 @@ fn convert(bytes: &[u8]) -> Result<Converted, String> {
|
||||
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`]
|
||||
|
||||
@@ -19,10 +19,10 @@
|
||||
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
|
||||
//! - `hatch`: pattern hatches' lines and gradient hatches' fills.
|
||||
//! - `text`: text values to plain text.
|
||||
//! - `acis`: a region's solid-modeler data as its outline.
|
||||
//! - `build`: items to the document.
|
||||
//!
|
||||
//! A region's solid-modeler data becomes its outline in `craft_dxf::acis`.
|
||||
|
||||
mod acis;
|
||||
mod build;
|
||||
mod curve;
|
||||
mod entity;
|
||||
|
||||
@@ -1,779 +0,0 @@
|
||||
//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x
|
||||
//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary
|
||||
//! (DXF 2013 and later keep it in the ACDSDATA section).
|
||||
//!
|
||||
//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a
|
||||
//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or
|
||||
//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A
|
||||
//! curve of any other kind comes in as a straight line between its vertices.
|
||||
//!
|
||||
//! The REGION groups are in the DXF Reference
|
||||
//! (<https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4>); which
|
||||
//! DXF versions hold text and which binary data is in <https://ezdxf.mozman.at/docs/acis.html>.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg};
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::curve;
|
||||
|
||||
/// The most bytes of one region's data read.
|
||||
pub(crate) const MAX_BYTES: usize = 16 << 20;
|
||||
/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges
|
||||
/// (a loop counts as one at least).
|
||||
const MAX_VISITS: usize = 1_000_000;
|
||||
/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either).
|
||||
const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"];
|
||||
/// From this version on, every record starts with its attribute, a history number and one more
|
||||
/// pointer; before it, with its attribute alone.
|
||||
const LONG_HEADER_VERSION: u32 = 700;
|
||||
|
||||
type P3 = [f64; 3];
|
||||
/// A B-spline: degree, knots, control points, weights (none: all 1).
|
||||
type Spline = (usize, Vec<f64>, Vec<P3>, Option<Vec<f64>>);
|
||||
|
||||
/// One value of a record.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Tok {
|
||||
Ptr(i64),
|
||||
Num(f64),
|
||||
Word(String),
|
||||
/// `forward` (false) or `reversed` (true).
|
||||
Sense(bool),
|
||||
Open,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record
|
||||
/// starts with.
|
||||
#[derive(Debug)]
|
||||
struct Rec {
|
||||
kind: String,
|
||||
toks: Vec<Tok>,
|
||||
}
|
||||
|
||||
impl Rec {
|
||||
/// The type `base` or one derived from it (`tedge-edge` is an edge).
|
||||
fn is(&self, base: &str) -> bool {
|
||||
self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-'))
|
||||
}
|
||||
|
||||
/// The `n`th pointer (-1: none).
|
||||
fn ptr(&self, n: usize) -> i64 {
|
||||
self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1)
|
||||
}
|
||||
|
||||
/// The sense right after the `n`th pointer: true when reversed (old files write 1).
|
||||
fn sense_after(&self, n: usize) -> Option<bool> {
|
||||
let mut ptrs = 0;
|
||||
for t in &self.toks {
|
||||
if ptrs > n {
|
||||
return match t {
|
||||
Tok::Sense(r) => Some(*r),
|
||||
Tok::Num(v) if v.is_finite() => Some(*v != 0.0),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if matches!(t, Tok::Ptr(_)) {
|
||||
ptrs += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The numbers, in order.
|
||||
fn nums(&self) -> Vec<f64> {
|
||||
self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The records of one body, and how pointers find them.
|
||||
struct Model {
|
||||
recs: Vec<Rec>,
|
||||
/// Record number by index, when the records carry their own.
|
||||
at: HashMap<i64, usize>,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
fn get(&self, p: i64) -> Option<&Rec> {
|
||||
if p < 0 {
|
||||
return None;
|
||||
}
|
||||
if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) }
|
||||
}
|
||||
|
||||
/// The record `p` points at when it is of type `base`.
|
||||
fn get_is(&self, p: i64, base: &str) -> Option<&Rec> {
|
||||
self.get(p).filter(|r| r.is(base))
|
||||
}
|
||||
|
||||
/// The records of type `base` from `first` along their `next` pointer (pointer `next`), each
|
||||
/// once. Missing records, wrong types and cycles outside coedge rings set `broken`.
|
||||
fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> {
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut p = first;
|
||||
while p >= 0 {
|
||||
if !seen.insert(p) {
|
||||
*broken |= base != "coedge";
|
||||
break;
|
||||
}
|
||||
let Some(r) = self.get_is(p, base) else {
|
||||
*broken = true;
|
||||
break;
|
||||
};
|
||||
out.push(r);
|
||||
p = r.ptr(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type
|
||||
/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks
|
||||
/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's
|
||||
/// endpoint lies on separate parts of its curve.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Outline {
|
||||
pub path: BezPath,
|
||||
pub approximated: bool,
|
||||
pub broken: bool,
|
||||
pub ambiguous: bool,
|
||||
}
|
||||
|
||||
/// Text data, ciphered as DXF writes it or not.
|
||||
pub(crate) fn from_text(text: &str) -> Option<Outline> {
|
||||
if text.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let plain;
|
||||
let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) {
|
||||
text
|
||||
} else {
|
||||
plain = decipher(text);
|
||||
&plain
|
||||
};
|
||||
outline(&sat_model(text)?)
|
||||
}
|
||||
|
||||
/// Binary data.
|
||||
pub(crate) fn from_binary(bytes: &[u8]) -> Option<Outline> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
outline(&sab_model(bytes)?)
|
||||
}
|
||||
|
||||
/// DXF's cipher of text data undone: each printable character is mapped back, and the space
|
||||
/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped.
|
||||
fn decipher(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
out.push(match c {
|
||||
' ' | '\n' | '\r' | '\t' => c,
|
||||
'@'..='_' => char::from(159 - c as u8),
|
||||
c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F),
|
||||
c => c,
|
||||
});
|
||||
if c == '^' && chars.peek() == Some(&' ') {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many values every record starts with in data of `version`.
|
||||
fn header_len(version: u32) -> usize {
|
||||
if version >= LONG_HEADER_VERSION { 3 } else { 1 }
|
||||
}
|
||||
|
||||
/// A text value as a value.
|
||||
fn sat_tok(w: &str) -> Tok {
|
||||
match w {
|
||||
"{" => Tok::Open,
|
||||
"}" => Tok::Close,
|
||||
"forward" | "forward_v" => Tok::Sense(false),
|
||||
"reversed" | "reversed_v" => Tok::Sense(true),
|
||||
_ => {
|
||||
if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::<i64>().ok()) {
|
||||
return Tok::Ptr(p);
|
||||
}
|
||||
match w.parse::<f64>() {
|
||||
Ok(v) if v.is_finite() => Tok::Num(v),
|
||||
_ => Tok::Word(w.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this line start a record (`[-<index>] <type> $<attribute> …`)?
|
||||
fn starts_record(line: &str) -> bool {
|
||||
let mut words = line.split_whitespace();
|
||||
let first = words.next().unwrap_or_default();
|
||||
let (kind, next) = if first.starts_with('-') && first[1..].parse::<u64>().is_ok() {
|
||||
(words.next().unwrap_or_default(), words.next().unwrap_or_default())
|
||||
} else {
|
||||
(first, words.next().unwrap_or_default())
|
||||
};
|
||||
kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$')
|
||||
}
|
||||
|
||||
/// Text data's records: a version line, product and tolerance lines, then records ending in `#`.
|
||||
fn sat_model(text: &str) -> Option<Model> {
|
||||
let version = text.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32;
|
||||
let skip = header_len(version);
|
||||
let mut offset = text.find('\n')? + 1;
|
||||
let start = loop {
|
||||
let rest = text.get(offset..)?;
|
||||
let line = rest.split('\n').next().unwrap_or_default();
|
||||
if starts_record(line) {
|
||||
break offset;
|
||||
}
|
||||
offset += line.len() + 1;
|
||||
};
|
||||
let body = text.get(start..)?;
|
||||
let (mut recs, mut at) = (Vec::new(), HashMap::new());
|
||||
let mut cur: Vec<Tok> = vec![];
|
||||
let (mut kind, mut index): (Option<String>, Option<i64>) = (None, None);
|
||||
let mut i = 0;
|
||||
let b = body.as_bytes();
|
||||
while i < b.len() {
|
||||
if b[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n);
|
||||
let word = body.get(i..end)?;
|
||||
i = end;
|
||||
// A counted string: `@<n>`, a space, then n bytes.
|
||||
if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::<usize>().ok()) {
|
||||
let from = (i + 1).min(b.len());
|
||||
let to = from.checked_add(n)?.min(b.len());
|
||||
cur.push(Tok::Word(body.get(from..to)?.to_string()));
|
||||
i = to;
|
||||
continue;
|
||||
}
|
||||
let (word, ends) = match word.strip_suffix('#') {
|
||||
Some(w) => (w, true),
|
||||
None => (word, false),
|
||||
};
|
||||
if !word.is_empty() {
|
||||
match &kind {
|
||||
None if index.is_none() && word.starts_with('-') && word[1..].parse::<i64>().is_ok() => {
|
||||
index = word[1..].parse().ok();
|
||||
}
|
||||
None => {
|
||||
if word.starts_with("End-of-") || word.starts_with("Begin-of-") {
|
||||
break;
|
||||
}
|
||||
kind = Some(word.to_string());
|
||||
}
|
||||
Some(_) => cur.push(sat_tok(word)),
|
||||
}
|
||||
}
|
||||
if ends {
|
||||
let toks = cur.split_off(skip.min(cur.len()));
|
||||
cur.clear();
|
||||
if let Some(n) = index.take() {
|
||||
at.insert(n, recs.len());
|
||||
}
|
||||
recs.push(Rec { kind: kind.take().unwrap_or_default(), toks });
|
||||
}
|
||||
}
|
||||
Some(Model { recs, at })
|
||||
}
|
||||
|
||||
/// Reads binary data's little-endian values.
|
||||
struct Bytes<'b> {
|
||||
b: &'b [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Bytes<'_> {
|
||||
fn take(&mut self, n: usize) -> Option<&[u8]> {
|
||||
let s = self.b.get(self.i..self.i.checked_add(n)?)?;
|
||||
self.i += n;
|
||||
Some(s)
|
||||
}
|
||||
fn u8(&mut self) -> Option<u8> {
|
||||
self.take(1).map(|s| s[0])
|
||||
}
|
||||
fn i16(&mut self) -> Option<f64> {
|
||||
self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]])))
|
||||
}
|
||||
fn u16(&mut self) -> Option<usize> {
|
||||
self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]])))
|
||||
}
|
||||
fn i32(&mut self) -> Option<i32> {
|
||||
self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
fn f64(&mut self) -> Option<f64> {
|
||||
let s = self.take(8)?;
|
||||
Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
|
||||
}
|
||||
fn text(&mut self, n: usize) -> Option<String> {
|
||||
self.take(n).map(|s| String::from_utf8_lossy(s).into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary data's records: the magic, four numbers (version first), product and tolerance values,
|
||||
/// then records of tagged values, each type name made of its parts.
|
||||
fn sab_model(b: &[u8]) -> Option<Model> {
|
||||
let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 };
|
||||
let version = r.u32()?;
|
||||
r.take(12)?;
|
||||
let skip = header_len(version);
|
||||
let mut recs = vec![];
|
||||
let (mut parts, mut kind, mut cur): (Vec<String>, Option<String>, Vec<Tok>) = (vec![], None, vec![]);
|
||||
while r.i < r.b.len() {
|
||||
let tag = r.u8()?;
|
||||
let tok = match tag {
|
||||
0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))),
|
||||
0x03 => Tok::Num(r.i16()?),
|
||||
0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)),
|
||||
0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))),
|
||||
0x06 | 0x17 => Tok::Num(r.f64()?),
|
||||
0x07 => {
|
||||
let n = usize::from(r.u8()?);
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x08 => {
|
||||
let n = r.u16()?;
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x09 | 0x12 => {
|
||||
let n = usize::try_from(r.u32()?).ok()?;
|
||||
Tok::Word(r.text(n)?)
|
||||
}
|
||||
0x0A => Tok::Sense(true),
|
||||
0x0B => Tok::Sense(false),
|
||||
0x0C => Tok::Ptr(i64::from(r.i32()?)),
|
||||
0x0D | 0x0E => {
|
||||
let n = usize::from(r.u8()?);
|
||||
let name = r.text(n)?;
|
||||
if kind.is_some() {
|
||||
Tok::Word(name)
|
||||
} else {
|
||||
parts.push(name);
|
||||
if tag == 0x0D {
|
||||
let k = parts.join("-");
|
||||
parts.clear();
|
||||
if k.starts_with("End-of-") || k.starts_with("Begin-of-") {
|
||||
break;
|
||||
}
|
||||
kind = Some(k);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
0x0F => Tok::Open,
|
||||
0x10 => Tok::Close,
|
||||
0x11 => {
|
||||
if let Some(k) = kind.take() {
|
||||
let toks = cur.split_off(skip.min(cur.len()));
|
||||
recs.push(Rec { kind: k, toks });
|
||||
}
|
||||
cur.clear();
|
||||
continue;
|
||||
}
|
||||
0x13 | 0x14 => {
|
||||
for _ in 0..3 {
|
||||
cur.push(Tok::Num(r.f64()?));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
0x16 => {
|
||||
for _ in 0..2 {
|
||||
cur.push(Tok::Num(r.f64()?));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
// Values before the first record are the header's.
|
||||
if kind.is_some() {
|
||||
cur.push(tok);
|
||||
}
|
||||
}
|
||||
Some(Model { recs, at: HashMap::new() })
|
||||
}
|
||||
|
||||
/// A body's placement: `p · m · scale + t`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Xf {
|
||||
m: [P3; 3],
|
||||
scale: f64,
|
||||
t: P3,
|
||||
}
|
||||
|
||||
impl Xf {
|
||||
const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] };
|
||||
|
||||
/// A `transform` record's: nine matrix numbers row by row, the translation, the scale.
|
||||
fn read(r: &Rec) -> Option<Xf> {
|
||||
let n: Vec<f64> = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
|
||||
if n.iter().any(|v| !v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let v = |i: usize| n.get(i).copied();
|
||||
let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]);
|
||||
let scale = v(12)?;
|
||||
Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale })
|
||||
}
|
||||
|
||||
fn vector(&self, p: P3) -> P3 {
|
||||
let [a, b, c] = self.m;
|
||||
std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale)
|
||||
}
|
||||
|
||||
fn point(&self, p: P3) -> P3 {
|
||||
let v = self.vector(p);
|
||||
std::array::from_fn(|i| v[i] + self.t[i])
|
||||
}
|
||||
}
|
||||
|
||||
/// Seen from above: x and y.
|
||||
fn flat(p: P3) -> Point {
|
||||
Point::new(p[0], p[1])
|
||||
}
|
||||
|
||||
fn sub(a: P3, b: P3) -> P3 {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
|
||||
fn dot(a: P3, b: P3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
fn cross(a: P3, b: P3) -> P3 {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
fn p3(n: &[f64], i: usize) -> Option<P3> {
|
||||
Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?])
|
||||
}
|
||||
|
||||
/// Endpoints farther apart than rounding at their coordinate size allows.
|
||||
fn endpoints_apart(a: Point, b: Point) -> bool {
|
||||
a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y)))
|
||||
}
|
||||
|
||||
/// Every face's loops of every body, as one path (filled even-odd).
|
||||
fn outline(m: &Model) -> Option<Outline> {
|
||||
let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false };
|
||||
// Records visited at every level together: chains shared between records are walked again
|
||||
// each time.
|
||||
let mut visits = 0usize;
|
||||
let mut spend = |n: usize| {
|
||||
visits = visits.saturating_add(n.max(1));
|
||||
(visits <= MAX_VISITS).then_some(())
|
||||
};
|
||||
for body in m.recs.iter().filter(|r| r.is("body")) {
|
||||
spend(1)?;
|
||||
let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? };
|
||||
for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) {
|
||||
spend(1)?;
|
||||
for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) {
|
||||
let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken);
|
||||
spend(ring.len())?;
|
||||
let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1));
|
||||
o.broken |= !complete;
|
||||
let mut bp = BezPath::new();
|
||||
for c in ring {
|
||||
let edge = m.get_is(c.ptr(3), "edge")?;
|
||||
let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?;
|
||||
o.ambiguous |= ambiguous;
|
||||
if let (Some(end), Some(start)) =
|
||||
(bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point()))
|
||||
{
|
||||
o.broken |= endpoints_apart(end, start);
|
||||
}
|
||||
super::entity::append(&mut bp, &seg);
|
||||
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if !bp.elements().is_empty() {
|
||||
if complete
|
||||
&& let (Some(end), Some(start)) =
|
||||
(bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point()))
|
||||
{
|
||||
o.broken |= endpoints_apart(end, start);
|
||||
}
|
||||
// A loop of one curve ending where it starts is split in two: as one
|
||||
// segment, its start and end would become one anchor.
|
||||
if let [seg] = bp.segments().collect::<Vec<_>>()[..]
|
||||
&& !matches!(seg, PathSeg::Line(_))
|
||||
{
|
||||
let (a, b) = seg.subdivide();
|
||||
bp = BezPath::from_path_segments([a, b].into_iter());
|
||||
}
|
||||
bp.close_path();
|
||||
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
|
||||
return None;
|
||||
}
|
||||
o.path.extend(bp);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some();
|
||||
ok.then_some(o)
|
||||
}
|
||||
|
||||
/// A vertex's position.
|
||||
fn vertex(m: &Model, p: i64) -> Option<P3> {
|
||||
let v = m.get_is(p, "vertex")?;
|
||||
let n = m.get_is(v.ptr(1), "point")?.nums();
|
||||
p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite()))
|
||||
}
|
||||
|
||||
/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first
|
||||
/// point.
|
||||
fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> {
|
||||
let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?);
|
||||
let closed = edge.ptr(0) == edge.ptr(1);
|
||||
let (from, to) = if reversed { (ev, sv) } else { (sv, ev) };
|
||||
// Against the curve's own direction?
|
||||
let back = edge.sense_after(3)? != reversed;
|
||||
let drawn = match m.get(edge.ptr(3)) {
|
||||
// Only -1 means the edge has no curve.
|
||||
None => {
|
||||
*approximated |= edge.ptr(3) != -1;
|
||||
None
|
||||
}
|
||||
Some(c) if c.is("straight-curve") => None,
|
||||
Some(c) => {
|
||||
let bp = if c.is("ellipse-curve") {
|
||||
ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false))
|
||||
} else if c.is("intcurve-curve") {
|
||||
spline(c, from, to, closed, back, xf)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
*approximated |= bp.is_none();
|
||||
bp
|
||||
}
|
||||
};
|
||||
if let Some(bp) = drawn {
|
||||
return Some(bp);
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(flat(xf.point(from)));
|
||||
bp.line_to(flat(xf.point(to)));
|
||||
Some((bp, false))
|
||||
}
|
||||
|
||||
/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve
|
||||
/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal,
|
||||
/// clockwise when `back`.
|
||||
fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<BezPath> {
|
||||
let n = c.nums();
|
||||
let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?);
|
||||
let len = dot(normal, normal).sqrt();
|
||||
if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) {
|
||||
return None;
|
||||
}
|
||||
let minor = cross(normal, major).map(|v| v / len * ratio);
|
||||
let angle = |p: P3| {
|
||||
let d = sub(p, centre);
|
||||
(dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major))
|
||||
};
|
||||
let (a, b) = (angle(from), angle(to));
|
||||
let tau = std::f64::consts::TAU;
|
||||
let sweep = match (closed, back) {
|
||||
(true, false) => tau,
|
||||
(true, true) => -tau,
|
||||
(false, false) => (b - a).rem_euclid(tau),
|
||||
(false, true) => -(a - b).rem_euclid(tau),
|
||||
};
|
||||
let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor)));
|
||||
curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep)
|
||||
}
|
||||
|
||||
/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots
|
||||
/// with their multiplicities (without the end knots, or with them), the control points.
|
||||
fn bspline(toks: &[Tok]) -> Option<Spline> {
|
||||
let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?;
|
||||
let rational = match &toks[at] {
|
||||
Tok::Word(w) if w == "nurbs" => true,
|
||||
Tok::Word(w) if w == "nubs" => false,
|
||||
_ => return None,
|
||||
};
|
||||
let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None };
|
||||
let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize;
|
||||
let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize;
|
||||
let mut knots = vec![];
|
||||
let mut i = at + 4;
|
||||
for _ in 0..count {
|
||||
let (k, mult) = (num(i)?, num(i + 1)?);
|
||||
if !(mult >= 1.0 && mult <= (degree + 1) as f64) {
|
||||
return None;
|
||||
}
|
||||
knots.extend(std::iter::repeat_n(k, mult as usize));
|
||||
i += 2;
|
||||
}
|
||||
let stride = if rational { 4 } else { 3 };
|
||||
let values: Vec<f64> = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
|
||||
let available = values.len() / stride;
|
||||
// The data leaves out the first and last knots; data that keeps them has two points fewer.
|
||||
let short = (knots.len() + 1).checked_sub(degree)?;
|
||||
let n = if available >= short {
|
||||
let (first, last) = (*knots.first()?, *knots.last()?);
|
||||
knots.insert(0, first);
|
||||
knots.push(last);
|
||||
short
|
||||
} else {
|
||||
knots.len().checked_sub(degree + 1)?
|
||||
};
|
||||
if n == 0 || n > available {
|
||||
return None;
|
||||
}
|
||||
let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect();
|
||||
let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect());
|
||||
Some((degree, knots, pts, weights))
|
||||
}
|
||||
|
||||
/// The distinct parameters of a cubic's self-intersection, when both lie on the curve.
|
||||
fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> {
|
||||
let b = (cubic.p1 - cubic.p0) * 3.0;
|
||||
let c = (cubic.p2 - cubic.p1) * 3.0 - b;
|
||||
let d = (cubic.p3 - cubic.p0) - b - c;
|
||||
let det = c.cross(d);
|
||||
if det == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0,
|
||||
// where u = s + t and v = s*t.
|
||||
let u = -b.cross(d) / det;
|
||||
let v = u * u - b.cross(c) / det;
|
||||
let discriminant = u * u - 4.0 * v;
|
||||
if !discriminant.is_finite() || discriminant <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let root = discriminant.sqrt();
|
||||
let (s, t) = ((u - root) * 0.5, (u + root) * 0.5);
|
||||
(0.0 <= s && s < t && t <= 1.0).then_some((s, t))
|
||||
}
|
||||
|
||||
/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole
|
||||
/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous.
|
||||
fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> {
|
||||
// The curve's own sense comes before its data.
|
||||
let open = c.toks.iter().position(|t| *t == Tok::Open)?;
|
||||
let curve_back = c.toks[..open].contains(&Tok::Sense(true));
|
||||
let (degree, knots, pts, weights) = bspline(&c.toks[open..])?;
|
||||
let ctrl: Vec<Point> = pts.into_iter().map(|p| flat(xf.point(p))).collect();
|
||||
let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?;
|
||||
let back = back != curve_back;
|
||||
let segs: Vec<PathSeg> = full.segments().collect();
|
||||
let (first, last) = (segs.first()?.start(), segs.last()?.end());
|
||||
let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot());
|
||||
let mut lengths = vec![0.0];
|
||||
for s in &segs {
|
||||
lengths.push(lengths.last()? + s.arclen(1e-9));
|
||||
}
|
||||
let total = *lengths.last()?;
|
||||
let at = |p: P3| {
|
||||
let p = flat(xf.point(p));
|
||||
let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect();
|
||||
let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?;
|
||||
let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9);
|
||||
let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y));
|
||||
let mut locations: Vec<_> =
|
||||
near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect();
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
if let PathSeg::Cubic(cubic) = s
|
||||
&& let Some((a, b)) = cubic_crossing(*cubic)
|
||||
&& !endpoints_apart(p, cubic.eval(a))
|
||||
{
|
||||
locations.extend([a, b].map(|t| (i as f64 + t, along(i, t))));
|
||||
}
|
||||
}
|
||||
// Nearby ends at a segment joint, or at a closed curve's seam, are one location.
|
||||
locations.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance);
|
||||
if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance {
|
||||
locations.pop();
|
||||
}
|
||||
Some((*i as f64 + n.t, locations))
|
||||
};
|
||||
let mut ambiguous = false;
|
||||
let part = if closed && ring {
|
||||
let (_, locations) = at(from)?;
|
||||
ambiguous = locations.len() > 1;
|
||||
full
|
||||
} else {
|
||||
let bounds = if closed {
|
||||
let (_, locations) = at(from)?;
|
||||
if let [a, b] = locations.as_slice() {
|
||||
Some((a.0, b.0))
|
||||
} else {
|
||||
ambiguous = true;
|
||||
None
|
||||
}
|
||||
} else {
|
||||
let ((ga, a), (gb, b)) = (at(from)?, at(to)?);
|
||||
ambiguous = a.len() > 1 || b.len() > 1;
|
||||
Some((ga, gb))
|
||||
};
|
||||
if let Some((ga, gb)) = bounds {
|
||||
let (lo, hi) = if back { (gb, ga) } else { (ga, gb) };
|
||||
let pieces = if lo <= hi || !ring {
|
||||
piece(&segs, lo.min(hi), hi.max(lo))
|
||||
} else {
|
||||
[piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat()
|
||||
};
|
||||
if pieces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
BezPath::from_path_segments(pieces.into_iter())
|
||||
} else {
|
||||
full
|
||||
}
|
||||
};
|
||||
Some((if back { part.reverse_subpaths() } else { part }, ambiguous))
|
||||
}
|
||||
|
||||
/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third).
|
||||
fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec<PathSeg> {
|
||||
let mut out = vec![];
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0));
|
||||
if t1 > t0 {
|
||||
out.push(s.subsegment(t0..t1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cubic_crossings_have_two_distinct_parameters() {
|
||||
let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0));
|
||||
let (s, t) = cubic_crossing(cubic).unwrap();
|
||||
assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}");
|
||||
let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0));
|
||||
assert!(cubic_crossing(plain).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deciphering_maps_each_character_back_and_drops_the_caret_space() {
|
||||
// "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|.
|
||||
assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#");
|
||||
}
|
||||
}
|
||||
+597
-30
@@ -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<String>,
|
||||
}
|
||||
|
||||
/// 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<u32>, Vec<Rc<str>>);
|
||||
|
||||
/// A shape check's block, its levels to the nesting limit and the ancestors it holds for.
|
||||
type ShapeKey = (Rc<str>, u32, Vec<Rc<str>>);
|
||||
|
||||
/// The blocks a block places within some levels (`None`: the shape checks' budgets ran out).
|
||||
type Reach = Option<Rc<HashSet<String>>>;
|
||||
|
||||
/// 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<Vec<String>>);
|
||||
|
||||
/// 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<String>,
|
||||
left_out: HashSet<String>,
|
||||
}
|
||||
|
||||
/// 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<ScanHere>),
|
||||
}
|
||||
|
||||
/// 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<String, Rc<Vec<Item>>>,
|
||||
bounds: HashMap<String, Option<Rect>>,
|
||||
sensitive: HashMap<String, bool>,
|
||||
/// Symbol names by block and what it inherits (`None`: the block has no art).
|
||||
symbols: HashMap<(String, Inherit), Option<String>>,
|
||||
/// 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<SymbolKey, Option<String>>,
|
||||
/// The blocks a block places within some levels below itself (see [`Build::reach_within`]).
|
||||
reaches: HashMap<ShapeKey, Reach>,
|
||||
/// The blocks each block places directly (see [`Build::placed_blocks`]).
|
||||
placed: HashMap<String, Rc<Vec<String>>>,
|
||||
/// How many levels of blocks a block draws below itself (see [`Build::height_under`]).
|
||||
block_height: HashMap<String, u32>,
|
||||
/// Whether a block placed with so many levels left before the nesting limit reaches it (see
|
||||
/// [`Build::reaches_limit`]).
|
||||
limit_reached: HashMap<ShapeKey, bool>,
|
||||
/// The ancestors a block places, by block, levels to the nesting limit and ancestors.
|
||||
ancestors_placed: HashMap<ShapeKey, Vec<Rc<str>>>,
|
||||
/// One shared copy of each ancestor name the keys above hold.
|
||||
interned: HashSet<Rc<str>>,
|
||||
/// 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<ScaledLook>>,
|
||||
/// The same answers for scans that left out a block inside itself, by depth.
|
||||
scaled_looks_here: HashMap<(String, Inherit, u32), Vec<Rc<ScanHere>>>,
|
||||
/// The steps of the scale scan in progress.
|
||||
scan_trail: Vec<Trail>,
|
||||
/// Names of the symbols made so far, and the next suffix to try for each label.
|
||||
symbol_names: HashSet<String>,
|
||||
next_suffix: HashMap<String, usize>,
|
||||
@@ -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<Rc<Vec<String>>> {
|
||||
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<str> {
|
||||
if let Some(n) = self.interned.get(name) {
|
||||
return n.clone();
|
||||
}
|
||||
let n: Rc<str> = 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<Rc<HashSet<String>>> {
|
||||
// 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<Rc<str>> = 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<str>]) -> 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<String>) -> (Option<u32>, 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<Rect> {
|
||||
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<String, Arc<Node>> = 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<String> {
|
||||
/// 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<Vec<String>>) {
|
||||
// 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<TrailKey>) -> bool {
|
||||
let steps: Vec<Trail> = 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<Rc<str>> = 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<Node>, Option<Rect>, 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<Node>, Option<Rect>, 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<usize> = 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<usize> = 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<usize> = 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<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether `taken` holds `name`, counted as one name tried (tests).
|
||||
|
||||
@@ -8,9 +8,10 @@ use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape};
|
||||
use vectorcraft_doc::Justify;
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use craft_dxf::acis;
|
||||
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
|
||||
|
||||
use super::acis;
|
||||
use super::build::MAX_ELEMENTS;
|
||||
use super::curve::{self, Vertex};
|
||||
use super::hatch::{self, Grad, NoPattern};
|
||||
use super::reader::{aci_paper, point};
|
||||
@@ -478,26 +479,12 @@ impl Converter {
|
||||
/// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3
|
||||
/// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle.
|
||||
fn region(&mut self, e: &EntityRecord<'_>) -> Option<Geom> {
|
||||
let g = e.groups();
|
||||
let own = g.subclass("AcDbModelerGeometry");
|
||||
let tags = if own.0.is_empty() { g.0 } else { own.0 };
|
||||
let mut text = String::new();
|
||||
for t in tags {
|
||||
match t.code {
|
||||
1 => {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(t.str_ref().unwrap_or_default());
|
||||
}
|
||||
3 => text.push_str(t.str_ref().unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
if text.len() > acis::MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?;
|
||||
let text = acis::text_data(e)?;
|
||||
let outline = if text.trim().is_empty() {
|
||||
acis::from_binary(self.regions.get(&e.record().handle()?)?, MAX_ELEMENTS)
|
||||
} else {
|
||||
acis::from_text(&text, MAX_ELEMENTS)
|
||||
}?;
|
||||
if outline.approximated {
|
||||
self.warn(REGION_CURVES);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
|
||||
//! linetype and text style tables; the blocks; the entities; the layouts; the image files.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_dxf::model::{self, EntityRecord};
|
||||
@@ -132,7 +132,7 @@ impl<'a> Drawing<'a> {
|
||||
d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size });
|
||||
}
|
||||
}
|
||||
d.regions = Rc::new(region_data(&doc));
|
||||
d.regions = Rc::new(craft_dxf::acis::binary_data(&doc));
|
||||
for b in doc.blocks {
|
||||
if b.name.is_empty() {
|
||||
continue;
|
||||
@@ -169,69 +169,6 @@ impl<'a> Drawing<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's
|
||||
/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94.
|
||||
fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> {
|
||||
let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities));
|
||||
let wanted: HashSet<u64> = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect();
|
||||
let mut out = HashMap::new();
|
||||
if wanted.is_empty() {
|
||||
return out;
|
||||
}
|
||||
for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) {
|
||||
for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") {
|
||||
let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue };
|
||||
if !wanted.contains(&handle) || out.contains_key(&handle) {
|
||||
continue;
|
||||
}
|
||||
let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue };
|
||||
let data = r.tags.get(at + 1..).unwrap_or_default();
|
||||
let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok());
|
||||
let mut bytes = Vec::new();
|
||||
let mut whole = true;
|
||||
for t in data.iter().filter(|t| t.code == 310) {
|
||||
whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes);
|
||||
if !whole || bytes.len() > super::acis::MAX_BYTES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !whole {
|
||||
continue;
|
||||
}
|
||||
if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) {
|
||||
out.insert(handle, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes
|
||||
/// than it holds (the data was cut short or damaged) or the data is longer than `limit`.
|
||||
pub(super) fn sized_region(mut bytes: Vec<u8>, size: Option<usize>, limit: usize) -> Option<Vec<u8>> {
|
||||
match size {
|
||||
Some(n) if n <= bytes.len() => bytes.truncate(n),
|
||||
Some(_) => return None,
|
||||
None => {}
|
||||
}
|
||||
(bytes.len() <= limit).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not
|
||||
/// a hex digit or an odd number of digits.
|
||||
pub(super) fn hex_bytes(hex: &str, out: &mut Vec<u8>) -> bool {
|
||||
let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
|
||||
let (pairs, rest) = hex.as_bytes().as_chunks::<2>();
|
||||
if !rest.is_empty() {
|
||||
return false;
|
||||
}
|
||||
for pair in pairs {
|
||||
let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false };
|
||||
out.push(hi << 4 | lo);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn point(p: model::Point) -> Point {
|
||||
Point::new(p[0], p[1])
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -327,20 +327,6 @@ fn binary_data_in_the_acdsdata_section_reads_alike() {
|
||||
short[7].1 = (bytes.len() + 1).to_string();
|
||||
let r = import(&drawing("AC1032", &e, &short), &points()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
|
||||
// A chunk with an odd number of digits or a character that is not a hex digit fails to read.
|
||||
let mut out = Vec::new();
|
||||
assert!(super::reader::hex_bytes("0aFf", &mut out));
|
||||
assert_eq!(out, [0x0A, 0xFF]);
|
||||
for hex in ["0aF", "0aZZ", "0 aF"] {
|
||||
assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}");
|
||||
}
|
||||
// Data longer than the limit is left out, unless its declared size cuts it within the limit.
|
||||
let sized = |len: usize, size: Option<usize>| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len());
|
||||
assert_eq!(sized(10, None), None);
|
||||
assert_eq!(sized(10, Some(9)), None);
|
||||
assert_eq!(sized(10, Some(11)), None);
|
||||
assert_eq!(sized(10, Some(5)), Some(5));
|
||||
assert_eq!(sized(8, None), Some(8));
|
||||
}
|
||||
|
||||
/// A drawing the export writes (R2000, millimetres) with a region added to its entities.
|
||||
|
||||
@@ -27,8 +27,6 @@
|
||||
#![doc(test(attr(deny(unsafe_code))))]
|
||||
|
||||
mod aci;
|
||||
// Temporary until storytold/craft-libs#5381 merges and the craft-libs pin moves past it.
|
||||
mod blocks_compat;
|
||||
pub mod dwg;
|
||||
#[cfg(test)]
|
||||
mod expansion_test;
|
||||
|
||||
+4
-10
@@ -15,9 +15,7 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
|
||||
use crate::aci::nearest_aci;
|
||||
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
|
||||
// Block and the INSERT writer come from craft-libs#5381 once it merges; see `blocks_compat`.
|
||||
use crate::blocks_compat::Block;
|
||||
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
use craft_dxf::drawing::{Block, Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
|
||||
/// Curves are flattened to within this distance (points) where DXF needs straight segments
|
||||
/// (hatch boundaries, R12 polylines).
|
||||
@@ -597,6 +595,7 @@ impl<'a> Scene<'a> {
|
||||
linetypes: self.linetypes,
|
||||
styles: self.styles,
|
||||
images: self.images,
|
||||
blocks: self.blocks,
|
||||
entities: self.e.into_string(),
|
||||
extents: self.extents.unwrap_or(limits),
|
||||
limits,
|
||||
@@ -604,12 +603,7 @@ impl<'a> Scene<'a> {
|
||||
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
|
||||
next: self.next,
|
||||
};
|
||||
DxfOutput {
|
||||
bytes: crate::blocks_compat::write(drawing, &self.blocks).into_bytes(),
|
||||
images: self.files,
|
||||
warnings: self.warnings,
|
||||
setting_notes: self.setting_notes,
|
||||
}
|
||||
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
|
||||
}
|
||||
|
||||
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
|
||||
@@ -788,7 +782,7 @@ impl<'a> Scene<'a> {
|
||||
let base = symbol_name(n.name.as_deref().unwrap_or_default(), long);
|
||||
let base = if base.is_empty() { symbol_name("Group", long) } else { base };
|
||||
let name = self.block_names.unique(&base, if long { 255 } else { 31 });
|
||||
crate::blocks_compat::insert(&mut self.e, insert, self.owner, &self.layer, &name);
|
||||
self.e.insert(insert, self.owner, &self.layer, &name);
|
||||
self.blocks.push(Block { name, record, begin, end, entities });
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ serde_json = { workspace = true }
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# Field text in Devanagari, Gujarati and other Unicode digits (`units`).
|
||||
craft-i18n = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
flate2 = { workspace = true }
|
||||
|
||||
@@ -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<Arrow>,
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
pub mod appearance;
|
||||
pub mod arrow;
|
||||
pub mod assets;
|
||||
pub mod blend;
|
||||
pub mod cancel;
|
||||
@@ -179,7 +180,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, ascii_digits, ascii_digits_one_number, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
|
||||
+125
-12
@@ -25,6 +25,16 @@ fn ends(segs: &[PathSeg]) -> Option<[(Point, Vec2); 2]> {
|
||||
Some([(first.start(), -tangent(first, 0.0)), (last.end(), tangent(last, 1.0))])
|
||||
}
|
||||
|
||||
/// `out` grown to take in the corners of the projecting caps, reaching `side` past each end of the
|
||||
/// open subpath `segs`.
|
||||
fn square_corners(mut out: Rect, segs: &[PathSeg], side: f64) -> Rect {
|
||||
for (at, dir) in ends(segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The joints between consecutive segments (and, `closed`, where the subpath closes): the point
|
||||
/// and the unit tangents in and out.
|
||||
fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2, Vec2)> + '_ {
|
||||
@@ -249,7 +259,7 @@ impl StrokeLayer {
|
||||
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
|
||||
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
|
||||
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
|
||||
/// reach of the arrowheads round their end points.
|
||||
/// outlines of the arrowheads.
|
||||
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
|
||||
let els = bp.elements();
|
||||
let subs = subpaths(bp);
|
||||
@@ -263,6 +273,9 @@ impl StrokeLayer {
|
||||
// box needed.
|
||||
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
|
||||
let mut even = even_only.then_some(bounds);
|
||||
// Tip-aligned arrowheads shorten the line, and its caps sit on the shortened ends.
|
||||
let pieces = crate::arrow::stroke_pieces(bp, self);
|
||||
let shortened = matches!(pieces.line, std::borrow::Cow::Owned(_));
|
||||
for (r, closed) in subs {
|
||||
let side = self.side_reach(closed);
|
||||
let butt = self.cap == LineCap::Butt && !closed;
|
||||
@@ -309,23 +322,50 @@ impl StrokeLayer {
|
||||
} else if !even_only {
|
||||
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
|
||||
}
|
||||
if square {
|
||||
for (at, dir) in ends(&segs).into_iter().flatten() {
|
||||
let n = Vec2::new(-dir.y, dir.x) * side;
|
||||
out = out.union_pt(at + dir * side + n).union_pt(at + dir * side - n);
|
||||
if square && !shortened {
|
||||
out = square_corners(out, &segs, side);
|
||||
}
|
||||
}
|
||||
if shortened && self.cap == LineCap::Square {
|
||||
let line = pieces.line.elements();
|
||||
// The renderer aligns the stroke along every subpath by whether the path ends closed.
|
||||
let side = self.side_reach(matches!(bp.elements().last(), Some(vectorcraft_geom::PathEl::ClosePath)));
|
||||
for (r, closed) in subpaths(&pieces.line) {
|
||||
if side <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
if closed {
|
||||
// A closed subpath with no length, a lone anchor included, paints the dot at the
|
||||
// whole path's reach when the stroke draws dots.
|
||||
if !self.draws_dots() || vectorcraft_geom::kurbo::segments(line[r.clone()].iter().copied()).any(|s| has_length(&s)) {
|
||||
continue;
|
||||
}
|
||||
let lone = line[r.start].end_point().map(|p| Rect::from_points(p, p));
|
||||
let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
continue;
|
||||
}
|
||||
let segs = drawn(&line[r.clone()]);
|
||||
if segs.is_empty() {
|
||||
// A trim that leaves no length still paints the caps' dot.
|
||||
let dot = segments(&line[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
} else {
|
||||
out = square_corners(out, &segs, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, _, end) in head_ends(self, bp) {
|
||||
let r = self.head_reach(end);
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
|
||||
for head in pieces.heads {
|
||||
if !head.outline.elements().is_empty() {
|
||||
out = out.union(head.outline.bounding_box());
|
||||
}
|
||||
}
|
||||
even.map_or(out, |e| out.union(e.inflate(side_max, side_max)))
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
|
||||
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
|
||||
/// projecting caps and the outlines of the arrowheads. An open subpath
|
||||
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
|
||||
/// ([`Self::body_along`]).
|
||||
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
|
||||
@@ -681,13 +721,86 @@ mod tests {
|
||||
})
|
||||
};
|
||||
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
|
||||
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
|
||||
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
|
||||
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}");
|
||||
// The triangle straddles its path end in Extend mode and ends exactly on it in Tip mode.
|
||||
assert_eq!(small, Rect::new(0.0, -4.0, 104.0, 4.0));
|
||||
assert_eq!(big, Rect::new(0.0, -12.0, 112.0, 12.0));
|
||||
let mut tip = at(300.0);
|
||||
tip.arrow_align = ArrowAlign::Tip;
|
||||
assert_eq!(tip.bounds_on(&l, b), Rect::new(0.0, -12.0, 100.0, 12.0));
|
||||
// The start has no head.
|
||||
assert_eq!(at(300.0).head_reach(false), 0.0);
|
||||
}
|
||||
|
||||
/// An open arrow at the start of a line, its tip on the start point: the box ends where the
|
||||
/// head's barbs end, with no room left in front of the tip (#10225).
|
||||
#[test]
|
||||
fn an_open_tip_aligned_arrowhead_adds_no_room_in_front_of_its_tip() {
|
||||
let l = line();
|
||||
let b = l.bounding_box();
|
||||
let st = stroke(1.0, |s| {
|
||||
s.start_arrow = Some(Arrowhead::ArrowOpen);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
s.arrow_scale = (300.0, 100.0);
|
||||
});
|
||||
let bounds = st.bounds_on(&l, b);
|
||||
// The barbs reach back along the line from the tip, and at most the line's weight past it.
|
||||
assert!(bounds.x0 <= 0.0 && bounds.x0 >= -st.width, "{bounds:?}");
|
||||
assert!(bounds.y0 < -st.width && bounds.y1 > st.width, "the barbs spread wider than the line: {bounds:?}");
|
||||
assert_eq!(bounds.x1, b.x1, "the end has no head and a butt cap");
|
||||
}
|
||||
|
||||
/// A Tip-aligned arrowhead shortens the line, and the projecting cap sits on the shortened end:
|
||||
/// the box takes in that cap's corners, and not the corners a cap on the path's own end would have.
|
||||
#[test]
|
||||
fn projecting_caps_under_tip_aligned_arrowheads_sit_on_the_shortened_ends() {
|
||||
let l = line();
|
||||
let b = l.bounding_box();
|
||||
let st = stroke(10.0, |s| {
|
||||
s.cap = LineCap::Square;
|
||||
s.join = LineJoin::Bevel;
|
||||
s.end_arrow = Some(Arrowhead::Triangle);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
});
|
||||
let pieces = crate::arrow::stroke_pieces(&l, &st);
|
||||
let segs = drawn(pieces.line.elements());
|
||||
let [_, (at, dir)] = ends(&segs).unwrap_or_else(|| panic!("the arrowhead covers the whole line"));
|
||||
assert!(at.x < 95.0 && (dir.x - 1.0).abs() < 1e-9, "{at:?} {dir:?}");
|
||||
let bounds = st.bounds_on(&l, b);
|
||||
let n = Vec2::new(-dir.y, dir.x) * 5.0;
|
||||
for corner in [at + dir * 5.0 + n, at + dir * 5.0 - n] {
|
||||
assert!(bounds.inflate(1e-9, 1e-9).contains(corner), "{corner:?} outside {bounds:?}");
|
||||
}
|
||||
// Nothing is painted right of the head's tip at x = 100; a cap on the path's own end would
|
||||
// reach to x = 105.
|
||||
let head = pieces.heads.iter().map(|h| h.outline.bounding_box()).reduce(|a, h| a.union(h));
|
||||
assert_eq!(head.map(|h| h.x1), Some(100.0));
|
||||
assert_eq!(bounds.x1, 100.0, "{bounds:?}");
|
||||
// The start has no head, and its cap projects 5 in front of it.
|
||||
assert_eq!(bounds.x0, -5.0, "{bounds:?}");
|
||||
}
|
||||
|
||||
/// A closed lone anchor in a path that ends open is painted as a dot at the whole path's reach,
|
||||
/// so the box takes it in when a Tip-aligned arrowhead moves the start cap off that anchor.
|
||||
#[test]
|
||||
fn closed_lone_anchors_keep_their_dot_under_tip_aligned_arrowheads() {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((0.0, 0.0));
|
||||
p.line_to((100.0, 0.0));
|
||||
p.move_to((0.0, 0.0));
|
||||
p.close_path();
|
||||
p.move_to((110.0, 0.0));
|
||||
p.line_to((120.0, 0.0));
|
||||
let st = stroke(10.0, |s| {
|
||||
s.cap = LineCap::Square;
|
||||
s.join = LineJoin::Bevel;
|
||||
s.align = StrokeAlign::Inside;
|
||||
s.start_arrow = Some(Arrowhead::Triangle);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
});
|
||||
let bounds = st.bounds_on(&p, p.bounding_box());
|
||||
assert_eq!(bounds.x0, -5.0, "the lone anchor's square dot reaches 5 left of it: {bounds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() {
|
||||
let sq = square();
|
||||
|
||||
@@ -303,3 +303,43 @@ fn format_area_formats_and_trims_cleanly() {
|
||||
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
|
||||
}
|
||||
|
||||
/// Typed in Devanagari or Gujarati digits, a field value reads as its ASCII spelling does:
|
||||
/// plain numbers, units, picas, arithmetic, percentages and a decimal comma.
|
||||
#[test]
|
||||
fn hindi_and_gujarati_digits_read_as_ascii_digits_do() {
|
||||
let ascii = ["12", "12.5 mm", "-3in", "2p6", "45*2", "10x2 mm", "100pt+25%", "1080/2 px", "13q"];
|
||||
let hindi = ["१२", "१२.५ mm", "-३in", "२p६", "४५*२", "१०x२ mm", "१००pt+२५%", "१०८०/२ px", "१३q"];
|
||||
let gujarati = ["૧૨", "૧૨.૫ mm", "-૩in", "૨p૬", "૪૫*૨", "૧૦x૨ mm", "૧૦૦pt+૨૫%", "૧૦૮૦/૨ px", "૧૩q"];
|
||||
for ((a, h), g) in ascii.iter().zip(hindi).zip(gujarati) {
|
||||
let want = Unit::Millimeters.parse(a);
|
||||
assert!(want.is_some(), "`{a}` should read");
|
||||
assert_eq!(Unit::Millimeters.parse(h), want, "`{h}` vs `{a}`");
|
||||
assert_eq!(Unit::Millimeters.parse(g), want, "`{g}` vs `{a}`");
|
||||
}
|
||||
assert_eq!(crate::parse_number("४५*२"), crate::parse_number("45*2"));
|
||||
assert_eq!(crate::parse_number("૪૫x૨"), crate::parse_number("45x2"));
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("०,५ mm"), Unit::Millimeters.parse("0.5 mm"));
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૦,૫"), Unit::Millimeters.parse("0.5"));
|
||||
}
|
||||
|
||||
/// A grouped thousand is refused in any digits, as `1,000` is, rather than read as 1.
|
||||
#[test]
|
||||
fn a_native_digit_thousand_is_refused_like_an_ascii_one() {
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("1,000 mm"), None);
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("१,००० mm"), None);
|
||||
assert_eq!(Unit::Millimeters.parse_with_decimal_comma("૧,૦૦૦"), None);
|
||||
assert_eq!(crate::decimal_point("१,०००"), crate::decimal_point("1,000"));
|
||||
}
|
||||
|
||||
/// One number mixing digit sets is refused, as craft-i18n's `parse_number` refuses it; separate
|
||||
/// numbers of a sum may each use their own.
|
||||
#[test]
|
||||
fn a_number_mixing_digit_sets_reads_as_nothing() {
|
||||
for text in ["1२", "૧२", "१.5", "૧२.૫ mm", "1,२"] {
|
||||
assert_eq!(Unit::Points.parse(text), None, "`{text}`");
|
||||
assert_eq!(Unit::Points.parse_with_decimal_comma(text), None, "`{text}`");
|
||||
assert_eq!(crate::parse_number(text), None, "`{text}`");
|
||||
}
|
||||
assert_eq!(Unit::Points.parse("१२+3"), Unit::Points.parse("12+3"));
|
||||
}
|
||||
+32
-8
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
/// Measurement units (display only; the model is always in points).
|
||||
@@ -203,20 +205,24 @@ impl Unit {
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
|
||||
/// as `*`) reads as nothing.
|
||||
///
|
||||
/// Digits may be any Unicode 16 decimal digits ([`ascii_digits`]): `१२ mm` is `12 mm`, `૪૫*૨` is `45*2`.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
let s = ascii_digits(s)?;
|
||||
parse_measure(×_as_asterisks(&s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
let text = ascii_digits(text)?;
|
||||
if text.contains(',') && times_as_asterisks(&text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
self.parse(&decimal_point(&text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
@@ -414,9 +420,26 @@ fn percent(s: &str) -> Option<f64> {
|
||||
/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed
|
||||
/// after the value the field shows) is 100 mm (#5684). A number written with both separators has
|
||||
/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a
|
||||
/// number that reads as thousands ([`thousands`]).
|
||||
pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
/// number that reads as thousands ([`thousands`]). Digits in other scripts come back as ASCII
|
||||
/// ([`ascii_digits`]), so `१,०००` is refused as `1,000` is; text mixing digit sets in one number
|
||||
/// comes back as it is, for the parser to refuse.
|
||||
pub fn decimal_point(text: &str) -> Cow<'_, str> {
|
||||
let Some(text) = ascii_digits(text) else { return text.into() };
|
||||
if text.contains(',') && !thousands(&text) { text.replace(',', ".").into() } else { text }
|
||||
}
|
||||
|
||||
/// `text` with every Unicode 16 decimal digit (Devanagari `०-९`, Gujarati `૦-૯`, Bengali,
|
||||
/// Arabic-Indic, full-width, …) written as its ASCII digit, so `१२.५ mm` reads as `12.5 mm`. A
|
||||
/// number here is a run of digits, `.` and `,`, and must use one digit set: `1२` and `૧२` are
|
||||
/// `None`. Operators, unit suffixes and other characters are left as they are.
|
||||
pub fn ascii_digits(text: &str) -> Option<Cow<'_, str>> {
|
||||
craft_i18n::ascii_digits(text, |c| matches!(c, '.' | ',')).ok()
|
||||
}
|
||||
|
||||
/// [`ascii_digits`] for text that holds a single number, exponent and unit included: every digit
|
||||
/// must come from one set, so `१e२` is `1e2` and `१e2` is `None`.
|
||||
pub fn ascii_digits_one_number(text: &str) -> Option<Cow<'_, str>> {
|
||||
craft_i18n::ascii_digits(text, |_| true).ok()
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
@@ -455,9 +478,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool {
|
||||
}
|
||||
|
||||
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
|
||||
/// nothing.
|
||||
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`, `४५*२`); text other than digits, `.` and operators
|
||||
/// reads as nothing.
|
||||
pub fn parse_number(s: &str) -> Option<f64> {
|
||||
let s = ascii_digits(s)?;
|
||||
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made, for a gradient, pattern or graphics, or when a later geometry effect reshapes paths but leaves images unchanged; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode (Revolve on a group draws the shaded faces instead); quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made, for a gradient, pattern or graphics, or when a later geometry effect reshapes paths but leaves images unchanged; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode (Revolve on a group draws the shaded faces instead); quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent), colorModel: document|grayscale|bitmap (document: RGB pixels in every document, which a CMYK document's PDF export converts as it converts raster effect images; grayscale: the Rec. 709 luma of each pixel; bitmap: two pixel values, black and white with background white, or black and transparent with background transparent, where a dark pixel at least half covered is black; applied after the background; grayscale and bitmap images are stored as 8-bit gray PNGs, with alpha unless every pixel is opaque); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate pai
Line truncated
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution, background and colorModel, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution, background and colorModel, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution, background and colorModel, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -102,9 +102,9 @@ pub use revolve::{
|
||||
pub use solids::rendered::{rendered_warning, three_d_bounds_art_in};
|
||||
pub use solids::{
|
||||
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic,
|
||||
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings,
|
||||
SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame,
|
||||
graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_COLOR_MODELS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS,
|
||||
RenderSettings, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
|
||||
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art,
|
||||
solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
|
||||
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
|
||||
|
||||
@@ -717,7 +717,6 @@ impl PixelFx {
|
||||
PixelFx::Charcoal { thickness, detail, .. } => Some(sketch_ink::charcoal_reach(thickness, detail)),
|
||||
PixelFx::Photocopy { detail, .. } => Some(sketch_ink::copy_reach(detail)),
|
||||
PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)),
|
||||
PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)),
|
||||
// The cells around the pixel's, and the cells around theirs.
|
||||
// (Without a usable grid there are no dots: see `pixelate::color_halftone`.)
|
||||
PixelFx::ColorHalftone { max_radius, .. } => {
|
||||
@@ -740,8 +739,9 @@ impl PixelFx {
|
||||
PixelFx::WaterPaper { fiber_length, .. } => {
|
||||
Some(sketch::water_paper_shift(fiber_length) + 3.0 * (0.06 * fiber_length.clamp(3.0, 50.0)).max(0.35))
|
||||
}
|
||||
// Cutout's palette and Torn Edges' peak-normalised edges come from the whole object.
|
||||
PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } => None,
|
||||
// Cutout's palette and the peak-normalized edges of Torn Edges and Glowing Edges come
|
||||
// from the whole object.
|
||||
PixelFx::Cutout { .. } | PixelFx::TornEdges { .. } | PixelFx::GlowingEdges { .. } => None,
|
||||
// The softened tones around the pixel.
|
||||
PixelFx::NeonGlow { size, .. } => Some(3.0 * artistic::glow_spread(size)),
|
||||
PixelFx::PlasticWrap { smoothness, .. } => Some(artistic::plastic_reach(smoothness)),
|
||||
|
||||
@@ -42,8 +42,8 @@ pub(crate) mod shadow;
|
||||
|
||||
pub(crate) mod wireframe;
|
||||
pub use wireframe::{
|
||||
RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe,
|
||||
three_d_wireframe_in,
|
||||
RENDER, RENDER_BACKGROUNDS, RENDER_COLOR_MODELS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image,
|
||||
renders_wireframe, three_d_wireframe_in,
|
||||
};
|
||||
|
||||
pub mod rendered;
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
|
||||
use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps};
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ImageBlob, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, ImageBlob, ImageObject, Node, NodeId, NodeKind, RasterColorModel};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_three_d::{Light, MeshProjection};
|
||||
|
||||
@@ -160,7 +160,8 @@ pub(crate) fn with_receiver(
|
||||
}
|
||||
|
||||
/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page,
|
||||
/// made with `samples` × `samples` samples a pixel.
|
||||
/// made with `samples` × `samples` samples a pixel. `gray` when the color model is Grayscale or
|
||||
/// Bitmap: every pixel's red, green and blue are equal, and the image is stored as a gray PNG.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Rendered {
|
||||
pub rect: Rect,
|
||||
@@ -168,6 +169,7 @@ pub struct Rendered {
|
||||
pub rows: u32,
|
||||
pub samples: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
pub gray: bool,
|
||||
}
|
||||
|
||||
/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the
|
||||
@@ -222,12 +224,33 @@ fn render_layer(
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p };
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
|
||||
[straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8)
|
||||
color_model_pixel(p, settings.color_model, settings.white)
|
||||
})
|
||||
.collect();
|
||||
Ok(Rendered { rect, cols, rows, samples: k, pixels })
|
||||
Ok(Rendered { rect, cols, rows, samples: k, pixels, gray: settings.color_model != RasterColorModel::Document })
|
||||
}
|
||||
|
||||
/// Premultiplied sRGB float pixel `p` as a straight RGBA8 pixel in color model `model`, `white`
|
||||
/// when `p` is already on the white background. Grayscale and Bitmap map the straight color before
|
||||
/// the coverage is rounded, so an edge pixel takes the gray or the black or white of the surface it
|
||||
/// covers. Bitmap on a transparent background is black and transparent: a dark pixel at least half
|
||||
/// covered is opaque black, and every other pixel is transparent.
|
||||
fn color_model_pixel(p: [f32; 4], model: RasterColorModel, white: bool) -> [u8; 4] {
|
||||
let a = p[3].clamp(0.0, 1.0);
|
||||
let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
|
||||
if model == RasterColorModel::Document {
|
||||
return [straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8);
|
||||
}
|
||||
let alpha = (a * 255.0).round() as u8;
|
||||
if alpha == 0 {
|
||||
return [0; 4];
|
||||
}
|
||||
let luma = 0.2126 * straight(p[0]) + 0.7152 * straight(p[1]) + 0.0722 * straight(p[2]);
|
||||
if model == RasterColorModel::Bitmap && !white {
|
||||
return if alpha >= 128 && luma < 0.5 { [0, 0, 0, 255] } else { [0; 4] };
|
||||
}
|
||||
let gray = if model == RasterColorModel::Bitmap { if luma < 0.5 { 0 } else { 255 } } else { (luma * 255.0).round() as u8 };
|
||||
[gray, gray, gray, alpha]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -630,11 +653,23 @@ pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
|
||||
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?)))))
|
||||
}
|
||||
|
||||
/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded.
|
||||
/// `image` as an image object holding its pixels as a PNG: RGBA, or for a [`Rendered::gray`] image
|
||||
/// gray, with alpha unless every pixel is opaque. `None` when it can't be encoded.
|
||||
fn image_object(image: &Rendered) -> Option<ImageObject> {
|
||||
let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?;
|
||||
let mut png = vec![];
|
||||
raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
let mut out = Cursor::new(&mut png);
|
||||
if image.gray {
|
||||
let pixels = image.pixels.as_chunks::<4>().0;
|
||||
if pixels.iter().all(|p| p[3] == 255) {
|
||||
let levels = pixels.iter().map(|p| p[0]).collect();
|
||||
image::GrayImage::from_raw(image.cols, image.rows, levels)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
} else {
|
||||
let gray_alpha = pixels.iter().flat_map(|p| [p[0], p[3]]).collect();
|
||||
image::GrayAlphaImage::from_raw(image.cols, image.rows, gray_alpha)?.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
}
|
||||
} else {
|
||||
image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?.write_to(&mut out, image::ImageFormat::Png).ok()?;
|
||||
}
|
||||
let blob = ImageBlob::png(png);
|
||||
let cell = image.rect.width() / f64::from(image.cols);
|
||||
Some(ImageObject {
|
||||
@@ -927,6 +962,7 @@ fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings
|
||||
.into_iter()
|
||||
.for_each(&mut f);
|
||||
[settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f);
|
||||
settings.color_model.id().hash(&mut h);
|
||||
for m in meshes {
|
||||
m.mesh.triangles.hash(&mut h);
|
||||
}
|
||||
|
||||
@@ -62,7 +62,8 @@ fn scene_of(n: &Node) -> (Vec<SolidMesh>, Lighting) {
|
||||
(crate::three_d_meshes(n).unwrap(), lighting(&fx.id, &p))
|
||||
}
|
||||
|
||||
const MEDIUM: RenderSettings = RenderSettings { quality: 1, resolution: None, white: false };
|
||||
const MEDIUM: RenderSettings =
|
||||
RenderSettings { quality: 1, resolution: None, white: false, color_model: vectorcraft_doc::RasterColorModel::Document };
|
||||
|
||||
const FOUR: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, super::super::ROTATE];
|
||||
|
||||
@@ -448,6 +449,127 @@ fn the_background_is_white_or_clear() {
|
||||
assert!(corners(&white).contains(&[255; 4]), "{:?}", corners(&white));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_model_maps_straight_color_before_rounding_coverage() {
|
||||
let dark = 127.0 / 255.0;
|
||||
let edge = [dark * 0.25, dark * 0.25, dark * 0.25, 0.25];
|
||||
assert_eq!(color_model_pixel(edge, RasterColorModel::Grayscale, false), [127, 127, 127, 64]);
|
||||
// Over white, every pixel is opaque, so Bitmap needs no rounding of the coverage.
|
||||
for (model, white) in [(RasterColorModel::Grayscale, false), (RasterColorModel::Grayscale, true), (RasterColorModel::Bitmap, true)] {
|
||||
assert_eq!(color_model_pixel([0.0; 4], model, white), [0; 4]);
|
||||
for rgb in [[127, 127, 127], [128, 128, 128], [255, 0, 0], [0, 255, 0], [0, 0, 255]] {
|
||||
let mut expected = [rgb[0], rgb[1], rgb[2], 255];
|
||||
vectorcraft_doc::RasterEffectsSettings { color_model: model, ..Default::default() }.finish_pixels(&mut expected);
|
||||
let p = [f32::from(rgb[0]) / 255.0, f32::from(rgb[1]) / 255.0, f32::from(rgb[2]) / 255.0, 1.0];
|
||||
assert_eq!(color_model_pixel(p, model, white), expected, "{model:?}, white {white}: {rgb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bitmap on a transparent background makes a black and transparent image: a dark pixel at least
|
||||
/// half covered is opaque black, and a light pixel or one less than half covered is transparent.
|
||||
#[test]
|
||||
fn bitmap_on_a_transparent_background_is_black_and_transparent() {
|
||||
let bitmap = |p| color_model_pixel(p, RasterColorModel::Bitmap, false);
|
||||
assert_eq!(bitmap([1.0, 1.0, 1.0, 1.0]), [0; 4], "white is transparent");
|
||||
assert_eq!(bitmap([0.0, 0.0, 0.0, 1.0]), [0, 0, 0, 255]);
|
||||
assert_eq!(bitmap([1.0, 0.0, 0.0, 1.0]), [0, 0, 0, 255], "red is dark");
|
||||
assert_eq!(bitmap([0.0, 1.0, 0.0, 1.0]), [0; 4], "green is light");
|
||||
assert_eq!(bitmap([0.0, 0.0, 0.0, 0.5]), [0, 0, 0, 255], "a half-covered black pixel is opaque black");
|
||||
let dark = 127.0 / 255.0;
|
||||
assert_eq!(bitmap([dark * 0.25, dark * 0.25, dark * 0.25, 0.25]), [0; 4], "a dark pixel a quarter covered is transparent");
|
||||
assert_eq!(bitmap([0.5, 0.5, 0.5, 0.5]), [0; 4], "a half-covered white pixel is transparent");
|
||||
assert_eq!(bitmap([0.0; 4]), [0; 4]);
|
||||
// A pale solid's light pixels are transparent and its dark ones black.
|
||||
let pale = solid_square(super::super::EXTRUDE, Color::rgb(0.9, 0.9, 0.7), json!({}));
|
||||
let (meshes, lighting) = scene_of(&pale);
|
||||
let at = |color_model| render(&meshes, &lighting, RenderSettings { color_model, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap().pixels;
|
||||
let (color, bitmap) = (at(RasterColorModel::Document), at(RasterColorModel::Bitmap));
|
||||
let mut clear = 0;
|
||||
for (c, b) in color.chunks(4).zip(bitmap.chunks(4)) {
|
||||
assert!(b == [0, 0, 0, 255] || b == [0; 4], "bitmap pixel {b:?} is black or transparent");
|
||||
let luma = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]);
|
||||
if c[3] == 255 && luma > 130.0 {
|
||||
assert_eq!(b, [0; 4], "a light pixel {c:?} is transparent");
|
||||
clear += 1;
|
||||
} else if c[3] == 255 && luma < 125.0 {
|
||||
assert_eq!(b, [0, 0, 0, 255], "a dark pixel {c:?} is black");
|
||||
}
|
||||
}
|
||||
assert!(clear > 0, "the pale solid has light pixels");
|
||||
}
|
||||
|
||||
/// Grayscale gives each pixel the Rec. 709 luma of the pixel the document's color mode gives, and
|
||||
/// Bitmap makes each pixel black or white over a white background and black or transparent on a
|
||||
/// transparent one. The effect's `colorModel` sets the model, and a new model makes a new image.
|
||||
#[test]
|
||||
fn the_color_model_makes_gray_or_black_and_white_pixels() {
|
||||
use vectorcraft_doc::RasterColorModel;
|
||||
let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({}));
|
||||
let (meshes, lighting) = scene_of(&n);
|
||||
let at = |color_model, white| {
|
||||
render(&meshes, &lighting, RenderSettings { color_model, white, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap().pixels
|
||||
};
|
||||
for white in [false, true] {
|
||||
let (color, gray, bitmap) =
|
||||
(at(RasterColorModel::Document, white), at(RasterColorModel::Grayscale, white), at(RasterColorModel::Bitmap, white));
|
||||
assert_eq!((color.len(), gray.len(), bitmap.len()), (color.len(), color.len(), color.len()));
|
||||
let (mut colored, mut blacks, mut whites) = (0, 0, 0);
|
||||
for ((c, g), b) in color.chunks(4).zip(gray.chunks(4)).zip(bitmap.chunks(4)) {
|
||||
assert_eq!(g[3], c[3], "white {white}: grayscale keeps each pixel's coverage");
|
||||
assert!(g[0] == g[1] && g[1] == g[2], "white {white}: grayscale pixel {g:?}");
|
||||
if white {
|
||||
assert_eq!(b[3], c[3], "white {white}: bitmap keeps each pixel's coverage");
|
||||
} else {
|
||||
assert!(b == [0, 0, 0, 255] || b == [0; 4], "on a transparent background bitmap pixel {b:?} is black or transparent");
|
||||
}
|
||||
if c[3] == 255 {
|
||||
let luma = 0.2126 * f64::from(c[0]) + 0.7152 * f64::from(c[1]) + 0.0722 * f64::from(c[2]);
|
||||
assert!((f64::from(g[0]) - luma).abs() <= 1.0, "white {white}: gray {g:?} for {c:?}, luma {luma}");
|
||||
assert!(b[..3] == [0; 3] || b[..3] == [255; 3], "white {white}: bitmap pixel {b:?}");
|
||||
blacks += usize::from(b == [0, 0, 0, 255]);
|
||||
whites += usize::from(b == [255; 4]);
|
||||
}
|
||||
colored += usize::from(c[0] != c[1] || c[1] != c[2]);
|
||||
}
|
||||
assert!(colored > 0, "white {white}: the document's color mode keeps the paint's color");
|
||||
// Over white, the background is white and the blue solid has dark pixels. On a transparent
|
||||
// background nothing is white.
|
||||
assert!(blacks > 0 && (whites > 0) == white, "white {white}: bitmap gives {blacks} black and {whites} white pixels");
|
||||
}
|
||||
// Grayscale and Bitmap images are stored as gray PNGs, and the document's color mode as RGBA.
|
||||
for (color_model, kinds) in [
|
||||
(RasterColorModel::Document, [image::ColorType::Rgba8, image::ColorType::Rgba8]),
|
||||
(RasterColorModel::Grayscale, [image::ColorType::La8, image::ColorType::L8]),
|
||||
(RasterColorModel::Bitmap, [image::ColorType::La8, image::ColorType::L8]),
|
||||
] {
|
||||
for (white, kind) in [false, true].into_iter().zip(kinds) {
|
||||
let image = render(&meshes, &lighting, RenderSettings { color_model, white, ..MEDIUM }, 72.0, false, &Limits::default()).unwrap();
|
||||
let object = image_object(&image).unwrap();
|
||||
let blob = object.pixels.unwrap();
|
||||
let decoded = image::load_from_memory(&blob.bytes).unwrap();
|
||||
assert_eq!(decoded.color(), kind, "{color_model:?}, white {white}");
|
||||
assert_eq!(decoded.to_rgba8().into_raw(), image.pixels, "{color_model:?}, white {white}: the PNG holds the pixels");
|
||||
}
|
||||
}
|
||||
let settings = |model: &str| crate::render_settings(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "colorModel": model}}));
|
||||
assert_eq!(settings("bitmap").map(|s| s.color_model), Some(RasterColorModel::Bitmap));
|
||||
assert_eq!(settings("grayscale").map(|s| s.color_model), Some(RasterColorModel::Grayscale));
|
||||
assert_eq!(settings("document").map(|s| s.color_model), Some(RasterColorModel::Document));
|
||||
let default = crate::render_settings(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}}));
|
||||
assert_eq!(default.map(|s| s.color_model), Some(RasterColorModel::Document), "the document's color mode is the default");
|
||||
assert_eq!(settings("rgb"), None, "a model outside the three draws shaded");
|
||||
let count = || RASTERIZATIONS.with(|count| count.get());
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let mut lit = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}}));
|
||||
let draw = |n: &Node| images(&super::super::solid_art_drawn_in(Some(&doc), n).unwrap()).len();
|
||||
assert_eq!(draw(&lit), 1);
|
||||
let start = count();
|
||||
lit.appearance.effects[0].params["render"]["colorModel"] = json!("grayscale");
|
||||
assert_eq!(draw(&lit), 1);
|
||||
assert_eq!(count(), start + 1, "a new color model makes a new image");
|
||||
}
|
||||
|
||||
/// A mesh without a projection, or meshes with different ones, can't be placed: the image is refused.
|
||||
#[test]
|
||||
fn meshes_without_one_projection_are_refused() {
|
||||
@@ -857,7 +979,7 @@ fn drawn_images_share_the_pixel_limit() {
|
||||
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let pixels = |resolution: f64| {
|
||||
let (meshes, lighting) = scene_of(&rotated_square(200.0, resolution));
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false };
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(resolution), ..MEDIUM };
|
||||
let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
|
||||
u64::from(m.cols) * u64::from(m.rows)
|
||||
};
|
||||
@@ -1009,7 +1131,7 @@ fn check_counts_raster_work_only_for_drawn_triangles() {
|
||||
assert!(lighting.lights.iter().any(|l| lighting.casts(l)));
|
||||
let two = vec![meshes[0].clone(), meshes[0].clone()];
|
||||
// At 600 ppi the image's raster work outweighs the draft shadow maps' work.
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(600.0), white: false };
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(600.0), ..MEDIUM };
|
||||
let limits = |max_work| {
|
||||
let mut limits = Limits::default();
|
||||
limits.max_work = max_work;
|
||||
@@ -1650,7 +1772,7 @@ fn a_medium_render_stays_within_its_work_bound() {
|
||||
let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
|
||||
n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap());
|
||||
let (meshes, lighting) = scene_of(&n);
|
||||
let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false };
|
||||
let settings = RenderSettings { quality: 1, resolution: Some(300.0), ..MEDIUM };
|
||||
let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
|
||||
assert_eq!(m.samples, 2);
|
||||
let samples = u64::from(m.cols) * u64::from(m.rows) * 4;
|
||||
@@ -1692,7 +1814,7 @@ fn edge_values_render_or_are_refused() {
|
||||
meshes[0].mesh.triangles.push([first[0], first[0], first[1]]);
|
||||
assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle");
|
||||
for resolution in [1.0, 2400.0] {
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false };
|
||||
let settings = RenderSettings { quality: 0, resolution: Some(resolution), ..MEDIUM };
|
||||
let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
|
||||
assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi");
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, RasterColorModel, StrokeLayer};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
|
||||
use vectorcraft_three_d::Facet;
|
||||
|
||||
@@ -21,8 +21,8 @@ use crate::{GeomContext, is_geometry};
|
||||
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
|
||||
|
||||
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
|
||||
/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and
|
||||
/// `background` ([`RENDER_BACKGROUNDS`]).
|
||||
/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution`,
|
||||
/// `background` ([`RENDER_BACKGROUNDS`]) and `colorModel` ([`RENDER_COLOR_MODELS`]).
|
||||
pub const RENDER: &str = "render";
|
||||
|
||||
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
|
||||
@@ -37,6 +37,11 @@ pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"];
|
||||
/// What the rendered image shows where no surface is: nothing, or white.
|
||||
pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"];
|
||||
|
||||
/// The color models of the rendered image, the ids of [`RasterColorModel`]: RGB pixels in every
|
||||
/// document, grayscale, or two pixel values, black and white on a white background and black and
|
||||
/// transparent on a transparent one.
|
||||
pub const RENDER_COLOR_MODELS: [&str; 3] = ["document", "grayscale", "bitmap"];
|
||||
|
||||
/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own
|
||||
/// default).
|
||||
const DEFAULT_QUALITY: usize = 1;
|
||||
@@ -51,6 +56,8 @@ pub struct RenderSettings {
|
||||
/// A white background, which makes the image opaque; otherwise it is transparent where no
|
||||
/// surface or shadow is.
|
||||
pub white: bool,
|
||||
/// The image's color model, applied after the background.
|
||||
pub color_model: RasterColorModel,
|
||||
}
|
||||
|
||||
impl RenderSettings {
|
||||
@@ -73,6 +80,11 @@ pub fn render_settings(id: &str, p: &Value) -> Option<RenderSettings> {
|
||||
quality: quality.unwrap_or(DEFAULT_QUALITY),
|
||||
resolution: render.get("resolution").and_then(Value::as_f64),
|
||||
white: render.get("background").and_then(Value::as_str) == Some("white"),
|
||||
color_model: render
|
||||
.get("colorModel")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|m| RasterColorModel::ALL.into_iter().find(|c| c.id() == m))
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -83,7 +95,8 @@ pub fn renders_image(fx: &Effect) -> bool {
|
||||
|
||||
/// The message a `render` that breaks the rules of [`validate_render`] is refused with.
|
||||
const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \
|
||||
resolution (null or a number from 1 to 2400) and background (transparent or white)";
|
||||
resolution (null or a number from 1 to 2400), background (transparent or white) and colorModel \
|
||||
(document, grayscale or bitmap)";
|
||||
|
||||
/// Check one `render` value against [`RENDER_RULES`].
|
||||
fn check_render(render: &Value) -> Result<(), String> {
|
||||
@@ -93,6 +106,7 @@ fn check_render(render: &Value) -> Result<(), String> {
|
||||
"mode" => one_of(value, &RENDER_MODES),
|
||||
"quality" => one_of(value, &RENDER_QUALITIES),
|
||||
"background" => one_of(value, &RENDER_BACKGROUNDS),
|
||||
"colorModel" => one_of(value, &RENDER_COLOR_MODELS),
|
||||
"resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)),
|
||||
_ => false,
|
||||
})
|
||||
@@ -124,8 +138,9 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
|
||||
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
|
||||
/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]),
|
||||
/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels
|
||||
/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default:
|
||||
/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic)
|
||||
/// per inch), `background` (one of [`RENDER_BACKGROUNDS`]) and `colorModel` (one of
|
||||
/// [`RENDER_COLOR_MODELS`]). A key left out takes its default: `shaded`, `medium`, the document's
|
||||
/// raster effects resolution, `transparent` and `document`. The 3D (Classic)
|
||||
/// effects refuse it as a parameter they do not take.
|
||||
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
|
||||
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
|
||||
|
||||
@@ -419,8 +419,9 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
|
||||
}
|
||||
|
||||
/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or
|
||||
/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background`
|
||||
/// (transparent or white), and only on the panel's four effects.
|
||||
/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400), `background`
|
||||
/// (transparent or white) and `colorModel` (document, grayscale or bitmap), and only on the panel's
|
||||
/// four effects.
|
||||
#[test]
|
||||
fn render_settings_are_validated() {
|
||||
for id in WIRE {
|
||||
@@ -434,6 +435,9 @@ fn render_settings_are_validated() {
|
||||
json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}),
|
||||
json!({"render": {"resolution": 1}}),
|
||||
json!({"render": {"resolution": 2400}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": "document"}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": "grayscale"}}),
|
||||
json!({"render": {"colorModel": "bitmap"}}),
|
||||
] {
|
||||
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
|
||||
}
|
||||
@@ -448,12 +452,16 @@ fn render_settings_are_validated() {
|
||||
json!({"render": {"mode": "rendered", "resolution": "300"}}),
|
||||
json!({"render": {"mode": "rendered", "background": "black"}}),
|
||||
json!({"render": {"mode": "rendered", "samples": 4}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": "rgb"}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": "Grayscale"}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": null}}),
|
||||
json!({"render": {"mode": "rendered", "colorModel": 1}}),
|
||||
] {
|
||||
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
|
||||
assert_eq!(
|
||||
e,
|
||||
"`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \
|
||||
or a number from 1 to 2400) and background (transparent or white)",
|
||||
or a number from 1 to 2400), background (transparent or white) and colorModel (document, grayscale or bitmap)",
|
||||
"{id} {bad}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<Arrow>,
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -17,11 +17,6 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
|
||||
# feature still recognizes the files and refuses them with a message. The apps list it beside
|
||||
# `bundled-fonts`.
|
||||
heif = ["dep:heic-rs", "dep:rayon"]
|
||||
# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges
|
||||
# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm`
|
||||
# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in
|
||||
# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`).
|
||||
cgm = ["vectorcraft-metafile/cgm"]
|
||||
|
||||
[dependencies]
|
||||
craft-codepage = { workspace = true }
|
||||
|
||||
@@ -184,6 +184,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "impact-bursts", name: "Impact Bursts", make: impact_bursts },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
|
||||
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
|
||||
@@ -1216,6 +1217,70 @@ pub(crate) fn dry_media() -> BrushLibrary {
|
||||
built("Dry Media", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// Impact Bursts: art brushes for hit sparks, shocks and crack strokes (original game VFX art).
|
||||
fn impact_bursts() -> BrushLibrary {
|
||||
let star = group(vec![
|
||||
black(polygon(&[(0.0, 0.0), (100.0, -8.0), (88.0, 0.0), (100.0, 8.0)])),
|
||||
black(polygon(&[(12.0, 0.0), (70.0, -14.0), (62.0, 0.0), (70.0, 14.0)])),
|
||||
black(polygon(&[(20.0, 0.0), (48.0, -18.0), (42.0, 0.0), (48.0, 18.0)])),
|
||||
black(polygon(&[(28.0, 0.0), (40.0, -10.0), (36.0, 0.0), (40.0, 10.0)])),
|
||||
]);
|
||||
let ring_shock =
|
||||
group(vec![ring(Point::new(50.0, 0.0), 18.0, 14.0), ring(Point::new(50.0, 0.0), 28.0, 25.0), ring(Point::new(50.0, 0.0), 38.0, 36.0)]);
|
||||
let slash = {
|
||||
let n = 40;
|
||||
let half = |x: f64| {
|
||||
let t = x / 100.0;
|
||||
let arch = 10.0 * (t * std::f64::consts::PI).sin();
|
||||
1.4 + 2.2 * (1.0 - (t - 0.5).abs() * 2.0).max(0.0) + arch * 0.05
|
||||
};
|
||||
let mid = |x: f64| 8.0 * ((x / 100.0) * std::f64::consts::PI).sin() - 4.0;
|
||||
let xs = |i: usize| 100.0 * i as f64 / n as f64;
|
||||
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, mid(x) - half(x))).collect();
|
||||
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, mid(x) + half(x))));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
};
|
||||
let spark_fan = group(vec![
|
||||
black(polygon(&[(0.0, 0.0), (55.0, -16.0), (48.0, -12.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (70.0, -6.0), (62.0, -2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (100.0, 0.0), (90.0, 2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (70.0, 6.0), (62.0, 2.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (55.0, 16.0), (48.0, 12.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (35.0, -10.0), (30.0, -6.0)])),
|
||||
black(polygon(&[(0.0, 0.0), (35.0, 10.0), (30.0, 6.0)])),
|
||||
]);
|
||||
let debris = group(vec![
|
||||
black(shapes::rectangle(Rect::new(4.0, -3.0, 12.0, 1.0))),
|
||||
black(polygon(&[(18.0, 2.0), (28.0, -2.0), (30.0, 4.0)])),
|
||||
black(shapes::rectangle(Rect::new(36.0, -4.0, 44.0, -1.0))),
|
||||
black(polygon(&[(50.0, 1.0), (58.0, 5.0), (62.0, -2.0)])),
|
||||
black(shapes::rectangle(Rect::new(68.0, -2.0, 78.0, 2.0))),
|
||||
black(polygon(&[(82.0, -4.0), (90.0, -1.0), (88.0, 3.0)])),
|
||||
black(shapes::rectangle(Rect::new(92.0, 0.0, 100.0, 3.0))),
|
||||
]);
|
||||
let crack = band(100.0, 1.4, 48, |x| {
|
||||
let t = (x / 8.0).floor();
|
||||
let local = (x / 8.0) - t;
|
||||
let amp = if (t as i32) % 3 == 0 {
|
||||
5.0
|
||||
} else if (t as i32) % 3 == 1 {
|
||||
-3.5
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
if (t as i32) % 2 == 0 { amp * local } else { amp * (1.0 - local) }
|
||||
});
|
||||
let brushes = vec![
|
||||
art("Star Burst", star, Colorization::Tints),
|
||||
art("Ring Shock", ring_shock, Colorization::Tints),
|
||||
art("Slash Arc", black(slash), Colorization::Tints),
|
||||
art("Spark Fan", spark_fan, Colorization::Tints),
|
||||
art("Debris Spray", debris, Colorization::Tints),
|
||||
art("Crack Line", black(crack), Colorization::Tints),
|
||||
];
|
||||
built("Impact Bursts", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
|
||||
@@ -63,6 +63,7 @@ pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> R
|
||||
store_grid(Arc::make_mut(&mut st.doc), &g);
|
||||
if let Some(it) = &mut st.interaction {
|
||||
store_grid(Arc::make_mut(&mut it.doc), &g);
|
||||
it.revision = st.revision + 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(g)
|
||||
@@ -745,6 +746,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
|
||||
}
|
||||
if let Some(it) = &mut st.interaction {
|
||||
clear(&mut it.doc);
|
||||
it.revision = st.revision + 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
}
|
||||
@@ -835,6 +835,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
@@ -873,6 +874,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let doc = std::mem::replace(&mut st.doc, e.doc);
|
||||
keep_unrecorded(&doc, &e.unrecorded, &mut st.doc);
|
||||
let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection));
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
|
||||
@@ -247,8 +247,7 @@ mod tests_svgimport;
|
||||
#[cfg(test)]
|
||||
mod tests_eps;
|
||||
|
||||
// The CGM reader waits on craft-libs#5410 (the `cgm` feature).
|
||||
#[cfg(all(test, feature = "cgm"))]
|
||||
#[cfg(test)]
|
||||
mod tests_cgm;
|
||||
#[cfg(test)]
|
||||
mod tests_dwgimport;
|
||||
|
||||
@@ -573,6 +573,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "dwg"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "pict"
|
||||
| "hpgl"
|
||||
| "ai"
|
||||
)
|
||||
|
||||
@@ -112,7 +112,9 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
why => err(format!("this CDR drawing can't be read ({why})")),
|
||||
})?;
|
||||
let (doc, mut warnings) = build(&d, note, PAGES_CUT);
|
||||
if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) {
|
||||
// Objects the reader or the mapping left out (bitmaps are read but not placed), or content past the reader's limits.
|
||||
let left_out = warnings.iter().any(|w| w == UNSUPPORTED_OBJECTS) || d.warnings.contains(&Warning::TooDeep);
|
||||
if d.version >= FRAMES_FROM && left_out {
|
||||
warnings.push(EMPTY_FRAMES.to_string());
|
||||
}
|
||||
Ok((doc, warnings))
|
||||
@@ -423,6 +425,8 @@ fn copy_cost(objects: &[cd::Object]) -> usize {
|
||||
match o {
|
||||
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
|
||||
cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)),
|
||||
// A bitmap or text is not placed, so it takes nothing past the object itself.
|
||||
cd::Object::Image(_) | cd::Object::Text(_) => {}
|
||||
cd::Object::Clip { container, objects } => {
|
||||
// A container whose outline is behind its fill is built twice, as that outline
|
||||
// and as the clipping path, inside a group of their own.
|
||||
|
||||
@@ -74,6 +74,8 @@ impl Builder {
|
||||
self.learn_spot(c);
|
||||
}
|
||||
}
|
||||
// Bitmaps and text are not placed, so their colors add no swatch.
|
||||
cd::Object::Image(_) | cd::Object::Text(_) => {}
|
||||
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
|
||||
cd::Object::Clip { container, objects } => {
|
||||
for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) {
|
||||
@@ -123,6 +125,8 @@ impl Builder {
|
||||
for o in objects.iter().rev() {
|
||||
match o {
|
||||
cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))),
|
||||
// Bitmaps and text are left out, and the warnings name them with the other objects not read.
|
||||
cd::Object::Image(_) | cd::Object::Text(_) => self.note(Warning::UnsupportedObjects),
|
||||
cd::Object::Group { objects: kids, flags } => {
|
||||
let children = self.objects_at(kids, to_doc, depth + 1);
|
||||
if !children.is_empty() {
|
||||
@@ -452,6 +456,7 @@ mod tests {
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let doc = Builder::new().document(&d);
|
||||
let swatch = doc.swatches.iter().find(|s| s.name == "Red ink").unwrap();
|
||||
@@ -494,6 +499,7 @@ mod tests {
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
assert!(Document::new(612.0, 792.0).swatches.iter().any(|s| s.name == "Black" && !s.spot));
|
||||
let doc = Builder::new().document(&d);
|
||||
@@ -535,6 +541,7 @@ mod tests {
|
||||
master: vec![master],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
b.copies_left = 1000;
|
||||
@@ -571,6 +578,7 @@ mod tests {
|
||||
master: vec![master],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
b.copies_left = 1000;
|
||||
@@ -644,6 +652,7 @@ mod tests {
|
||||
master: vec![],
|
||||
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let doc = Builder::new().document(&d);
|
||||
doc.layers
|
||||
@@ -671,6 +680,7 @@ mod tests {
|
||||
master: vec![],
|
||||
guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let mut b = Builder::new();
|
||||
let doc = b.document(&d);
|
||||
@@ -744,6 +754,7 @@ mod tests {
|
||||
master: vec![],
|
||||
guides: vec![],
|
||||
warnings: vec![],
|
||||
left_out: Default::default(),
|
||||
};
|
||||
let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]]));
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
|
||||
@@ -103,7 +103,15 @@ pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards
|
||||
.collect();
|
||||
pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers });
|
||||
}
|
||||
let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() };
|
||||
let drawing = cd::Drawing {
|
||||
version: 0,
|
||||
page_size: None,
|
||||
pages,
|
||||
master: Vec::new(),
|
||||
guides: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
left_out: Default::default(),
|
||||
};
|
||||
// The limits `document.open` reads `.cmx` files with, so the file opens whole again.
|
||||
let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?;
|
||||
for (set, w) in [
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chos
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|pict|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), embedIcc?: true (webp: the sRGB profile in an ICCP chunk), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, units, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …pict writes a QuickDraw version 2 picture (.pct) of the artboard as emf and wmf do (up to 16 device units a point; at most 32,767 points on a side; fills as polygons, strokes as their filled outlines and images over white; what it leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alik
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|pict|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -1094,7 +1094,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "pict" | "hpgl" | "cmx"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -1136,7 +1136,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards =
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "dwg" | "emf" | "wmf" | "pict" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1181,6 +1181,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"pict" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Pict),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
|
||||
@@ -575,11 +575,20 @@ pub const FORMATS: &[Format] = &[
|
||||
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
|
||||
// each chosen artboard, with the art's fills and strokes in their colors.
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images,
|
||||
// and written by `vectorcraft_metafile::export` as version 2 pictures (`.pct`).
|
||||
Format {
|
||||
id: "pict",
|
||||
label: "PICT",
|
||||
extensions: &["pct", "pic", "pict"],
|
||||
mime: "image/x-pict",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: metafile::OPTIONS,
|
||||
},
|
||||
// Binary Computer Graphics Metafiles, read by `vectorcraft_metafile::import_cgm` into paths,
|
||||
// type and images. Behind the `cgm` feature until craft-libs#5410 merges.
|
||||
#[cfg(feature = "cgm")]
|
||||
// type and images.
|
||||
reader("cgm", "CGM", &["cgm"], "image/cgm", false),
|
||||
// Layered raster `.pcraft` documents, read by `pcraftread` as one image: the full-size
|
||||
// composite, the layers combined, or the preview with a note. Exports don't write them.
|
||||
@@ -654,7 +663,6 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
@@ -681,12 +689,11 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
/// names of PNG, BMP and JPEG files (File › Open and Place still read them all). On Linux the desktop
|
||||
/// entry's EPS and JPEG types (shared-mime-info's) also cover `.epsf` and `.jpe`, so file managers
|
||||
/// offer VectorCraft for them.
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, layered raster `.pcraft`
|
||||
/// documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either. CGM files are added here
|
||||
/// when the `cgm` feature is turned on (craft-libs#5410).
|
||||
/// The packaging declares no type for HP-GL plot files, PICT pictures, CGM files, layered raster
|
||||
/// `.pcraft` documents or DWG drawings (`.dwg`, `.dws` and `.dwt`) either.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "jpe", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "pcraft", "dwg", "dws", "dwt",
|
||||
"jpc", "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", "cgm", "pcraft", "dwg", "dws", "dwt",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
@@ -773,7 +780,6 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"pct",
|
||||
"pic",
|
||||
"pict",
|
||||
#[cfg(feature = "cgm")]
|
||||
"cgm",
|
||||
"plt",
|
||||
"hpgl",
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! `document.export {format: emf|wmf}` and Export As (one picture of an artboard, or one per
|
||||
//! artboard with Use Artboards; raster effects as images, rendered at the document's raster
|
||||
//! effects resolution), `document.open` and File → Place (one artboard, the picture's frame).
|
||||
//! QuickDraw pictures (PICT) and binary Computer Graphics Metafiles (CGM) open and place the same
|
||||
//! way; they are never written.
|
||||
//! QuickDraw pictures (PICT) are written (`format: pict`) and open and place the same way. Binary
|
||||
//! Computer Graphics Metafiles (CGM) open and place the same way; they are never written.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -14,7 +14,7 @@ use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for EMF and WMF.
|
||||
/// The options `document.formats` lists for EMF, WMF and PICT.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
|
||||
|
||||
/// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one
|
||||
@@ -46,7 +46,7 @@ pub(super) fn encode_flattening(
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
vectorcraft_metafile::check_regions_for(&rects, kind).map_err(|e| bad(C, e))?;
|
||||
// Raster effects (shadows, glows, blurs) as images, as PDF export does.
|
||||
let flat = flatten(doc);
|
||||
let src = flat.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -26,8 +26,8 @@ pub const OPTIONS: &[FormatOption] = &[
|
||||
FormatOption {
|
||||
name: "version",
|
||||
ty: "integer",
|
||||
default: "4",
|
||||
description: "the format version to write: 4 (current), or 3, 2 or 1 for older VectorCraft versions (1 and 2 are never compressed; newer features they don't know are lost there)",
|
||||
default: "5",
|
||||
description: "the format version to write: 5 (current), or 4, 3, 2 or 1 for older VectorCraft versions (1 and 2 are never compressed; newer features they don't know are lost there)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "preview",
|
||||
@@ -202,7 +202,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: impl std::io::Write) -> Result<()> {
|
||||
let (mut so, extras) = save_options(cmd, f, doc, p)?;
|
||||
// Include Linked Files keeps placed documents' files; older versions get their art.
|
||||
let full = if so.include_linked || so.version < vectorcraft_format::VERSION {
|
||||
let full = if so.include_linked || so.version < vectorcraft_format::PLACED_SINCE {
|
||||
crate::cmd::place::document::full_documents(doc).0
|
||||
} else {
|
||||
std::borrow::Cow::Borrowed(doc)
|
||||
@@ -223,7 +223,7 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
}
|
||||
drop(drawn);
|
||||
let native = match full {
|
||||
Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::VERSION => {
|
||||
Cow::Owned(full) if so.include_linked && so.version >= vectorcraft_format::PLACED_SINCE => {
|
||||
// Include available bytes without replacing missing, relinkable placed objects.
|
||||
let mut original = doc.clone();
|
||||
original.images = full.images;
|
||||
@@ -242,7 +242,7 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
/// groups of their art for older versions.
|
||||
fn rounded(doc: &Document, version: u32, decimals: u8) -> Document {
|
||||
let mut d = doc.clone();
|
||||
if version < vectorcraft_format::VERSION {
|
||||
if version < vectorcraft_format::PLACED_SINCE {
|
||||
vectorcraft_format::placed_as_groups(&mut d);
|
||||
}
|
||||
d.round_geometry(decimals.min(vectorcraft_format::MAX_PRECISION));
|
||||
|
||||
@@ -46,9 +46,10 @@ impl ScreenSize {
|
||||
/// `2x` (or `2`), `100w`, `100h` or `72ppi`, in any case; positive numbers only.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
// Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`.
|
||||
// Digits and `.` only: `str::parse` would also take `+2`, `1e2`, `inf` and `nan`. Digits of
|
||||
// other scripts read as ASCII digits do (`"२x"` is `2x`), as number fields read them.
|
||||
let num = |t: &str| {
|
||||
let t = t.trim();
|
||||
let t = vectorcraft_doc::ascii_digits(t.trim())?;
|
||||
if !t.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
|
||||
return None;
|
||||
}
|
||||
@@ -196,7 +197,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 8] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 9] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx", "dwg", "pict"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -535,6 +535,7 @@ fn export_extensions_name_every_writable_format() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pct",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
@@ -573,6 +574,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"tga",
|
||||
"psd",
|
||||
"cmx",
|
||||
"pict",
|
||||
"dwg"
|
||||
]
|
||||
);
|
||||
|
||||
@@ -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<synth::Node>, objects: Vec<synth::Node>| {
|
||||
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() {
|
||||
|
||||
@@ -322,9 +322,9 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
#[test]
|
||||
fn pict_and_pagemaker_say_what_to_use_instead() {
|
||||
let mut s = two_boards();
|
||||
// PICT opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PICT files can be opened but not written"), "{e}");
|
||||
// PCX opens; it isn't written.
|
||||
let e = s.execute("document.export", &json!({"format": "pcx"})).unwrap_err().to_string();
|
||||
assert!(e.contains("PCX files can be opened but not written"), "{e}");
|
||||
let e = s
|
||||
.execute("document.open", &json!({"name": "old.pct", "dataBase64": vectorcraft_format::base64_encode(&[0u8; 600])}))
|
||||
.unwrap_err()
|
||||
|
||||
@@ -476,7 +476,7 @@ fn placed_carried_fonts_survive_break_link_and_older_version_save() {
|
||||
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
|
||||
assert_eq!(glyphs(&s).1, 1);
|
||||
}
|
||||
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
|
||||
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::PLACED_SINCE - 1 };
|
||||
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
|
||||
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! PICT pictures through the commands: `document.open` by extension or by content, File › Place as
|
||||
//! one group clipped to the picture's frame, the dialogs' filters and the format list, and files
|
||||
//! that aren't pictures, or a PICT export, refused with a message.
|
||||
//! one group clipped to the picture's frame, `document.export` of one artboard or each, the dialogs'
|
||||
//! filters and the format list, and files that aren't pictures refused with a message.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::NodeKind;
|
||||
@@ -83,8 +83,47 @@ fn files_that_are_not_pictures_are_refused() {
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
png.extend(&picture()[8..]);
|
||||
assert!(detect("x.png", &png).is_none_or(|f| f.id != "pict"));
|
||||
let e = s.execute("document.export", &json!({"format": "pict"})).expect_err("refused").to_string();
|
||||
assert!(e.contains("PICT files can be opened but not written"), "{e}");
|
||||
}
|
||||
|
||||
fn data(r: &serde_json::Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_export_writes_a_picture_that_opens_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 5, "width": 20, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "pict"})).unwrap();
|
||||
assert_eq!((r["format"].as_str(), &r["warnings"]), (Some("pict"), &json!([])), "{r}");
|
||||
let bytes = data(&r);
|
||||
assert_eq!(detect("x.bin", &bytes).map(|f| f.id), Some("pict"));
|
||||
assert_eq!(writable_format(None, Some("x/logo.pct")).unwrap().id, "pict");
|
||||
// The first artboard: its red rectangle, in place.
|
||||
let mut back = Session::new();
|
||||
back.execute("document.open", &json!({"name": "logo.pct", "dataBase64": b64(&bytes)})).unwrap();
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards[0].rect.size(), (100.0, 100.0).into());
|
||||
let mut paths = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
paths.push(n.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1);
|
||||
let b = paths[0].geometric_bounds().unwrap();
|
||||
let want = vectorcraft_geom::Rect::new(10.0, 20.0, 40.0, 60.0);
|
||||
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 0.07), "{b:?}");
|
||||
assert_eq!(paths[0].appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_rgba8(1.0)), Some([255, 0, 0, 255]));
|
||||
// Use Artboards: one picture each.
|
||||
let r = s.execute("document.export", &json!({"format": "pict", "useArtboards": true})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2);
|
||||
assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.pct"), "{files:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -98,7 +137,6 @@ fn the_dialogs_and_the_format_list_name_pict() {
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "pict").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)), "{f}");
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false)), "{f}");
|
||||
assert_eq!(f["mime"], "image/x-pict");
|
||||
assert!(writable_format(None, Some("x/logo.pct")).is_err());
|
||||
}
|
||||
@@ -72,6 +72,17 @@ fn sizes_parse_as_factor_width_height_or_resolution() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_read_digits_of_other_scripts() {
|
||||
assert_eq!(ScreenSize::parse("२x"), Some(ScreenSize::Scale(2.0)));
|
||||
assert_eq!(ScreenSize::parse("૧૦૦W"), Some(ScreenSize::Width(100.0)));
|
||||
assert_eq!(ScreenSize::parse("१४४ppi"), Some(ScreenSize::Ppi(144.0)));
|
||||
// One digit set per number, and the same grammar as ASCII digits.
|
||||
for bad in ["1२x", "१.5x", "-२x", "०w"] {
|
||||
assert_eq!(ScreenSize::parse(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_width_or_height_row_gives_that_many_pixels() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -461,6 +461,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::distortcmds::finish_edit_text(st, inner);
|
||||
st.isolation = Some(layer);
|
||||
st.selection.set([left]);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
st.revision += 1;
|
||||
return ok();
|
||||
}
|
||||
@@ -498,6 +499,7 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
// A guide path isolated while Lock Guides is on isn't selected (#1534).
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// The art on a locked artboard can't be selected.
|
||||
|
||||
@@ -71,7 +71,11 @@ fn resolution(v: &Value) -> Result<f64> {
|
||||
"screen" => 72.0,
|
||||
"medium" => 150.0,
|
||||
"high" => 300.0,
|
||||
other => other.trim_end_matches("ppi").trim().parse::<f64>().map_err(|_| bad(C, format!("unknown resolution `{v}`")))?,
|
||||
// Digits of other scripts read as ASCII digits do (`"३००"` is 300), as number fields read them,
|
||||
// with one digit set for the whole value, exponent included (`"१e2"` is refused).
|
||||
other => vectorcraft_doc::ascii_digits_one_number(other.trim_end_matches("ppi").trim())
|
||||
.and_then(|n| n.parse::<f64>().ok())
|
||||
.ok_or_else(|| bad(C, format!("unknown resolution `{v}`")))?,
|
||||
},
|
||||
v => v.as_f64().ok_or_else(|| bad(C, "resolution must be a number or screen|medium|high"))?,
|
||||
};
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
"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<Item = ProfileEntry<'_>> {
|
||||
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<ProfileEntry<'_>> = 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<String>) {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
}
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<String> = 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<Value> {
|
||||
let profiles: Vec<Value> = s
|
||||
.profile_entries()
|
||||
|
||||
@@ -51,6 +51,9 @@ pub struct DocState {
|
||||
/// Increments on every change (also selection and view-only changes); UIs re-render when it
|
||||
/// moves. Not a dirty flag: see [`DocState::is_dirty`].
|
||||
pub revision: u64,
|
||||
/// Increments each time the selection is set through [`crate::Session::select`] and the other
|
||||
/// selection entries, even when it ends as it was. Not saved, not undoable.
|
||||
pub selections: u64,
|
||||
/// The document as last saved (or opened). Structural sharing makes "unchanged" a pointer
|
||||
/// comparison, and undoing back to the saved state counts as clean.
|
||||
pub(crate) saved_doc: Arc<Document>,
|
||||
@@ -544,6 +547,7 @@ impl DocState {
|
||||
history: History { limit: 500, ..Default::default() },
|
||||
path,
|
||||
revision: 1,
|
||||
selections: 0,
|
||||
active_layer,
|
||||
layer_rows: vec![],
|
||||
layers_reveal: None,
|
||||
|
||||
@@ -7,6 +7,11 @@ use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// The new-art paint state before the running preview, or its current value without a preview.
|
||||
pub fn new_art_paint_before_preview(s: &Session) -> &vectorcraft_tools::PaintDefaults {
|
||||
s.active().and_then(|st| st.interaction.as_ref()).map_or(&s.paint, |it| &it.paint)
|
||||
}
|
||||
|
||||
pub(crate) fn rect_json(r: Option<vectorcraft_geom::Rect>) -> Value {
|
||||
match r {
|
||||
Some(r) => json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }),
|
||||
|
||||
@@ -11,8 +11,8 @@ pub struct Interaction {
|
||||
/// The selection the previews start from (shared, so a preview frame copies nothing).
|
||||
pub selection: Arc<Selection>,
|
||||
pub(crate) active_appearance_item: Option<PreviewAppearanceItem>,
|
||||
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
|
||||
/// revision, and this value stays the same until the interaction ends.
|
||||
/// The baseline document's [`crate::DocState::revision`]. Previews keep this value; replacing or changing the
|
||||
/// baseline advances it to the document's next revision.
|
||||
pub revision: u64,
|
||||
pub preview: Option<(String, Value)>,
|
||||
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
|
||||
|
||||
@@ -108,6 +108,8 @@ pub struct Session {
|
||||
/// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for
|
||||
/// such a stop samples only into a stop selected on that gradient, and otherwise ends.
|
||||
pub(crate) stop_pick: Option<cmd::gradient::StopOwner>,
|
||||
/// The point and document revision the Eyedropper was armed for.
|
||||
freeform_point_pick: Option<tooling::FreeformPointPick>,
|
||||
/// Pointer and key input that came while the tool computed an edit on another thread, each with
|
||||
/// its number and view, made in order once the edit is applied.
|
||||
held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>,
|
||||
|
||||
@@ -68,6 +68,53 @@ type Recipient = (String, String, u64);
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many [`EventPluginsHeld`] this thread holds.
|
||||
static EVENT_PLUGINS_HELD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The thread whose test has events plug-ins installed in the process-wide registry, if any.
|
||||
#[cfg(test)]
|
||||
static EVENT_PLUGINS_OWNER: std::sync::Mutex<Option<std::thread::ThreadId>> = std::sync::Mutex::new(None);
|
||||
#[cfg(test)]
|
||||
static EVENT_PLUGINS_FREED: std::sync::Condvar = std::sync::Condvar::new();
|
||||
|
||||
/// Held by a test that installs events plug-ins in the process-wide registry. Every such plug-in
|
||||
/// reacts to every session's changes and spends handlers of every session's frame budget
|
||||
/// ([`MAX_FRAME_HANDLERS`]), so when tests run as threads of one process, another test's plug-ins
|
||||
/// would take the handlers a test counts on. A thread waits while another thread holds one; the
|
||||
/// guards one thread holds count as one, until the last of them is dropped.
|
||||
#[cfg(test)]
|
||||
pub(crate) struct EventPluginsHeld {
|
||||
/// Dropped on the thread that made it.
|
||||
_thread: std::marker::PhantomData<*const ()>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn hold_event_plugins() -> EventPluginsHeld {
|
||||
if EVENT_PLUGINS_HELD.with(std::cell::Cell::get) == 0 {
|
||||
let me = std::thread::current().id();
|
||||
let mut owner = EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
while owner.is_some_and(|t| t != me) {
|
||||
owner = EVENT_PLUGINS_FREED.wait(owner).unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
}
|
||||
*owner = Some(me);
|
||||
}
|
||||
EVENT_PLUGINS_HELD.with(|n| n.set(n.get() + 1));
|
||||
EventPluginsHeld { _thread: std::marker::PhantomData }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Drop for EventPluginsHeld {
|
||||
fn drop(&mut self) {
|
||||
let last = EVENT_PLUGINS_HELD.with(|n| {
|
||||
n.set(n.get() - 1);
|
||||
n.get() == 0
|
||||
});
|
||||
if last {
|
||||
*EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None;
|
||||
EVENT_PLUGINS_FREED.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipient `p` is.
|
||||
@@ -836,6 +883,7 @@ mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let id = "test.events.nested";
|
||||
let _held = hold_event_plugins();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
|
||||
@@ -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<vectorcraft_doc::SavedProfile>,
|
||||
/// 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<String>,
|
||||
/// 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![],
|
||||
|
||||
@@ -64,6 +64,7 @@ impl Session {
|
||||
lender: None,
|
||||
back_to_painter: None,
|
||||
stop_pick: None,
|
||||
freeform_point_pick: None,
|
||||
held_input: Default::default(),
|
||||
input_count: 0,
|
||||
edit_started_by: None,
|
||||
|
||||
@@ -252,8 +252,64 @@ impl Session {
|
||||
|
||||
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
self.active_appearance_item = None;
|
||||
let uid = self.doc()?.uid;
|
||||
self.select_document_unwatched(uid, f)
|
||||
}
|
||||
|
||||
/// Change the selection in an open document without switching the active document.
|
||||
pub fn select_in_document(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
if self.active().is_some_and(|st| st.uid == uid) {
|
||||
return self.select(f);
|
||||
}
|
||||
self.select_document_unwatched(uid, f)
|
||||
}
|
||||
|
||||
/// Give document `uid` back a selection it had, new art included, through the selection
|
||||
/// filters as they are now: guides locked since, hidden or locked slices and art on a locked
|
||||
/// artboard that is not new art are left out. In the active document, outside a command and an
|
||||
/// interaction, the journal records the selection that comes back, with the current layer kept,
|
||||
/// in the open undo groups too, and the paints for new art load from it as `select.set` loads
|
||||
/// them (with New Art Has Basic Appearance on, a symbol part or an Objects on Path member does
|
||||
/// not load its paints, as `symbol.instance.selectPart` and
|
||||
/// `object.objectsOnPath.selectMember` do not), so a recorded action replays as it ran.
|
||||
pub fn restore_selection(&mut self, uid: u64, selection: Selection) -> Result<()> {
|
||||
let active = self.active().is_some_and(|st| st.uid == uid && st.interaction.is_none()) && self.depth == 0;
|
||||
let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?;
|
||||
let (made, layer) = (st.selection.clone(), st.active_layer);
|
||||
st.selection_record = None;
|
||||
st.selection = selection;
|
||||
self.select_in_document(uid, |_, _| {})?;
|
||||
if !active {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(st) = self.document_mut(uid) else { return Ok(()) };
|
||||
if st.selection == made {
|
||||
return Ok(());
|
||||
}
|
||||
let steps = selection_steps(&st.selection, &made, &st.doc, layer, &st.highlighted_rows());
|
||||
// Only the selection commands load paints on replay: a symbol part comes back through
|
||||
// `symbol.instance.selectPart` and an Objects on Path member through
|
||||
// `object.objectsOnPath.selectMember`, which load none.
|
||||
let loads = steps.iter().any(|(id, _)| id.starts_with("select.") || id == "layer.target");
|
||||
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
|
||||
for step in steps {
|
||||
self.journal.push(step);
|
||||
}
|
||||
self.journal_in_undo_groups(Some(uid), &grouped, from);
|
||||
// As `Session::execute` does after a selection command, which starts without the marker
|
||||
// of a defaults-only paint that ran before it.
|
||||
self.defaults_only_ran = None;
|
||||
self.inherit_new_art();
|
||||
if loads {
|
||||
self.load_selection_paints();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply the selection filters and update the editing state of document `uid`.
|
||||
fn select_document_unwatched(&mut self, uid: u64, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
let st = self.document_mut(uid).ok_or(EngineError::NoDocument)?;
|
||||
let before = st.selection.objects.clone();
|
||||
let new_art = st.selection.new_art.clone();
|
||||
let record = if st.selection_record().is_some() { st.selection_record.take() } else { None };
|
||||
@@ -294,6 +350,7 @@ impl Session {
|
||||
st.layer_rows.clear();
|
||||
}
|
||||
st.revision += 1;
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
// Puppet Warp pins belong to the art they were placed on: another selection starts afresh.
|
||||
if st.doc.puppet.as_ref().is_some_and(|p| p.ids != st.selection.objects) {
|
||||
cmd::distortcmds::drop_puppet_pins(st);
|
||||
@@ -522,6 +579,8 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let began = std::mem::replace(&mut it.doc, st.doc.clone());
|
||||
st.revision += 1;
|
||||
it.revision = st.revision;
|
||||
// The drag acts on the objects it began with: a selection the command made (a paste, a
|
||||
// duplicate, Select All) does not change what the drag moves. A dialog's preview acts on
|
||||
// the selection the command left, and its dialog previews again on its next pass, from the
|
||||
|
||||
@@ -24,6 +24,16 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
r
|
||||
}
|
||||
|
||||
/// What [`Session::execute`] compares to tell that a command changed the selection: the counts of
|
||||
/// what is selected and the first and last object, guide and slice, read in constant time.
|
||||
type SelectionSummary = ([usize; 5], [Option<NodeId>; 6], bool);
|
||||
|
||||
fn selection_summary(s: &Selection) -> SelectionSummary {
|
||||
let counts = [s.objects.len(), s.anchors.len(), s.segments.len(), s.guides.len(), s.slices.len()];
|
||||
let ends = [s.objects.first(), s.objects.last(), s.guides.first(), s.guides.last(), s.slices.first(), s.slices.last()].map(|id| id.copied());
|
||||
(counts, ends, s.symbol_part.is_some())
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run a command callback and keep warnings from every preview it settles or restores.
|
||||
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
|
||||
@@ -72,7 +82,19 @@ impl Session {
|
||||
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
// A command, a step of a batch included, that leaves the active document with another
|
||||
// selection counts as a selection change ([`crate::DocState::selections`]), whichever way
|
||||
// it wrote the selection. The selections are compared by a summary that takes constant time.
|
||||
let before = self.active().map(|st| (st.uid, st.selections, selection_summary(&st.selection)));
|
||||
let r = self.revealing(|s| s.execute_unwatched(id, params));
|
||||
if let Some((uid, selections, summary)) = before
|
||||
&& let Some(st) = self.document_mut(uid)
|
||||
&& st.selections == selections
|
||||
&& selection_summary(&st.selection) != summary
|
||||
{
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
|
||||
@@ -230,7 +252,7 @@ impl Session {
|
||||
params.get("ids").filter(|v| !v.is_null()).cloned().or_else(|| given.map(|ids| ids.iter().map(|i| i.0).collect::<Vec<_>>().into()))
|
||||
})
|
||||
.flatten();
|
||||
let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer));
|
||||
let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer, d.selections));
|
||||
// Only a selection command that changes the selection loads its paints for new art: other
|
||||
// commands, and clicking what is already selected, keep a sampled paint in the proxies.
|
||||
let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten();
|
||||
@@ -240,11 +262,12 @@ impl Session {
|
||||
}
|
||||
let r = cmd::run_spec(s, spec, run_params);
|
||||
if r.is_err()
|
||||
&& let Some((uid, selection, layer)) = selected_before
|
||||
&& let Some((uid, selection, layer, selections)) = selected_before
|
||||
&& let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
|
||||
{
|
||||
st.selection = selection;
|
||||
st.active_layer = layer;
|
||||
st.selections = selections;
|
||||
st.revision += 1;
|
||||
}
|
||||
r
|
||||
|
||||
@@ -118,6 +118,7 @@ impl Session {
|
||||
}
|
||||
let undone = std::mem::replace(&mut st.doc, e.doc);
|
||||
st.selection = Arc::unwrap_or_clone(e.selection);
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
deselect_hidden(&self.menu, &st.doc, &mut st.selection);
|
||||
st.restore_isolation(g.isolation, &undone);
|
||||
st.sync_new_art();
|
||||
@@ -276,6 +277,7 @@ impl Session {
|
||||
}
|
||||
let undone = std::mem::replace(&mut st.doc, doc);
|
||||
st.selection = selection;
|
||||
st.selections = st.selections.wrapping_add(1);
|
||||
st.restore_isolation(scope.isolation, &undone);
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
|
||||
@@ -121,6 +121,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"game-trails",
|
||||
"energy-beams",
|
||||
"dry-media",
|
||||
"impact-bursts",
|
||||
"tech-circuit",
|
||||
"engraving",
|
||||
"arrows",
|
||||
@@ -171,6 +172,12 @@ fn the_builtin_libraries_list_their_brush_names_and_counts() {
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
let impact = run(&mut s, "brush.library", json!({"library": "impact-bursts"}));
|
||||
assert_eq!(
|
||||
impact["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Star Burst", "Ring Shock", "Slash Arc", "Spark Fan", "Debris Spray", "Crack Line"]
|
||||
);
|
||||
assert_eq!((libs[14]["name"].as_str(), libs[14]["count"].as_u64()), (Some("Impact Bursts"), Some(6)));
|
||||
let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"}));
|
||||
assert_eq!(
|
||||
arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
@@ -204,6 +211,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
|
||||
("game-trails", "art"),
|
||||
("energy-beams", "art"),
|
||||
("dry-media", "art"),
|
||||
("impact-bursts", "art"),
|
||||
("arrows", "art"),
|
||||
("image-brush", "scatter"),
|
||||
("artistic", "art"),
|
||||
|
||||
@@ -284,6 +284,67 @@ fn image_widths(bytes: &[u8]) -> Vec<u32> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `render.colorModel` outside document, grayscale and bitmap is refused before the document
|
||||
/// changes. A valid one is saved with the effect and read back, and Grayscale gives the image
|
||||
/// Expand Appearance leaves gray pixels, stored as a gray PNG.
|
||||
#[test]
|
||||
fn a_rendered_3d_color_model_is_checked_saved_and_drawn() {
|
||||
let mut s = rendered_square(&[]);
|
||||
let object = |s: &Session| {
|
||||
let mut found = None;
|
||||
for l in &s.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |n| {
|
||||
if n.appearance.effects.iter().any(|e| e.id == "threeD.extrude") {
|
||||
found = Some(n.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
found.unwrap()
|
||||
};
|
||||
let before = object(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!("sepia"), json!("rgb"), json!(null), json!(2)] {
|
||||
let params = json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "colorModel": bad}}});
|
||||
let e = s.execute("effect.setParams", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("colorModel (document, grayscale or bitmap)"), "{bad}: {e}");
|
||||
}
|
||||
assert_eq!(object(&s), before, "a refused color model leaves the object unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(
|
||||
&mut s,
|
||||
"effect.setParams",
|
||||
json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low", "colorModel": "grayscale"}}}),
|
||||
);
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let mut models = vec![];
|
||||
for l in &back.layers {
|
||||
l.walk(&mut |n| {
|
||||
for e in n.appearance.effects.iter().filter(|e| e.id == "threeD.extrude") {
|
||||
models.push(vectorcraft_render::effects::render_settings(&e.id, &e.params).map(|r| r.color_model));
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(models, vec![Some(vectorcraft_doc::RasterColorModel::Grayscale)], "the saved file keeps the color model");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let mut keys = vec![];
|
||||
for l in &doc.layers {
|
||||
l.walk(&mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(keys.len(), 1, "{keys:?}");
|
||||
let decoded = image::load_from_memory(&doc.images[&keys[0]].bytes).unwrap();
|
||||
assert!(matches!(decoded.color(), image::ColorType::L8 | image::ColorType::La8), "a gray image is stored gray: {:?}", decoded.color());
|
||||
let pixels = decoded.to_rgba8();
|
||||
let opaque = pixels.pixels().filter(|p| p[3] == 255).count();
|
||||
assert!(opaque > 0, "the image covers the solid");
|
||||
let colored: Vec<_> = pixels.pixels().filter(|p| p[3] > 0 && !(p[0] == p[1] && p[1] == p[2])).take(4).collect();
|
||||
assert!(colored.is_empty(), "pixels with color in a grayscale image: {colored:?}");
|
||||
}
|
||||
|
||||
/// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one
|
||||
/// embedded image of the same size in pixels that covers the object.
|
||||
#[test]
|
||||
|
||||
@@ -846,3 +846,58 @@ fn a_command_during_a_quick_pen_press_runs_inside_it() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_drag_advances_its_baseline_revision() {
|
||||
for real_time in [true, false] {
|
||||
let (mut s, _, other) = two_squares(real_time);
|
||||
s.select_tool("selection", view()).unwrap();
|
||||
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
|
||||
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
|
||||
let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision;
|
||||
pointer(&mut s, PointerKind::Drag, 150.0, 140.0);
|
||||
assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, revision, "previews keep the baseline revision");
|
||||
s.execute("appearance.setItem", &json!({"ids": [other.0], "index": 1, "weight": 3})).unwrap();
|
||||
let rebased = s.doc().unwrap().interaction.as_ref().unwrap().revision;
|
||||
assert!(rebased > revision, "an outside document edit advances the baseline revision");
|
||||
pointer(&mut s, PointerKind::Drag, 160.0, 150.0);
|
||||
assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, rebased, "later previews keep the rebased revision");
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(other).unwrap().appearance.stroke().unwrap().width, 3.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_change_during_an_interaction_advances_its_baseline_revision() {
|
||||
let (mut s, _) = session(true);
|
||||
s.begin_interaction("Grid").unwrap();
|
||||
let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision;
|
||||
crate::cmd::distortcmds::silent(&mut s, |grid| grid.visible = !grid.visible).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let it = st.interaction.as_ref().unwrap();
|
||||
assert!(it.revision > revision, "a direct baseline change advances its revision");
|
||||
assert_eq!(crate::cmd::distortcmds::grid_of(&it.doc).visible, crate::cmd::distortcmds::grid_of(&st.doc).visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_perspective_type_editing_during_an_interaction_advances_its_baseline_revision() {
|
||||
let (mut s, _) = crate::tests_persp_select::persp_session();
|
||||
let r = s.execute("text.create", &json!({"x": 430, "y": 400, "text": "HELLO", "size": 48})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("perspective.attach", &json!({"ids": [id.0], "plane": "right"})).unwrap();
|
||||
s.execute("perspective.editText", &json!({"id": id.0})).unwrap();
|
||||
s.begin_interaction("Edit").unwrap();
|
||||
let it = s.doc().unwrap().interaction.as_ref().unwrap();
|
||||
let revision = it.revision;
|
||||
let text = it.doc.node(id).unwrap();
|
||||
assert!(text.extras().perspective.as_deref().unwrap().editing, "the baseline starts in Edit Text mode");
|
||||
assert!(text.projection().is_none(), "the baseline text is flat while editing");
|
||||
crate::cmd::distortcmds::finish_edit_text(s.doc_mut().unwrap(), id);
|
||||
let st = s.doc().unwrap();
|
||||
let it = st.interaction.as_ref().unwrap();
|
||||
let text = it.doc.node(id).unwrap();
|
||||
assert!(!text.extras().perspective.as_deref().unwrap().editing, "the baseline leaves Edit Text mode");
|
||||
assert!(text.projection().is_some(), "the baseline text is projected again");
|
||||
assert!(it.revision > revision, "leaving Edit Text advances the baseline revision");
|
||||
assert_eq!(it.revision, st.revision, "the baseline revision is the document's new revision");
|
||||
}
|
||||
@@ -875,3 +875,30 @@ fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() {
|
||||
let (layer, at) = place_of(&s, g);
|
||||
assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order");
|
||||
}
|
||||
|
||||
/// A restored Objects on Path member keeps the paints for new art as they are, as the journal
|
||||
/// entry that records it (`object.objectsOnPath.selectMember`) does when it is replayed.
|
||||
#[test]
|
||||
fn a_restored_member_leaves_the_same_paints_live_and_on_replay() {
|
||||
let mut s = session();
|
||||
let (g, [a, b, c], _) = three_on_a_line(&mut s);
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0, b.0, c.0, g.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("object.objectsOnPath.selectMember", &json!({"member": b.0})).unwrap();
|
||||
let saved = s.doc().unwrap().selection.clone();
|
||||
let blue = rect(&mut s, 400.0, 0.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [blue.0], "color": "#0000ff"})).unwrap();
|
||||
select(&mut s, &[blue]);
|
||||
let before = s.paint.clone();
|
||||
let (uid, from) = (s.doc().unwrap().uid, s.journal.len());
|
||||
s.restore_selection(uid, saved.clone()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection, saved);
|
||||
assert_eq!(s.paint, before, "selecting a member keeps the paints for new art");
|
||||
let steps = s.journal.since(from).to_vec();
|
||||
assert_eq!(steps.iter().map(|(c, _)| c.as_str()).collect::<Vec<_>>(), ["object.objectsOnPath.selectMember"]);
|
||||
select(&mut s, &[blue]);
|
||||
for (cmd, p) in steps {
|
||||
s.execute(&cmd, &p).unwrap();
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().selection, saved);
|
||||
assert_eq!(s.paint, before, "the replay leaves the same paints");
|
||||
}
|
||||
@@ -1507,7 +1507,7 @@ fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() {
|
||||
n
|
||||
};
|
||||
let prefix = vectorcraft_doc::placed_document::RESOURCE_PREFIX;
|
||||
let older = vectorcraft_format::VERSION - 1;
|
||||
let older = vectorcraft_format::PLACED_SINCE - 1;
|
||||
let old =
|
||||
vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": older})).unwrap())).unwrap();
|
||||
assert_eq!(placed_in_brushes(&old), 0, "{}", old.unknown[vectorcraft_brush::DOC_KEY]);
|
||||
@@ -1519,6 +1519,8 @@ fn saved_for_older_apps_placed_documents_in_brush_art_become_their_art() {
|
||||
let current = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap())).unwrap();
|
||||
assert_eq!(placed_in_brushes(¤t), 2, "the current version keeps them placed");
|
||||
assert!(current.symbols.iter().all(|s| !s.name.starts_with(prefix)));
|
||||
let v4 = vectorcraft_format::load(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "version": 4})).unwrap())).unwrap();
|
||||
assert_eq!(placed_in_brushes(&v4), 2, "version 4 keeps them placed too");
|
||||
// With a precision, the preview shows the brushes' art as the file holds it, rounded.
|
||||
let file = decode(&s.execute("file.saveCopy", &json!({"version": older, "precision": 0, "preview": true})).unwrap());
|
||||
let saved = vectorcraft_format::load(&file).unwrap();
|
||||
|
||||
@@ -12,12 +12,33 @@ fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// A session with a 400 × 200 document that takes `grant` from requests.
|
||||
fn session() -> Session {
|
||||
/// A session that holds [`crate::plugin_events::hold_event_plugins`] while it lives.
|
||||
struct Held {
|
||||
s: Session,
|
||||
_held: crate::plugin_events::EventPluginsHeld,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Held {
|
||||
type Target = Session;
|
||||
fn deref(&self) -> &Session {
|
||||
&self.s
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for Held {
|
||||
fn deref_mut(&mut self) -> &mut Session {
|
||||
&mut self.s
|
||||
}
|
||||
}
|
||||
|
||||
/// A session with a 400 × 200 document that takes `grant` from requests. The plug-ins its test
|
||||
/// installs are the only events plug-ins installed while it lives.
|
||||
fn session() -> Held {
|
||||
let held = crate::plugin_events::hold_event_plugins();
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s
|
||||
Held { s, _held: held }
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
|
||||
@@ -91,6 +91,21 @@ fn settings_report_change_in_one_step_and_reject_junk() {
|
||||
assert_eq!(s.execute(C, &json!({"colorModel": "cmyk"})).unwrap()["colorModel"], "cmyk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolution_given_as_text_reads_digits_of_other_scripts() {
|
||||
let mut s = session();
|
||||
let r = s.execute(C, &json!({"resolution": "३०० ppi"})).unwrap();
|
||||
assert_eq!(r["resolution"].as_f64(), Some(300.0));
|
||||
assert_eq!(s.doc().unwrap().doc.raster_effects_ppi, 300.0);
|
||||
// One digit set per number, exponent included, and the same 1 to 2400 ppi range as ASCII digits.
|
||||
for bad in ["1५0", "५०००", "१e2", "1e२", "१e+2"] {
|
||||
assert!(s.execute(C, &json!({"resolution": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), 1);
|
||||
let r = s.execute(C, &json!({"resolution": "१e२"})).unwrap();
|
||||
assert_eq!(r["resolution"].as_f64(), Some(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_white_background_makes_effect_images_opaque() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -802,7 +802,7 @@ fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() {
|
||||
/// it became is named by a fresh wrapper.
|
||||
#[test]
|
||||
fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() {
|
||||
let base = folder("stale-relative");
|
||||
let base = folder("stale-relative-move");
|
||||
let a = base.join("main/a.png");
|
||||
std::fs::write(&a, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<String> {
|
||||
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::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
@@ -10,6 +10,11 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind
|
||||
|
||||
use crate::{EngineError, Prefs, Result, Session};
|
||||
|
||||
pub(crate) struct FreeformPointPick {
|
||||
document: (u64, u64, u64),
|
||||
index: usize,
|
||||
}
|
||||
|
||||
/// What a hover's lend decision holds for ([`Session::hover_tool_at`]).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub(crate) struct HoverKey {
|
||||
@@ -229,6 +234,7 @@ impl Session {
|
||||
self.tool = self.make_tool(id);
|
||||
// A pick is armed for a stop after its tool is chosen (`note_stop_pick`).
|
||||
self.stop_pick = None;
|
||||
self.freeform_point_pick = None;
|
||||
if let Some(selection) = text_selection {
|
||||
self.tool.set_option("textSelection", &selection);
|
||||
}
|
||||
@@ -633,7 +639,7 @@ impl Session {
|
||||
appearance_item: self.appearance_item(),
|
||||
constrain_angle: self.prefs.constrain_angle,
|
||||
keyboard_increment: self.prefs.keyboard_increment,
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
freeform_point: if self.tool.id() == "eyedropper" { self.pick_freeform_point() } else { self.selected_freeform_point() },
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
scale_strokes: self.prefs.scale_strokes,
|
||||
@@ -1637,6 +1643,9 @@ impl Session {
|
||||
let sets_pressed = self.press_taken_by(self.tool.id());
|
||||
self.tool.set_option(key, v);
|
||||
self.note_stop_pick(key, self.tool.id() == "eyedropper");
|
||||
if key == "freeformPoint" && self.tool.id() == "eyedropper" {
|
||||
self.note_freeform_point_pick(v);
|
||||
}
|
||||
self.tool_set_since_reset = true;
|
||||
self.keep_tool_settings();
|
||||
self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed);
|
||||
@@ -1733,9 +1742,14 @@ impl Session {
|
||||
};
|
||||
self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed);
|
||||
// The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one.
|
||||
if (active || lender) && values.contains_key("stop") {
|
||||
if active || lender {
|
||||
let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper";
|
||||
self.note_stop_pick("stop", eyedropper);
|
||||
if values.contains_key("stop") {
|
||||
self.note_stop_pick("stop", eyedropper);
|
||||
}
|
||||
if eyedropper && let Some(v) = values.get("freeformPoint") {
|
||||
self.note_freeform_point_pick(v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1761,6 +1775,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn note_freeform_point_pick(&mut self, option: &Value) {
|
||||
self.freeform_point_pick = None;
|
||||
if option.is_string()
|
||||
&& let Some(doc) = self.active()
|
||||
&& let Some(index) = self.selected_freeform_point()
|
||||
&& self.proxy_freeform(!self.fill_active).is_some_and(|(f, _)| index < f.points.len())
|
||||
{
|
||||
self.freeform_point_pick = Some(FreeformPointPick { document: (doc.uid, doc.revision, doc.reverts), index });
|
||||
}
|
||||
}
|
||||
|
||||
/// An index can outlive its point after a deletion or another paint is applied.
|
||||
fn pick_freeform_point(&self) -> Option<usize> {
|
||||
let pick = self.freeform_point_pick.as_ref()?;
|
||||
let doc = self.active()?;
|
||||
self.selected_freeform_point().filter(|&index| index == pick.index && pick.document == (doc.uid, doc.revision, doc.reverts))
|
||||
}
|
||||
|
||||
/// The tool that took the press under way: the active tool, or the tool that lent a selection
|
||||
/// tool for it (a Cmd-drag), which the dropped press gives its options back to.
|
||||
fn pressed_tool(&self) -> Option<&dyn Tool> {
|
||||
|
||||
@@ -4161,10 +4161,7 @@ proptest! {
|
||||
|
||||
// ---------- Binary CGM files: opened and placed ----------
|
||||
|
||||
// The CGM reader waits on craft-libs#5410: everything here is behind the `cgm` feature.
|
||||
|
||||
/// One CGM element, in the long form past 30 bytes, padded to an even length.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
if data.len() < 31 {
|
||||
@@ -4181,7 +4178,6 @@ fn cgm_el(class: u16, id: u16, data: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// A metafile of one picture holding `body`.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut b = cgm_el(0, 1, b"\x01x");
|
||||
b.extend(cgm_el(1, 1, &be16(&[3])));
|
||||
@@ -4198,7 +4194,6 @@ fn cgm_of(body: &[(u16, u16, Vec<u8>)]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// A picture with lines, shapes, arcs, a figure, markers, text, a cell array and a clip.
|
||||
#[cfg(feature = "cgm")]
|
||||
fn cgm_sample() -> Vec<u8> {
|
||||
cgm_of(&[
|
||||
(5, 34, vec![8, 10, 20, 30, 40, 50, 60]),
|
||||
@@ -4232,7 +4227,6 @@ fn cgm_sample() -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// The sample the mutations start from opens with art, type and an image.
|
||||
#[cfg(feature = "cgm")]
|
||||
#[test]
|
||||
fn the_cgm_sample_opens() {
|
||||
let l = vectorcraft_engine::cmd::fileio::load("x.cgm", &cgm_sample()).unwrap();
|
||||
@@ -4249,14 +4243,12 @@ fn the_cgm_sample_opens() {
|
||||
|
||||
/// CGM elements VectorCraft reads, and some it skips: the class in the high byte, the id in the
|
||||
/// low one.
|
||||
#[cfg(feature = "cgm")]
|
||||
const CGM_ELEMENTS: [u16; 44] = [
|
||||
0x0008, 0x0009, 0x0103, 0x0104, 0x0105, 0x0107, 0x010A, 0x010C, 0x010D, 0x0113, 0x0201, 0x0202, 0x0203, 0x0207, 0x0301, 0x0302, 0x0305, 0x0306,
|
||||
0x030A, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040B, 0x040C, 0x040D, 0x040F, 0x0411, 0x0412, 0x0414, 0x0418,
|
||||
0x041A, 0x0503, 0x0504, 0x050F, 0x0510, 0x0512, 0x0522, 0x0801,
|
||||
];
|
||||
|
||||
#[cfg(feature = "cgm")]
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
|
||||
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
|
||||
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
|
||||
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
|
||||
//! the tile or is painted with patterns, and pattern fills in large-canvas symbols, as their tiles cut
|
||||
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
|
||||
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
|
||||
//! stroke not; an image in a clipping group of the region it is cut to), images that can't be
|
||||
@@ -225,7 +225,7 @@ use vectorcraft_pdf::PrivateData;
|
||||
use crate::ps;
|
||||
|
||||
mod writer;
|
||||
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
|
||||
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
|
||||
|
||||
use writer::Writer;
|
||||
|
||||
|
||||
@@ -6682,12 +6682,12 @@ fn instances_the_data_cant_hold_are_written_as_their_art() {
|
||||
}
|
||||
|
||||
/// Symbols whose art paints with a pattern, directly, through a nested symbol, in an opacity mask
|
||||
/// and through an inline graphic: their definitions hold the pattern fills as tiles cut to the shape (the reader keeps no
|
||||
/// symbol whose art paints with a pattern), and their instances are written as their art, whose
|
||||
/// and through an inline graphic: their definitions retain native pattern resources, and their
|
||||
/// instances are written as their art, whose
|
||||
/// pattern fills keep the document's placement as the canvas draws them, each with a warning. An
|
||||
/// instance of a symbol without pattern paint stays an instance.
|
||||
#[test]
|
||||
fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
fn symbols_with_pattern_fills_keep_resources_and_place_as_art() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
// Tiles that cover the shape, so its tiles cut to it draw its box.
|
||||
let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK));
|
||||
@@ -6722,12 +6722,17 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 182.0, 42.0)), fill());
|
||||
doc.insert(Some(layer), usize::MAX, filled).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART) && out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "grid resources must not become tiles: {:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let names: Vec<&str> = back.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Patch", "Outer", "Masked", "Plain", "Typed"]);
|
||||
let patch = &back.symbols[0].art;
|
||||
assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind);
|
||||
assert!(
|
||||
matches!(patch.kind, NodeKind::Path { .. }) && vectorcraft_doc::pattern::uses_pattern(patch, Some("Dots")),
|
||||
"the symbol must retain its original pattern-filled path: {:?}",
|
||||
patch.kind
|
||||
);
|
||||
assert_eq!(instances(&back.symbols[1].art), 0, "the nested instance is its art");
|
||||
let kids = back.layers[0].children().unwrap();
|
||||
let kinds: Vec<bool> = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect();
|
||||
@@ -6757,8 +6762,164 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
|
||||
same_lines(&boxes(&back), &boxes(&doc));
|
||||
}
|
||||
|
||||
/// Original ruled tile shared by symbol art and an ordinary canvas object. The symbol's pattern
|
||||
/// and geometry are scaled together, as editing its art with Transform Pattern Tiles does.
|
||||
fn ruled_pattern_symbol(strokes: bool, tile_type: vectorcraft_doc::TileType, extent: f64) -> Document {
|
||||
let mut doc = Document::new(240.0, 140.0);
|
||||
let line =
|
||||
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 2.0));
|
||||
let mut tile = vectorcraft_doc::PatternDef::new("Rules", vec![Arc::new(line)]);
|
||||
tile.tile = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
tile.tile_type = tile_type;
|
||||
doc.patterns.push(tile);
|
||||
let fill = || Appearance::basic(Paint::Pattern { pattern: "Rules".into(), xf: Affine::IDENTITY }, Paint::None, 0.0);
|
||||
let mut art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, extent, extent)), fill());
|
||||
art.transform(Affine::scale(0.2), vectorcraft_doc::Scaling { strokes, patterns: true, ..Default::default() });
|
||||
doc.symbols.push(Symbol { name: "Scaled".into(), art: Arc::new(art), dynamic: false });
|
||||
let layer = doc.layers[0].id;
|
||||
let one = instance(&mut doc, "Scaled", Affine::translate((20.0, 20.0)));
|
||||
doc.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let shared = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(125.0, 5.0, 225.0, 105.0)), fill());
|
||||
doc.insert(Some(layer), usize::MAX, shared).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaled_pattern_symbol_keeps_native_pattern_resources_in_editing_data() {
|
||||
let small = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
let large = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 200.0);
|
||||
let (a, b) = (program(&small), program(&large));
|
||||
eprintln!("pattern symbol editing bytes: {} -> {} for four times the tile area", a.len(), b.len());
|
||||
let back = read_back(&small);
|
||||
let art = &back.symbols.iter().find(|s| s.name == "Scaled").unwrap().art;
|
||||
assert!(vectorcraft_doc::pattern::uses_pattern(art, Some("Rules")), "the symbol must retain pattern paint rather than one object per tile");
|
||||
assert_eq!(a.matches("%AI3_BeginPattern: (Rules)").count(), 1);
|
||||
assert!(b.len() < a.len() * 2, "editing data must not grow with every covered tile: {} -> {}", a.len(), b.len());
|
||||
let tile = back.pattern("Rules").unwrap();
|
||||
assert_eq!(tile.tile, small.patterns[0].tile);
|
||||
assert_eq!(tile.art[0].geometric_bounds().unwrap().width(), 8.0);
|
||||
let strokes: Vec<_> =
|
||||
tile.art[0].appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(stroke) = i { Some(stroke.width) } else { None }).collect();
|
||||
assert_eq!(strokes, [2.0], "the shared tile keeps its original stroke");
|
||||
}
|
||||
|
||||
// Four editing-stream round trips and native raster probes cover the flag and fallback cases.
|
||||
#[test]
|
||||
fn scaled_pattern_symbol_new_instances_match_native_tile_stroke_weight() {
|
||||
for strokes in [true, false] {
|
||||
for tile_type in [vectorcraft_doc::TileType::Grid, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }] {
|
||||
let doc = ruled_pattern_symbol(strokes, tile_type, 100.0);
|
||||
// Native rendering scales a 2pt pattern stroke to 0.4pt with its pattern affine,
|
||||
// under either flag. The flag controls the selected object's own stroke separately.
|
||||
let native = vectorcraft_testkit::raster::render_region(&doc, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
|
||||
let native_weight = (0..native.height).filter(|y| native.pixel(20, *y)[0] < 64).count();
|
||||
assert!((6..=10).contains(&native_weight), "native weight={native_weight}, strokes={strokes}, {tile_type:?}");
|
||||
let mut back = read_back(&doc);
|
||||
// Place afresh from the editing stream's symbol definition, rather than measuring
|
||||
// the already-expanded canvas instance or the file's native payload.
|
||||
back.layers.clear();
|
||||
let layer = back.add_layer(Some("New instance"));
|
||||
let one = instance(&mut back, "Scaled", Affine::translate((20.0, 20.0)));
|
||||
back.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let placed = vectorcraft_testkit::raster::render_region(&back, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
|
||||
let weight = (0..placed.height).filter(|y| placed.pixel(20, *y)[0] < 64).count();
|
||||
assert!((6..=10).contains(&weight), "editing symbol weight={weight}, native={native_weight}, strokes={strokes}, {tile_type:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each case goes through the real editing stream and renderer: the mask stroke has to be
|
||||
// transformed as geometry even when writing its dictionary temporarily clears the tile clip.
|
||||
#[test]
|
||||
fn pattern_tile_fallback_preserves_affine_mask_stroke_weight() {
|
||||
for matrix in
|
||||
[Affine::scale(0.2), Affine::scale_non_uniform(0.2, 0.4), Affine::new([0.2, 0.0, 0.1, 0.2, 0.0, 0.0]), Affine::scale_non_uniform(-0.2, 0.2)]
|
||||
{
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, 100.0);
|
||||
let white_line =
|
||||
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::WHITE), 2.0));
|
||||
let mut tile = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK);
|
||||
tile.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(white_line), clip: true, invert: false, disabled: false, linked: true }));
|
||||
doc.patterns[0].art = vec![Arc::new(tile)];
|
||||
Arc::make_mut(&mut doc.symbols[0].art)
|
||||
.transform(matrix * Affine::scale(5.0), vectorcraft_doc::Scaling { patterns: true, ..Default::default() });
|
||||
// This fallback bakes the unsupported brick phase. Place on whole super-tile periods
|
||||
// so the probe isolates stroke geometry, rather than that existing placement limitation.
|
||||
doc.layers.clear();
|
||||
let native_layer = doc.add_layer(Some("Native instance"));
|
||||
let native_one = instance(&mut doc, "Scaled", Affine::translate((60.0, 40.0)));
|
||||
doc.insert(Some(native_layer), usize::MAX, native_one).unwrap();
|
||||
let bounds = doc.symbols[0].art.geometric_bounds().unwrap() + vectorcraft_geom::Vec2::new(60.0, 40.0);
|
||||
let period_y = 10.0 * matrix.as_coeffs()[3].abs();
|
||||
let region = Rect::new(bounds.x0, bounds.y0, bounds.x0 + 2.0, bounds.y0 + period_y);
|
||||
let native = vectorcraft_testkit::raster::render_region(&doc, region, 20.0);
|
||||
// Brick rows shift the line horizontally; select a visible native column and compare
|
||||
// that same column after the editing-stream round trip.
|
||||
let (column, native_weight) = (0..native.width)
|
||||
.map(|x| (x, (0..native.height).filter(|y| native.pixel(x, *y)[0] < 64).count()))
|
||||
.max_by_key(|(_, weight)| *weight)
|
||||
.unwrap();
|
||||
assert!(native_weight > 0 && native_weight < native.height as usize, "native mask stroke: {matrix:?}, {native_weight}");
|
||||
let mut back = read_back(&doc);
|
||||
back.layers.clear();
|
||||
let layer = back.add_layer(Some("New instance"));
|
||||
let one = instance(&mut back, "Scaled", Affine::translate((60.0, 40.0)));
|
||||
back.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let placed = vectorcraft_testkit::raster::render_region(&back, region, 20.0);
|
||||
let weight = (0..placed.height).filter(|y| placed.pixel(column, *y)[0] < 64).count();
|
||||
assert!(weight.abs_diff(native_weight) <= 2, "mask stroke {matrix:?}: editing={weight}, native={native_weight}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_definition_dictionary_is_scoped_away_from_its_symbol() {
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
// Definitions can hold freshly generated id-less art. Its dictionary must not consume the
|
||||
// surrounding symbol's root entries just because these independent art scopes share id 0.
|
||||
Arc::make_mut(&mut doc.patterns[0].art[0]).id = vectorcraft_doc::NodeId(0);
|
||||
let art = (*doc.symbols[0].art).clone();
|
||||
let other = square(&mut doc, Rect::new(25.0, 0.0, 30.0, 5.0), Color::BLACK);
|
||||
let mut root = group(&mut doc, vec![art, other], false);
|
||||
root.id = vectorcraft_doc::NodeId(0);
|
||||
doc.symbols[0].art = Arc::new(root);
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("pattern art must not steal its symbol's declaration");
|
||||
let mut uses = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| uses |= vectorcraft_doc::pattern::uses_pattern(n, Some("Rules")));
|
||||
assert!(uses);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_pattern_matrices_stay_readable_or_use_the_bounded_fallback() {
|
||||
for scale in [0.00001, 0.0, 1e-9] {
|
||||
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
|
||||
let art = Arc::make_mut(&mut doc.symbols[0].art);
|
||||
for item in art.appearance.items.iter_mut() {
|
||||
if let Paint::Pattern { xf, .. } = item.paint_mut() {
|
||||
*xf = Affine::scale(scale);
|
||||
}
|
||||
}
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("a bad paint matrix must not discard its symbol");
|
||||
let mut paints = vec![];
|
||||
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
if let Paint::Pattern { xf, .. } = item.paint() {
|
||||
paints.push(*xf);
|
||||
}
|
||||
}
|
||||
});
|
||||
if scale == 0.00001 {
|
||||
assert_eq!(paints, [Affine::scale(scale)], "a small invertible affine must survive serialization");
|
||||
} else {
|
||||
assert!(paints.is_empty() && out.warnings.iter().any(|w| w == writer::PATTERN_PLACEMENT), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol whose art paints with a pattern only through a brushed stroke, whose brush's art is
|
||||
/// filled with a pattern: the definition holds the tiles, and its instance is written as its art.
|
||||
/// filled with a pattern: the definition keeps that resource, and its instance is written as art.
|
||||
#[test]
|
||||
fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
@@ -6786,9 +6947,13 @@ fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
|
||||
doc.insert(Some(layer), usize::MAX, one).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Brushed"]);
|
||||
assert_eq!(instances(&back.layers[0]), 0, "the instance is its art");
|
||||
let mut pattern = false;
|
||||
vectorcraft_doc::swatches::walk_with_masks(&back.symbols[0].art, &mut |n| pattern |= vectorcraft_doc::pattern::uses_pattern(n, Some("Dots")));
|
||||
assert!(pattern, "indirect brush paint retains its pattern resource in the definition");
|
||||
}
|
||||
|
||||
/// A symbol first defined from the drawn look of a group with a style, through a member's scatter
|
||||
|
||||
@@ -48,7 +48,7 @@ pub(super) use paints::{
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
|
||||
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, OVERRIDE_SERIALIZATIONS, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
#[cfg(test)]
|
||||
@@ -62,8 +62,10 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
|
||||
pub(super) const MAX_NEST: u32 = 8;
|
||||
|
||||
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
|
||||
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
|
||||
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a large canvas's symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
|
||||
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
|
||||
pub(super) const PATTERN_PLACEMENT: &str =
|
||||
"pattern fills and strokes whose placement cannot be read are written gray in the editing data for other apps";
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
@@ -270,10 +272,10 @@ pub(super) struct Writer<'a> {
|
||||
/// ([`Self::symbol_paints_pattern`]).
|
||||
patterned_symbols: HashMap<String, bool>,
|
||||
symbol_omissions: HashMap<*const Node, symbols::OmissionFacts>,
|
||||
/// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over
|
||||
/// Pattern references or tiles were written in the art ([`Self::define_symbol`] starts it over
|
||||
/// for each symbol's art).
|
||||
wrote_pattern: bool,
|
||||
/// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live
|
||||
/// The symbols whose definitions write pattern paint: a brushed stroke's brush art or a live
|
||||
/// object's art can paint with a pattern that the symbol's own objects don't name.
|
||||
pattern_written: HashSet<String>,
|
||||
/// Art that draws as it should only where it is was written in the art being written
|
||||
@@ -1034,6 +1036,7 @@ impl<'a> Writer<'a> {
|
||||
mask = None;
|
||||
mask_written = false;
|
||||
}
|
||||
let symbol_root = self.root_entries.as_ref().is_some_and(|(id, _)| *id == n.id);
|
||||
let entries = match &self.root_entries {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
@@ -1084,6 +1087,10 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
mask_written = false;
|
||||
}
|
||||
// A pattern may first be written by the root's mask, so declare its space afterwards.
|
||||
if symbol_root && self.in_symbol && self.symbols_live && self.wrote_pattern {
|
||||
let _ = writeln!(self.body, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
|
||||
}
|
||||
self.body.push_str("%_;\n%_\n");
|
||||
mask_written
|
||||
}
|
||||
@@ -1483,7 +1490,8 @@ impl<'a> Writer<'a> {
|
||||
let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() };
|
||||
return self.path_object(path, rule, Some(&flat), None, xy);
|
||||
};
|
||||
let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box());
|
||||
let inverse = xf.inverse();
|
||||
let tiles = def.instances_in(Affine::IDENTITY, inverse.transform_rect_bbox(path.to_bezpath().bounding_box()));
|
||||
// More tiles than a fill places come back as none: the shape is filled gray, as a
|
||||
// pattern that isn't found is.
|
||||
if tiles.is_empty() && !def.art.is_empty() {
|
||||
@@ -1497,8 +1505,26 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
self.wrote_pattern = true;
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(path, rule);
|
||||
let mut region = self.cut(path, rule);
|
||||
region.transform(inverse);
|
||||
self.clip = Some(region);
|
||||
let shown = std::mem::take(&mut self.shown);
|
||||
self.shown = shown
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.apply_affine(inverse);
|
||||
p
|
||||
})
|
||||
.collect();
|
||||
// Outline and clip strokes in pattern space before applying its affine. Moving
|
||||
// just their centerlines first kept 2pt strokes at 2pt under a 20% pattern scale;
|
||||
// scaling by one mean factor would still distort nonuniform/sheared patterns.
|
||||
let spaces = (self.to_art, self.grad_space, self.canvas, self.instance_space);
|
||||
self.to_art *= *xf;
|
||||
self.grad_space *= *xf;
|
||||
self.canvas *= *xf;
|
||||
self.instance_space *= *xf;
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for t in &tiles {
|
||||
@@ -1511,6 +1537,8 @@ impl<'a> Writer<'a> {
|
||||
self.end_group("U", xy);
|
||||
self.nest -= 1;
|
||||
self.clip = outer;
|
||||
self.shown = shown;
|
||||
(self.to_art, self.grad_space, self.canvas, self.instance_space) = spaces;
|
||||
}
|
||||
Paint::None => {}
|
||||
}
|
||||
|
||||
@@ -430,7 +430,7 @@ impl Writer<'_> {
|
||||
}
|
||||
|
||||
/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four).
|
||||
fn matrix(m: Affine) -> String {
|
||||
pub(super) fn matrix(m: Affine) -> String {
|
||||
let n: Vec<String> = m.as_coeffs().iter().map(|v| precise(*v)).collect();
|
||||
format!("[{}]", n.join(" "))
|
||||
}
|
||||
|
||||
@@ -366,7 +366,12 @@ impl Writer<'_> {
|
||||
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
|
||||
/// write it)?
|
||||
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
|
||||
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
let [a, b, c, d, ..] = self.to_art.as_coeffs();
|
||||
// Operators receive transformed path coordinates, but their width is in art units.
|
||||
// A non-isometric map needs the stroke's outline transformed too (including in masks,
|
||||
// whose dictionary temporarily clears the clipping region of a pattern fallback).
|
||||
let isometry = (a * a + b * b - 1.0).abs() < 1e-9 && (c * c + d * d - 1.0).abs() < 1e-9 && (a * c + b * d).abs() < 1e-9;
|
||||
isometry && self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
|
||||
}
|
||||
|
||||
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
|
||||
@@ -575,10 +580,10 @@ impl Writer<'_> {
|
||||
|
||||
/// Can pattern `name` be written as a definition and painted with from here: the document has
|
||||
/// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used
|
||||
/// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with
|
||||
/// a pattern) or nested more than [`MAX_NEST`] deep?
|
||||
/// in another pattern's tile or nested more than [`MAX_NEST`] deep? A large canvas's symbol
|
||||
/// art uses the original document, whose same-name tiles can differ from the reduced page's.
|
||||
pub(super) fn pattern_writable(&self, name: &str) -> bool {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || (self.in_symbol && !self.symbols_live) {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.find(name).is_some() {
|
||||
@@ -604,7 +609,14 @@ impl Writer<'_> {
|
||||
let doc = self.doc;
|
||||
// The tile's box is an object of the definition ([`Self::take_objects`]).
|
||||
let (before, bound) = (self.charges(), self.bound.len());
|
||||
let Some(def) = doc.pattern(name).filter(|_| self.take_objects(1)) else { return false };
|
||||
let Some(def) = doc.pattern(name) else { return false };
|
||||
// A pattern is a separate global resource, even when first discovered in symbol art.
|
||||
// Charge its objects outside the symbol-art budget and isolate parent dictionaries.
|
||||
let in_symbol = std::mem::take(&mut self.in_symbol);
|
||||
if !self.take_objects(1) {
|
||||
self.in_symbol = in_symbol;
|
||||
return false;
|
||||
}
|
||||
self.defining.push(name.to_string());
|
||||
// The art is written in the pattern's space, y up, from the state a definition starts in.
|
||||
let saved = (
|
||||
@@ -616,6 +628,7 @@ impl Writer<'_> {
|
||||
self.block_end,
|
||||
// The tile's masks' objects are written with their art styles, those of no other art.
|
||||
(std::mem::replace(&mut self.styled, self.pattern_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()),
|
||||
(in_symbol, self.root_entries.take(), self.instance_entries.take(), self.block_start),
|
||||
);
|
||||
// `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its
|
||||
// placement is worked out in the tile's space turned y up.
|
||||
@@ -646,6 +659,7 @@ impl Writer<'_> {
|
||||
(self.clip, self.shown),
|
||||
self.block_end,
|
||||
(self.styled, self.mask_level),
|
||||
(self.in_symbol, self.root_entries, self.instance_entries, self.block_start),
|
||||
) = saved;
|
||||
let art = std::mem::replace(&mut self.body, art);
|
||||
self.defining.pop();
|
||||
@@ -678,7 +692,18 @@ impl Writer<'_> {
|
||||
return self.plain_color(Color::gray(0.5), stroke);
|
||||
};
|
||||
let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y;
|
||||
let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' });
|
||||
let written = Affine::new(m.as_coeffs().map(|v| (v * 1e10).round() / 1e10));
|
||||
// Keep a definition's reference readable after serialization; a singular or rounded-flat
|
||||
// paint must not make the reader discard the entire symbol that contains it.
|
||||
if !written.as_coeffs().iter().all(|v| v.is_finite()) || !written.determinant().is_finite() || written.determinant().abs() < 1e-12 {
|
||||
self.warn(super::PATTERN_PLACEMENT);
|
||||
return self.plain_color(Color::gray(0.5), stroke);
|
||||
}
|
||||
// Indirect pattern paint (for example in brush art) also prevents a live symbol
|
||||
// instance: the canvas keeps its pattern phase fixed when placing that instance.
|
||||
self.wrote_pattern = true;
|
||||
let _ =
|
||||
writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), super::images::matrix(m), if stroke { 'P' } else { 'p' });
|
||||
}
|
||||
|
||||
/// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then
|
||||
|
||||
@@ -19,6 +19,9 @@ pub(in crate::ai_editing) const SYMBOL_CHANGES: &str =
|
||||
"the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out";
|
||||
pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol";
|
||||
pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides";
|
||||
/// Version 1 declares that pattern matrices in this definition use its art coordinates.
|
||||
/// Foreign definitions without that declaration retain the reader's conservative fallback.
|
||||
pub(crate) const PATTERN_SPACE_KEY: &str = "VectorCraftSymbolPatternSpace";
|
||||
const MAX_OVERRIDES_BYTES: usize = 1 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -385,6 +388,9 @@ impl Writer<'_> {
|
||||
if wrap {
|
||||
self.line("u");
|
||||
self.node(root);
|
||||
if self.symbols_live && self.wrote_pattern {
|
||||
let _ = writeln!(entries, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
|
||||
}
|
||||
let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n");
|
||||
} else {
|
||||
// A group always writes its dictionary ([`Self::dictionary`]), which takes the entries.
|
||||
|
||||
@@ -631,8 +631,12 @@ impl<'a> Reader<'a> {
|
||||
let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1;
|
||||
let Some(frame) = sub.frames.pop().filter(|_| measured) else { return };
|
||||
let mut kids = frame.children;
|
||||
// Where a symbol's art puts a pattern's tiles isn't known.
|
||||
let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0));
|
||||
// Unmarked foreign symbols do not declare the coordinate convention of their patterns.
|
||||
// Our writer explicitly declares symbol-art space, so those definitions can retain paint.
|
||||
let whole = !head.left_out
|
||||
&& sub.unread.is_empty()
|
||||
&& sub.hidden_unread.is_empty()
|
||||
&& (head.pattern_space || !kids.iter().any(|n| paints_pattern(n, 0)));
|
||||
if !whole {
|
||||
let boxes = self.doc.symbol_boxes();
|
||||
let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes)));
|
||||
|
||||
@@ -805,6 +805,12 @@ impl<'a> Reader<'a> {
|
||||
{
|
||||
head.dynamic = true;
|
||||
}
|
||||
if self.frames.len() == 1
|
||||
&& let Some(head) = self.symbol.as_mut()
|
||||
&& o.nums(crate::ai_editing::PATTERN_SPACE_KEY).first().copied() == Some(1.0)
|
||||
{
|
||||
head.pattern_space = true;
|
||||
}
|
||||
if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY)
|
||||
&& let Some(bytes) = crate::ai_editing::hex_decode(&text)
|
||||
&& let Ok(list) = serde_json::from_slice::<Vec<vectorcraft_doc::SymbolOverride>>(&bytes)
|
||||
|
||||
@@ -245,6 +245,8 @@ pub(super) struct SymbolHead {
|
||||
/// `AI13PatternRegistrationType` in the dictionary after the art.
|
||||
pub(super) registration: Option<f64>,
|
||||
pub(super) dynamic: bool,
|
||||
/// The writer declares its pattern matrices to be in symbol-art coordinates (version 1).
|
||||
pub(super) pattern_space: bool,
|
||||
/// Art the reader left out (type, a placed file, non-native art, an image it can't read or
|
||||
/// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the
|
||||
/// page draws them, within the box of the rest.
|
||||
|
||||
+38
-23
@@ -33,9 +33,9 @@
|
||||
//! The document has a version of its own (`document.version`, [`vectorcraft_doc::FORMAT_VERSION`]),
|
||||
//! which readers do not check. A version 2 document's Twist effects turn clockwise for a positive
|
||||
//! angle. A version 1 document's Twist angles are negated when it opens, unless the file is of
|
||||
//! [`VERSION`] and its `generator` is VectorCraft 0.21.0 or later, which turned them clockwise
|
||||
//! already; [`save_with`] writes a version 1 document with them negated back for an older file
|
||||
//! version ([`vectorcraft_doc::twist`]).
|
||||
//! [`PLACED_SINCE`] or later and its `generator` is VectorCraft 0.21.0 or later, which turned them
|
||||
//! clockwise already; [`save_with`] writes a version 1 document with them negated back for a file
|
||||
//! version older than [`PLACED_SINCE`] ([`vectorcraft_doc::twist`]).
|
||||
#![forbid(unsafe_code)]
|
||||
#![doc(test(attr(forbid(unsafe_code))))]
|
||||
|
||||
@@ -64,11 +64,16 @@ use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
pub use craft_vectorcraft_format::{
|
||||
BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part,
|
||||
sniff,
|
||||
BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, LIVE_STAR_SINCE, MIN_VERSION, PREVIEW_MAX, VERSION,
|
||||
is_compressed, json_part, sniff,
|
||||
};
|
||||
use stream::Out;
|
||||
|
||||
/// The first version whose files keep placed documents, Color Halftone's Max Radius in pixels and
|
||||
/// Twist angles as they are. A save for an older version writes placed documents as the art they
|
||||
/// show, the radius in points and Twist angles negated back, as apps of those versions read them.
|
||||
pub const PLACED_SINCE: u32 = 4;
|
||||
|
||||
/// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs,
|
||||
/// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them,
|
||||
/// so every file VectorCraft writes reads back. On wasm32 the cap is a quarter of the native
|
||||
@@ -252,7 +257,7 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
|
||||
// resources. Otherwise resources only exporting adds are never saved. The images and placed
|
||||
// documents in the stored brushes' art count as those in the layers do.
|
||||
let linked = with_brush_art(&mut d, |d| {
|
||||
if version < VERSION {
|
||||
if version < PLACED_SINCE {
|
||||
placed_as_groups(d);
|
||||
} else {
|
||||
d.drop_placed_resources();
|
||||
@@ -268,15 +273,15 @@ fn body(doc: &Document, o: &SaveOptions) -> Result<Body, FormatError> {
|
||||
if version < 3 {
|
||||
d.store_legacy_color_profiles();
|
||||
}
|
||||
// Apps before this one's version take Color Halftone's Max Radius in points (#3260), and
|
||||
// predate 0.21.0, turning Twist the other way. The radii first: their conversion runs only on
|
||||
// a document of version 3 or later, and the Twist one then marks it version 1.
|
||||
if version < VERSION {
|
||||
// Apps before version 4 take Color Halftone's Max Radius in points (#3260), and predate
|
||||
// 0.21.0, turning Twist the other way. The radii first: their conversion runs only on a
|
||||
// document of version 3 or later, and the Twist one then marks it version 1.
|
||||
if version < PLACED_SINCE {
|
||||
d.halftone_radii_to_points();
|
||||
d.store_legacy_twist_angles();
|
||||
}
|
||||
// Older apps don't know live stars: they get the outline a star draws as a plain path.
|
||||
if version < VERSION {
|
||||
if version < LIVE_STAR_SINCE {
|
||||
d.live_stars_to_paths();
|
||||
}
|
||||
let v1 = if version == 1 {
|
||||
@@ -309,7 +314,7 @@ pub fn with_brush_art<T>(d: &mut Document, f: impl FnOnce(&mut Document) -> T) -
|
||||
|
||||
/// Every placed document in `d`'s art, the art of its stored brushes included, replaced by a group
|
||||
/// of the art it shows, with the resources that art uses, as a save for a version older than
|
||||
/// [`VERSION`] writes it. Without a placed document, the resources only exporting adds are dropped
|
||||
/// [`PLACED_SINCE`] writes it. Without a placed document, the resources only exporting adds are dropped
|
||||
/// ([`Document::drop_placed_resources`]).
|
||||
pub fn placed_as_groups(d: &mut Document) {
|
||||
with_brush_art(d, |d| {
|
||||
@@ -576,7 +581,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
|
||||
// version): its Twist angles turned the other way. The app that wrote it is read from the JSON
|
||||
// before the data after it is taken; the walk's depth is bounded by the JSON reader's nesting
|
||||
// limit.
|
||||
let current_file = f.version >= VERSION;
|
||||
let current_file = f.version >= PLACED_SINCE;
|
||||
f.document.migrate_twist_angles(|| current_file && vectorcraft_doc::twist::written_clockwise(generator(file.json()).as_deref()));
|
||||
// The bytes after the JSON, read in one pass: the images' first, then the profiles'.
|
||||
let entries: Vec<[u64; 2]> = f.images.values().chain(f.profiles.values()).filter_map(|i| i.blob).collect();
|
||||
@@ -1128,7 +1133,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(checked, 20);
|
||||
// Four for each version, and two compressed for each version from 3.
|
||||
assert_eq!(checked, 4 * (VERSION - MIN_VERSION + 1) + 2 * (VERSION - COMPRESSED_SINCE + 1));
|
||||
}
|
||||
|
||||
/// Files are read through the crate's `Contents` with the messages VectorCraft gave before,
|
||||
@@ -1148,7 +1154,10 @@ mod tests {
|
||||
let doc = v["document"].to_string();
|
||||
let file = |format: &str, version: u32| format!(r#"{{"format":"{format}","version":{version},"document":{doc}}}"#);
|
||||
assert_eq!(message(&file("svg", 4)).as_deref(), Some("not a VectorCraft file: format is `svg`"));
|
||||
assert_eq!(message(&file("vectorcraft", 9)).as_deref(), Some("file version 9 is newer than this VectorCraft supports (4)"));
|
||||
assert_eq!(
|
||||
message(&file("vectorcraft", 9)).as_deref(),
|
||||
Some(format!("file version 9 is newer than this VectorCraft supports ({VERSION})").as_str())
|
||||
);
|
||||
// A document that does not read is reported first, as before.
|
||||
assert!(
|
||||
message(r#"{"format":"vectorcraft","version":9,"document":7}"#).is_some_and(|m| m.starts_with("not a VectorCraft file: invalid type"))
|
||||
@@ -1188,15 +1197,16 @@ mod tests {
|
||||
let old = load(&save(&d, false)).unwrap();
|
||||
assert_eq!(old.version, vectorcraft_doc::FORMAT_VERSION);
|
||||
assert!((radius(&old) - 8.0 * ppi / 72.0).abs() < 1e-9, "8 pt at {ppi} ppi: {}", radius(&old));
|
||||
// Saved for an older app, in every older version: the radius in points, which opens
|
||||
// here in pixels again.
|
||||
// Saved for an older app, in every version before 4: the radius in points, which opens
|
||||
// here in pixels again. Version 4 and later keep it in pixels.
|
||||
let px = radius(&old);
|
||||
for version in MIN_VERSION..VERSION {
|
||||
for version in MIN_VERSION..=VERSION {
|
||||
let bytes = save_with(&old, &SaveOptions { version, ..SaveOptions::default() }).unwrap();
|
||||
let json = String::from_utf8(unpack::Unpacked::new(&bytes).unwrap().json().to_vec()).unwrap();
|
||||
let at = json.find("\"maxRadius\":").unwrap() + "\"maxRadius\":".len();
|
||||
let saved: f64 = json[at..].split([',', '}']).next().unwrap().trim().parse().unwrap();
|
||||
assert!((saved - 8.0).abs() < 1e-9, "{ppi} ppi, version {version} holds 8 pt: {saved}");
|
||||
let want = if version < 4 { 8.0 } else { px };
|
||||
assert!((saved - want).abs() < 1e-9, "{ppi} ppi, version {version} holds {want}: {saved}");
|
||||
let back = load(&bytes).unwrap();
|
||||
assert!((radius(&back) - px).abs() < 1e-9, "{ppi} ppi, version {version}: {}", radius(&back));
|
||||
}
|
||||
@@ -1410,15 +1420,20 @@ mod tests {
|
||||
let again = load(&save(&old, false)).unwrap();
|
||||
assert_eq!((again.version, angle(&again)), (now, Some(-30.0)), "saved again, it is the current version");
|
||||
// Saved for an older file version (apps before 0.21.0): version 1 with the angle negated
|
||||
// back, whatever the generator, and it reopens as it was.
|
||||
for version in MIN_VERSION..VERSION {
|
||||
// back, whatever the generator, and it reopens as it was. Version 4 and later keep it.
|
||||
for version in MIN_VERSION..=VERSION {
|
||||
let bytes = save_with(&d, &SaveOptions { version, ..SaveOptions::default() }).unwrap();
|
||||
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(v["document"]["version"], 1, "file version {version}");
|
||||
assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}");
|
||||
let (document, saved) = if version < 4 { (1, r#""angle":-30.0"#) } else { (now, r#""angle":30.0"#) };
|
||||
assert_eq!(v["document"]["version"], document, "file version {version}");
|
||||
assert!(String::from_utf8_lossy(&bytes).contains(saved), "file version {version}");
|
||||
let back = load(&bytes).unwrap();
|
||||
assert_eq!((back.version, angle(&back)), (now, Some(30.0)), "file version {version}");
|
||||
}
|
||||
// A version 4 file from 0.21.0 or later turned its version 1 document's angles already.
|
||||
let mut v4: serde_json::Value = serde_json::from_slice(¤t).unwrap();
|
||||
(v4["version"], v4["document"]["version"], v4["generator"]) = (4.into(), 1.into(), "VectorCraft 0.25.2".into());
|
||||
assert_eq!(angle(&load(&serde_json::to_vec(&v4).unwrap()).unwrap()), Some(30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user