mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Merge main into fix/windows-font-registry-watch
This commit is contained in:
commit
8e5bdee59e
73 files changed
+5895
-495
No files matched your search
@@ -82,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,11 +16,35 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
# A main run is the analysis a nightly waits for; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
nightly-commit:
|
||||
name: Nightly commit is main's head
|
||||
# A workflow_run checks out and analyzes main's head, so main must not have moved since the
|
||||
# nightly started.
|
||||
if: github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Require main's head to be the nightly's commit
|
||||
env:
|
||||
NIGHTLY_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
RUN_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
if [ "$NIGHTLY_SHA" != "$RUN_SHA" ]; then
|
||||
echo "::error::main moved from $NIGHTLY_SHA to $RUN_SHA after the nightly started; this run would not analyze the nightly's commit"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sonarcloud:
|
||||
needs: nightly-commit
|
||||
if: ${{ !cancelled() && contains(fromJSON('["success","skipped"]'), needs.nightly-commit.result) }}
|
||||
# Tracked at @main so org-wide CI improvements propagate without PR churn.
|
||||
# The reusable workflow defaults build-jobs to 2 so a cold instrumented
|
||||
# archive stays within hosted-runner memory (craft-common-actions#333).
|
||||
|
||||
Generated
+94
-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=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1298,7 +1298,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1319,7 +1319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1331,7 +1331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1339,7 +1339,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1364,7 +1364,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1383,7 +1383,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1401,7 +1401,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1410,7 +1410,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1418,7 +1418,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1427,12 +1427,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1452,7 +1452,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
@@ -1468,7 +1468,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
@@ -1478,7 +1478,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1486,7 +1486,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1512,7 +1512,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
@@ -1528,7 +1528,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1536,7 +1536,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1555,7 +1555,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dwg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"acadrust",
|
||||
"craft-dxf",
|
||||
@@ -1565,7 +1565,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1577,7 +1577,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1587,12 +1587,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
@@ -1602,7 +1602,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1617,7 +1617,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1636,7 +1636,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1645,7 +1645,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1668,12 +1668,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1681,7 +1681,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1689,7 +1689,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1702,7 +1702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"brotli 9.1.3",
|
||||
"brotli-decompressor 6.3.2",
|
||||
@@ -1732,7 +1732,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1759,7 +1759,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1777,7 +1777,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1785,7 +1785,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1796,7 +1796,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1811,7 +1811,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1825,7 +1825,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1843,7 +1843,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1855,7 +1855,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1866,7 +1866,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1876,7 +1876,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
@@ -1885,7 +1885,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1901,7 +1901,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pbr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-texture",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1910,7 +1910,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1921,7 +1921,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1933,7 +1933,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1966,7 +1966,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1975,7 +1975,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1999,7 +1999,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -2010,7 +2010,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -2024,7 +2024,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -2035,7 +2035,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -2048,7 +2048,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2057,7 +2057,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -2076,7 +2076,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -2093,7 +2093,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2104,7 +2104,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -2125,7 +2125,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2137,7 +2137,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2162,7 +2162,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-texture"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -2170,7 +2170,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2185,7 +2185,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2200,7 +2200,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2210,7 +2210,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2219,7 +2219,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2234,12 +2234,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2253,7 +2253,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -2270,7 +2270,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2308,7 +2308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2319,7 +2319,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2337,7 +2337,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2358,7 +2358,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2379,7 +2379,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2398,7 +2398,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2430,7 +2430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2441,7 +2441,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2451,7 +2451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2462,7 +2462,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2470,7 +2470,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2502,7 +2502,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2971,7 +2971,6 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"smithay-clipboard",
|
||||
"web-time",
|
||||
"webbrowser",
|
||||
"windows-sys 0.61.2",
|
||||
"winit",
|
||||
]
|
||||
@@ -3862,7 +3861,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"brotli 8.0.4",
|
||||
"hayro-postscript",
|
||||
@@ -3871,7 +3870,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3889,7 +3888,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3907,12 +3906,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4895,7 +4894,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -5052,7 +5051,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -7618,7 +7617,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=37d0532f42eb3421769c8a454e3e25a20fbcff97#37d0532f42eb3421769c8a454e3e25a20fbcff97"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f9e5cecc9cf1b701b22f6f24a88719b14456323e#f9e5cecc9cf1b701b22f6f24a88719b14456323e"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
@@ -8673,6 +8672,7 @@ dependencies = [
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"webbrowser",
|
||||
"windows",
|
||||
"winit",
|
||||
"winreg",
|
||||
@@ -9292,6 +9292,7 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"toml",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
|
||||
+42
-43
@@ -10,60 +10,60 @@ license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# The DWG reader and writer craft-dwg uses, at the rev craft-libs pins (its Cargo.toml). Tests only: it writes the
|
||||
# R12, R13 and R14 DWG files that craft-dwg's writer, 2000 and later, does not.
|
||||
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# Nightly profile isolation, launch protocol, and security fence.
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -203,16 +203,15 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
|
||||
# It stays at this rev until craft-libs#5222 merges.
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
|
||||
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
|
||||
|
||||
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "f9e5cecc9cf1b701b22f6f24a88719b14456323e", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -108,6 +108,50 @@ fn reveal_command(path: &str) -> std::process::Command {
|
||||
c
|
||||
}
|
||||
|
||||
/// Opens the `file:` URL of a file the app wrote (View PDF after Saving, Show in Browser) in the
|
||||
/// default web browser.
|
||||
fn open_file_url(url: &str) -> Result<(), String> {
|
||||
webbrowser::open(url).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
|
||||
/// Opens a link with the system's handler, without waiting for it:
|
||||
/// `craft::platform::open::open_external` on macOS and Windows, xdg-open elsewhere ([`link_command`]).
|
||||
pub(crate) fn open_link(url: &str) -> Result<(), String> {
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
let mut c = link_command(url)?;
|
||||
c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {url}: {e}"))
|
||||
}
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
{
|
||||
craft::platform::open::open_external(url)
|
||||
}
|
||||
}
|
||||
|
||||
/// xdg-open with `url` as its only argument. xdg-open stops with "unexpected option" at any
|
||||
/// argument that starts with `-`, `--` included, which `craft::platform::open::open_external` puts
|
||||
/// before the URL, so a URL that starts with `-` is refused here instead. Remove this once
|
||||
/// craft-libs' `open_external` runs xdg-open without `--`.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
fn link_command(url: &str) -> Result<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 +227,8 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
// View PDF after Saving and Show in Browser open the file they wrote.
|
||||
open_file_url: Some(Box::new(open_file_url)),
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))),
|
||||
|
||||
@@ -439,6 +439,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,8 +896,7 @@ 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())
|
||||
let spec = main_window_spec(shell_info, Arc::new(SystemWindows), host_services::open_link)
|
||||
.placement(Arc::new(Mutex::new(placement)))
|
||||
.frame(decision);
|
||||
let spec = match start_pen(&winit_window) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -130,14 +130,15 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
}
|
||||
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// reports: the pressure it reports, 0 included, which a pen in contact can report as its tip touches
|
||||
/// down and lifts (#10231), 0 while it hovers, and a full press for a pen in contact that reports
|
||||
/// none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
|
||||
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
|
||||
/// within 0..1 and none when it is not a number.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<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,
|
||||
};
|
||||
@@ -318,13 +319,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
fn a_pen_that_reports_pressure_keeps_zero_at_the_ends_of_a_stroke() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(
|
||||
pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure,
|
||||
0.0,
|
||||
"a tip that touches down or lifts with no pressure does not press fully"
|
||||
);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_ERASER, true, UPRIGHT, None), eraser_sample(0.0), "the eraser end too");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -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`]
|
||||
|
||||
+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).
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
|
||||
+30
-8
@@ -249,7 +249,7 @@ impl StrokeLayer {
|
||||
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
|
||||
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
|
||||
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
|
||||
/// reach of the arrowheads round their end points.
|
||||
/// outlines of the arrowheads.
|
||||
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
|
||||
let els = bp.elements();
|
||||
let subs = subpaths(bp);
|
||||
@@ -316,16 +316,17 @@ impl StrokeLayer {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (at, _, end) in head_ends(self, bp) {
|
||||
let r = self.head_reach(end);
|
||||
out = out.union(Rect::from_center_size(at, (2.0 * r, 2.0 * r)));
|
||||
for head in crate::arrow::stroke_pieces(bp, self).heads {
|
||||
if !head.outline.elements().is_empty() {
|
||||
out = out.union(head.outline.bounding_box());
|
||||
}
|
||||
}
|
||||
even.map_or(out, |e| out.union(e.inflate(side_max, side_max)))
|
||||
}
|
||||
|
||||
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
|
||||
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
|
||||
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
|
||||
/// projecting caps and the outlines of the arrowheads. An open subpath
|
||||
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
|
||||
/// ([`Self::body_along`]).
|
||||
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
|
||||
@@ -681,13 +682,34 @@ mod tests {
|
||||
})
|
||||
};
|
||||
let (small, big) = (at(100.0).bounds_on(&l, b), at(300.0).bounds_on(&l, b));
|
||||
assert!(big.x1 > small.x1 + 15.0 && big.y1 > small.y1 + 7.0, "{small:?} → {big:?}");
|
||||
// A 300% head on a 2 pt stroke is 24 pt long and wide: its tip, past the end, is inside.
|
||||
assert!(big.x1 >= 100.0 + 24.0 && big.y1 >= 12.0 && big.x0 == 0.0, "{big:?}");
|
||||
// The triangle straddles its path end in Extend mode and ends exactly on it in Tip mode.
|
||||
assert_eq!(small, Rect::new(0.0, -4.0, 104.0, 4.0));
|
||||
assert_eq!(big, Rect::new(0.0, -12.0, 112.0, 12.0));
|
||||
let mut tip = at(300.0);
|
||||
tip.arrow_align = ArrowAlign::Tip;
|
||||
assert_eq!(tip.bounds_on(&l, b), Rect::new(0.0, -12.0, 100.0, 12.0));
|
||||
// The start has no head.
|
||||
assert_eq!(at(300.0).head_reach(false), 0.0);
|
||||
}
|
||||
|
||||
/// An open arrow at the start of a line, its tip on the start point: the box ends where the
|
||||
/// head's barbs end, with no room left in front of the tip (#10225).
|
||||
#[test]
|
||||
fn an_open_tip_aligned_arrowhead_adds_no_room_in_front_of_its_tip() {
|
||||
let l = line();
|
||||
let b = l.bounding_box();
|
||||
let st = stroke(1.0, |s| {
|
||||
s.start_arrow = Some(Arrowhead::ArrowOpen);
|
||||
s.arrow_align = ArrowAlign::Tip;
|
||||
s.arrow_scale = (300.0, 100.0);
|
||||
});
|
||||
let bounds = st.bounds_on(&l, b);
|
||||
// The barbs reach back along the line from the tip, and at most the line's weight past it.
|
||||
assert!(bounds.x0 <= 0.0 && bounds.x0 >= -st.width, "{bounds:?}");
|
||||
assert!(bounds.y0 < -st.width && bounds.y1 > st.width, "the barbs spread wider than the line: {bounds:?}");
|
||||
assert_eq!(bounds.x1, b.x1, "the end has no head and a butt cap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangles_keep_exact_bounds_and_sharp_corners_spike_up_to_the_limit() {
|
||||
let sq = square();
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 is not placed, so it takes nothing past the object itself.
|
||||
cd::Object::Image(_) => {}
|
||||
cd::Object::Clip { container, objects } => {
|
||||
// A container whose outline is behind its fill is built twice, as that outline
|
||||
// and as the clipping path, inside a group of their own.
|
||||
|
||||
@@ -74,6 +74,8 @@ impl Builder {
|
||||
self.learn_spot(c);
|
||||
}
|
||||
}
|
||||
// Bitmaps are not placed, so their colors add no swatch.
|
||||
cd::Object::Image(_) => {}
|
||||
cd::Object::Group { objects: kids, .. } => stack.extend(kids),
|
||||
cd::Object::Clip { container, objects } => {
|
||||
for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) {
|
||||
@@ -123,6 +125,8 @@ impl Builder {
|
||||
for o in objects.iter().rev() {
|
||||
match o {
|
||||
cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))),
|
||||
// Bitmaps are left out, and the warnings name them with the other objects not read.
|
||||
cd::Object::Image(_) => self.note(Warning::UnsupportedObjects),
|
||||
cd::Object::Group { objects: kids, flags } => {
|
||||
let children = self.objects_at(kids, to_doc, depth + 1);
|
||||
if !children.is_empty() {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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![],
|
||||
|
||||
@@ -522,6 +522,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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -87,6 +87,9 @@ craft = { workspace = true, features = ["dialogs", "update", "automation-agents"
|
||||
# The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in
|
||||
# Cargo.lock with the time-zone crates `clock` uses.
|
||||
chrono = { workspace = true, features = ["clock"] }
|
||||
# The digest of each open document's file, which Save compares with the file before asking whether to replace it
|
||||
# (`src/io/saved_contents.rs`). Already in Cargo.lock (the engine's and the plug-ins' digests).
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# The status bar's Date and Time readout reads the page's clock with this crate in the web build. It
|
||||
|
||||
@@ -5,12 +5,13 @@ use craft::platform::clipboard::{Clipboard, ClipboardProbe, EventClipboard};
|
||||
use craft::platform::clock::monotonic_ms;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::{ActiveLook, PushButtonLook};
|
||||
use craft::ui::choice::ChoiceLook;
|
||||
use craft::ui::choice::{ChoiceLook, SwatchCorners};
|
||||
use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, MoveBandCursor, QuietHeader, SectionRhythm};
|
||||
use craft::ui::docking::IconGroupSeparator;
|
||||
use craft::ui::docking::{FloatingGroupLook, IconGroupSeparator};
|
||||
use craft::ui::list::{CommandHighlight, ThumbRows};
|
||||
use craft::ui::menu::{MenuTitleLook, MenuTitlePad};
|
||||
use craft::ui::patterns::form_dialogs::PresetCardLook;
|
||||
use craft::ui::primitives::DrawingCursorLook;
|
||||
use craft::ui::runtime::drag::{self, OsFiles};
|
||||
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
@@ -671,6 +672,7 @@ impl VectorcraftApp {
|
||||
if !self.background.jobs.is_empty()
|
||||
|| !self.opening.pending.is_empty()
|
||||
|| !self.opening.converting.is_empty()
|
||||
|| io::save::checks_pending(self)
|
||||
|| plugin_runs::any_pending(self)
|
||||
|| !self.placing.pending.is_empty()
|
||||
|| !self.trace_runs.running.is_empty()
|
||||
@@ -712,7 +714,7 @@ impl VectorcraftApp {
|
||||
if ctx.current_pass_index() == 0
|
||||
&& let Some(u) = self.pending_url.take()
|
||||
{
|
||||
ctx.open_url(egui::OpenUrl::new_tab(u));
|
||||
self.open_pending_url(ctx, u);
|
||||
}
|
||||
self.flush_clipboard_out();
|
||||
self.drain_inbox();
|
||||
@@ -792,6 +794,7 @@ impl VectorcraftApp {
|
||||
self.handle_input(&ctx);
|
||||
self.ui_frame(ui);
|
||||
self.window_keys(&ctx);
|
||||
io::save::after_ui(self, &ctx);
|
||||
// What the canvas, a panel, a dialog or a window key changed in this pass reaches
|
||||
// the plug-ins that react to it now, since an idle app draws no further frame; a
|
||||
// line a handler wrote shows in the next one. The handlers' time counts toward the
|
||||
@@ -939,6 +942,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips);
|
||||
// Painted tool cursors grow with UI Scaling only when Scale Cursor Proportional to UI is on.
|
||||
root = root.cursor_follows_zoom(prefs.scale_cursor_with_ui);
|
||||
// The Selection, Direct Selection and Hand pointers, the drawing crosshairs and the tool cursors draw in black and
|
||||
// white over the artwork in either interface theme.
|
||||
root.values.set(DrawingCursorLook::Monochrome);
|
||||
root.sizes = theme::app_sizes();
|
||||
root.values.set(view::zoom_scheme(print, native_ppp));
|
||||
root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off });
|
||||
@@ -967,6 +973,10 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
// Check boxes, radio buttons and switches that are on take the strong accent with a white mark, sliders fill their
|
||||
// track to the value in the accent, and a dialog's Cancel is a filled button beside its accent answer.
|
||||
root.values.set(ChoiceLook::Strong);
|
||||
// Color swatches and the Fill and Stroke wells keep square corners, so a small sample shows its whole color.
|
||||
root.values.set(SwatchCorners::Square);
|
||||
// Floating panel groups and tool palettes are square palettes with a small shadow.
|
||||
root.values.set(FloatingGroupLook::Palette);
|
||||
root.values.set(TrackFill::Accent);
|
||||
root.values.set(DialogButtonLook::Filled);
|
||||
// Sections stand apart with production's room around their dividers.
|
||||
|
||||
@@ -15,6 +15,20 @@ impl VectorcraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the URL [`Self::open_url`] asked for: a `file:` URL with the host's
|
||||
/// [`Services::open_file_url`](crate::Services::open_file_url) when it has one, any other URL
|
||||
/// (and a `file:` URL without that service) as egui's `OpenUrl` in a new tab.
|
||||
pub(crate) fn open_pending_url(&mut self, ctx: &egui::Context, url: String) {
|
||||
let file = url.split_once(':').is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("file"));
|
||||
if file && let Some(open) = self.services.open_file_url.as_mut() {
|
||||
if let Err(error) = open(&url) {
|
||||
log::warn!("could not open {url:?}: {error}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
ctx.open_url(egui::OpenUrl::new_tab(url));
|
||||
}
|
||||
|
||||
/// Open `url`, which came from a document (an object's URL attribute), in the browser:
|
||||
/// [`browsable_url`]s only.
|
||||
pub(crate) fn open_document_url(&mut self, url: &str) -> Result<(), String> {
|
||||
@@ -122,3 +136,65 @@ impl VectorcraftApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::VectorcraftApp;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// An app whose host opens `file:` URLs by recording them in the returned list.
|
||||
fn app_opening_files() -> (VectorcraftApp, Rc<RefCell<Vec<String>>>) {
|
||||
let opened = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = Rc::clone(&opened);
|
||||
let services = crate::Services {
|
||||
open_file_url: Some(Box::new(move |url: &str| {
|
||||
seen.borrow_mut().push(url.to_owned());
|
||||
Ok(())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
(VectorcraftApp::new(vectorcraft_engine::Session::new(), services), opened)
|
||||
}
|
||||
|
||||
/// The URLs the next frame of `app` asked egui to open.
|
||||
fn opened_in_frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<String> {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out.platform_output
|
||||
.commands
|
||||
.into_iter()
|
||||
.filter_map(|c| match c {
|
||||
egui::OutputCommand::OpenUrl(open) => Some(open.url),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A file the app wrote opens through the host once, outside egui's links, which the UI
|
||||
/// runtime's link opener would drop; a web link still goes to egui.
|
||||
#[test]
|
||||
fn a_written_file_opens_through_the_host_and_a_web_link_through_egui() {
|
||||
let (mut app, files) = app_opening_files();
|
||||
let ctx = crate::testing::ui_context();
|
||||
|
||||
app.open_url("FILE:///tmp/out.pdf");
|
||||
assert!(opened_in_frame(&mut app, &ctx).is_empty(), "the file URL is not handed to egui");
|
||||
assert_eq!(*files.borrow(), ["FILE:///tmp/out.pdf"], "the host opens the file URL");
|
||||
assert!(opened_in_frame(&mut app, &ctx).is_empty());
|
||||
assert_eq!(files.borrow().len(), 1, "a frame without a request opens nothing again");
|
||||
|
||||
app.open_link("help.discord");
|
||||
assert_eq!(opened_in_frame(&mut app, &ctx), ["https://discord.gg/artcraft"]);
|
||||
assert_eq!(files.borrow().len(), 1, "a web link does not reach the file opener");
|
||||
}
|
||||
|
||||
/// Without the host's file opener (the web build), a `file:` URL goes to egui as before.
|
||||
#[test]
|
||||
fn without_a_file_opener_a_file_url_goes_to_egui() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.open_url("file:///tmp/out.svg");
|
||||
assert_eq!(opened_in_frame(&mut app, &ctx), ["file:///tmp/out.svg"]);
|
||||
}
|
||||
}
|
||||
@@ -78,3 +78,39 @@ fn the_close_caption_asks_about_unsaved_documents() {
|
||||
assert_eq!(close_frame(&mut app, &ctx), Some(CloseDecision::Close));
|
||||
assert!(!asks_about_unsaved(&app), "nothing unsaved, nothing asked");
|
||||
}
|
||||
|
||||
/// A color swatch fills its well to the corners: every opaque rectangle the well paints has square corners, so a
|
||||
/// small sample shows its whole color.
|
||||
#[test]
|
||||
fn a_color_swatch_paints_a_square_well() {
|
||||
use craft::theme::Srgba;
|
||||
use craft::ui::choice::Swatch;
|
||||
use craft::ui::contract::Show as _;
|
||||
let mut well = egui::Rect::NOTHING;
|
||||
let mut out = crate::testing::ui_context().run_ui(Default::default(), |ui| {
|
||||
well = Swatch::new("Color", Srgba::rgb(0.2, 0.6, 0.4)).show(ui).response.rect;
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let fills: Vec<(egui::Rect, egui::CornerRadius)> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Rect(rect) if rect.fill.a() == 255 && well.expand(1.0).contains_rect(rect.rect) => Some((rect.rect, rect.corner_radius)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!fills.is_empty(), "the well paints its color in {well:?}");
|
||||
let rounded: Vec<_> = fills.iter().filter(|(_, corners)| *corners != egui::CornerRadius::ZERO).collect();
|
||||
assert!(rounded.is_empty(), "the well's corners are square: {rounded:?}");
|
||||
}
|
||||
|
||||
/// Floating panel groups and tool palettes take the palette frame, square with a small shadow, not the rounded frame
|
||||
/// of a floating window.
|
||||
#[test]
|
||||
fn floating_groups_take_the_palette_frame() {
|
||||
use craft::ui::docking::FloatingGroupLook;
|
||||
use craft::ui::runtime::env::Env;
|
||||
let mut look = None;
|
||||
crate::testing::ui_context().run_ui(Default::default(), |ui| look = Some(Env::of(ui).get::<FloatingGroupLook>())).textures_delta.clear();
|
||||
assert_eq!(look, Some(FloatingGroupLook::Palette));
|
||||
}
|
||||
@@ -625,9 +625,8 @@ impl Component for ArtMarks<'_> {
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let style = &cx.style;
|
||||
let draw = ui.draw();
|
||||
for quad in self.fade {
|
||||
draw.data_fill(&PaintShape::Polygon(quad.to_vec()), FADE_OUTSIDE);
|
||||
}
|
||||
let pieces: Vec<_> = self.fade.iter().map(|quad| quad.to_vec()).collect();
|
||||
draw.data_fill_tiled(&pieces, FADE_OUTSIDE);
|
||||
let bleed = self.bleed.iter().map(|path| (path, style.bleed));
|
||||
for (path, color) in bleed.chain(self.artboard_marks.iter().map(|path| (path, style.marks))) {
|
||||
for (points, closed) in path_runs(&self.view, path) {
|
||||
|
||||
@@ -688,6 +688,89 @@ struct MeshKey {
|
||||
pub(crate) struct KeptMesh {
|
||||
key: MeshKey,
|
||||
mesh: Arc<egui::Mesh>,
|
||||
/// How far the marks moved on screen since they were tessellated, in physical pixels, unrounded
|
||||
/// ([`KeptMesh::translate`]). The mesh moved by this distance rounded.
|
||||
moved: [f64; 2],
|
||||
}
|
||||
|
||||
/// How far from a whole number of physical pixels the marks' move since they were tessellated may be on screen, and
|
||||
/// still count as whole: rounding noise of the screen position, well under what the tessellator's `f32` positions hold.
|
||||
const PIXEL_SLACK: f64 = 1e-6;
|
||||
|
||||
impl KeptMesh {
|
||||
/// Moves the mesh by `by` in the document when tessellating the moved marks would give the same mesh moved, and
|
||||
/// returns whether it did. `points` are the marks' anchors and direction handles before the move ([`knot_points`]),
|
||||
/// and `options` the Path Options they are drawn with. The mesh moves when the marks' whole move since they were
|
||||
/// tessellated is a whole number of physical pixels on screen, and when every point's `f32` screen position moves
|
||||
/// by this move's whole pixels too. Every square [`mark_shapes`] could draw at a point, at the anchor side and at
|
||||
/// the handle side, must keep its `f32` size and have each edge round to pixels as the tessellator rounds it, moved
|
||||
/// by the same whole pixels; a square thin enough for the tessellator to draw as a line is tessellated again. It
|
||||
/// also needs every point inside the canvas before and after the move, so the marks are drawn near and inside the
|
||||
/// clip on both sides and no anchor, handle or outline is left out or culled.
|
||||
fn translate(&mut self, by: Vec2, points: impl IntoIterator<Item = Point>, options: &PathOptionsSettings) -> bool {
|
||||
let key = &self.key;
|
||||
let ppp = f64::from(key.pixels_per_point);
|
||||
let view = key.view.affine();
|
||||
let shift = (view * (Point::ZERO + by)) - (view * Point::ZERO);
|
||||
let moved = [self.moved[0] + shift.x * ppp, self.moved[1] + shift.y * ppp];
|
||||
if moved.iter().any(|p| !p.is_finite() || (p - p.round()).abs() > PIXEL_SLACK) {
|
||||
return false;
|
||||
}
|
||||
// This move in whole physical pixels.
|
||||
let pixels = [moved[0].round() - self.moved[0].round(), moved[1].round() - self.moved[1].round()];
|
||||
let area = key.rect.expand(key.look.reach).intersect(key.clip);
|
||||
// `CanvasView::to_screen` with the affine computed once.
|
||||
let screen = |p: Point| {
|
||||
let s = view * p;
|
||||
egui::pos2(s.x as f32, s.y as f32)
|
||||
};
|
||||
let whole = |from: f32, to: f32, px: f64| ((f64::from(to) - f64::from(from)) * ppp - px).abs() <= PIXEL_SLACK;
|
||||
// The tessellator's `f32` rounding of an edge to pixels (`GuiRounding::round_to_pixels`), in whole pixels.
|
||||
let ppp_f32 = key.pixels_per_point;
|
||||
let snapped = |edge: f32| f64::from((edge * ppp_f32).round());
|
||||
let lands = |from: f32, to: f32, px: f64| snapped(to) - snapped(from) == px;
|
||||
let sides = mark_sides(options, &key.look);
|
||||
// Below this side the tessellator draws a filled square as a line, which it rounds other ways.
|
||||
let feathering = if key.options.feathering { key.options.feathering_size_in_pixels / ppp_f32 } else { 0.0 };
|
||||
if sides.iter().any(|side| *side <= 2.0 * feathering) {
|
||||
return false;
|
||||
}
|
||||
for p in points {
|
||||
let (from, to) = (screen(p), screen(p + by));
|
||||
if !(area.contains(from) && area.contains(to) && whole(from.x, to.x, pixels[0]) && whole(from.y, to.y, pixels[1])) {
|
||||
return false;
|
||||
}
|
||||
for side in sides {
|
||||
let (a, b) = (Rect::from_center_size(from, egui::Vec2::splat(side)), Rect::from_center_size(to, egui::Vec2::splat(side)));
|
||||
// The tessellator tests the built square's `f32` width and height, which can come out below `side`.
|
||||
if a.size() != b.size()
|
||||
|| [a, b].iter().any(|r| r.width() <= 2.0 * feathering || r.height() <= 2.0 * feathering)
|
||||
|| !(lands(a.min.x, b.min.x, pixels[0])
|
||||
&& lands(a.max.x, b.max.x, pixels[0])
|
||||
&& lands(a.min.y, b.min.y, pixels[1])
|
||||
&& lands(a.max.y, b.max.y, pixels[1]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let offset = vec2((pixels[0] / ppp) as f32, (pixels[1] / ppp) as f32);
|
||||
self.moved = moved;
|
||||
Arc::make_mut(&mut self.mesh).translate(offset);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Every anchor and direction handle of `anchors`, in document units. The outlines lie inside the hull of these
|
||||
/// points, as a curve lies inside the hull of its points.
|
||||
fn knot_points(anchors: &Anchors) -> impl Iterator<Item = Point> + '_ {
|
||||
anchors
|
||||
.paths
|
||||
.iter()
|
||||
.chain(&anchors.plain)
|
||||
.flat_map(|p| &p.subpaths)
|
||||
.flat_map(|sp| &sp.knots)
|
||||
.flat_map(|knot| [knot.anchor, knot.in_ctrl, knot.out_ctrl])
|
||||
}
|
||||
|
||||
/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show.
|
||||
@@ -809,7 +892,7 @@ impl Component for AnchorMarks<'_> {
|
||||
None => {
|
||||
let shapes = shapes();
|
||||
let mesh = Arc::new(tessellate(shapes, &key));
|
||||
*kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) });
|
||||
*kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh), moved: [0.0; 2] });
|
||||
mesh
|
||||
}
|
||||
};
|
||||
@@ -864,14 +947,20 @@ enum MarkFill {
|
||||
Path,
|
||||
}
|
||||
|
||||
/// The side of an anchor's mark, then of a direction handle's end, under `options`.
|
||||
fn mark_sides(options: &PathOptionsSettings, look: &MarkLook) -> [f32; 2] {
|
||||
let anchor = options.anchor_size.unwrap_or(look.anchor);
|
||||
let handle = if options.handles == HandleStyle::Large { look.large } else { look.anchor };
|
||||
[anchor, handle]
|
||||
}
|
||||
|
||||
/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the
|
||||
/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors.
|
||||
fn mark_shapes(out: &mut Vec<Shape>, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) {
|
||||
let options = set.options;
|
||||
let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0)));
|
||||
let path_color = |path: &EditPath| path.color.map(Color32::from);
|
||||
let anchor_side = options.anchor_size.unwrap_or(look.anchor);
|
||||
let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor };
|
||||
let [anchor_side, handle_side] = mark_sides(options, look);
|
||||
let circles = set.shown == AnchorsShown::Curvature;
|
||||
let line = |out: &mut Vec<Shape>, points: Vec<egui::Pos2>, closed: bool, segment: bool, color: Option<Color32>| {
|
||||
let named = if segment { look.thick } else { look.medium };
|
||||
@@ -1198,12 +1287,22 @@ impl SelectionMarks {
|
||||
self.from = (moved.from.clone(), moved.by);
|
||||
self.doc = moved.to.clone();
|
||||
}
|
||||
// The kept mesh shows these marks, so it stays theirs under the new key.
|
||||
let was = self.key;
|
||||
if let Some(kept) = self.mesh.get_mut().as_mut().filter(|kept| kept.key.marks == was) {
|
||||
kept.key.marks = key;
|
||||
}
|
||||
self.key = key;
|
||||
Some(self)
|
||||
}
|
||||
|
||||
/// Moves every mark by `by`.
|
||||
/// Moves every mark by `by`, and the kept mesh of the anchor marks with them when it can move as it is
|
||||
/// ([`KeptMesh::translate`]); otherwise the next paint tessellates the marks again.
|
||||
fn translate(&mut self, by: Vec2) {
|
||||
let mesh = self.mesh.get_mut();
|
||||
if mesh.as_mut().is_some_and(|kept| !kept.translate(by, knot_points(&self.anchors), &self.anchors.options)) {
|
||||
*mesh = None;
|
||||
}
|
||||
let shift = vectorcraft_geom::Affine::translate(by);
|
||||
for o in &mut self.outlines {
|
||||
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
|
||||
|
||||
@@ -1014,7 +1014,48 @@ fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) -
|
||||
let out = canvas_frame(app, ctx, vec![]);
|
||||
OVERLAY_MARKS.with(|on| on.set(false));
|
||||
RAW_MARKS.with(|on| on.set(false));
|
||||
crate::tests::labels::flat_painted_shapes(&out.shapes)
|
||||
// A placeholder that was never filled paints nothing.
|
||||
crate::tests::labels::flat_painted_shapes(&out.shapes).into_iter().filter(|shape| !matches!(shape, egui::Shape::Noop)).collect()
|
||||
}
|
||||
|
||||
/// `marks` with each run of shapes that `overlay` paints as one kept mesh replaced by that run tessellated into one
|
||||
/// mesh, as `Draw::kept_mesh` tessellates it: the context's options, no font atlas discs and no clip. A run ends where
|
||||
/// its mesh reaches the vertex count of the overlay's mesh at the same place; anything else is left as it was. Also
|
||||
/// returns how many runs of more than one shape became a mesh.
|
||||
fn kept_like(overlay: &[egui::Shape], marks: Vec<egui::Shape>, ctx: &egui::Context) -> (Vec<egui::Shape>, usize) {
|
||||
let options = ctx.tessellation_options(|options| *options);
|
||||
let mut marks = marks.into_iter().peekable();
|
||||
let mut out = Vec::new();
|
||||
let mut runs = 0;
|
||||
for shape in overlay {
|
||||
// A mesh both frames paint is compared as it is.
|
||||
let both = matches!(marks.peek(), Some(egui::Shape::Mesh(_)));
|
||||
let egui::Shape::Mesh(kept) = shape else {
|
||||
out.extend(marks.next());
|
||||
continue;
|
||||
};
|
||||
if both {
|
||||
out.extend(marks.next());
|
||||
continue;
|
||||
}
|
||||
let mut tessellator = egui::epaint::Tessellator::new(ctx.pixels_per_point(), options, [1, 1], Vec::new());
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let mut run = Vec::new();
|
||||
while mesh.vertices.len() < kept.vertices.len()
|
||||
&& let Some(next) = marks.next()
|
||||
{
|
||||
run.push(next.clone());
|
||||
tessellator.tessellate_shape(next, &mut mesh);
|
||||
}
|
||||
if mesh.vertices.len() == kept.vertices.len() {
|
||||
runs += usize::from(run.len() > 1);
|
||||
out.push(egui::Shape::Mesh(std::sync::Arc::new(mesh)));
|
||||
} else {
|
||||
out.extend(run);
|
||||
}
|
||||
}
|
||||
out.extend(marks);
|
||||
(out, runs)
|
||||
}
|
||||
|
||||
/// A canvas app with one curve, the task bar off and every frame drawn on this thread.
|
||||
@@ -1039,8 +1080,9 @@ fn the_anchor_marks_paint_what_the_bezier_overlay_paints() {
|
||||
change(&mut marks.anchors);
|
||||
}
|
||||
let overlay = canvas_shapes(app, &ctx, true);
|
||||
let marks = canvas_shapes(app, &ctx, false);
|
||||
assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len());
|
||||
// The overlay paints its anchors and handles as one kept mesh, the marks paint them one shape at a time.
|
||||
let (marks, runs) = kept_like(&overlay, canvas_shapes(app, &ctx, false), &ctx);
|
||||
assert!(runs > 0, "{case}: the overlay painted the marks as a kept mesh ({} shapes)", overlay.len());
|
||||
let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b);
|
||||
assert!(
|
||||
overlay == marks,
|
||||
@@ -1283,3 +1325,165 @@ fn a_move_of_the_selection_moves_its_marks_without_building_them() {
|
||||
assert_eq!(frames(&mut app, 3), 1, "an undo");
|
||||
assert!(kept_marks_are_current(&app), "after an undo");
|
||||
}
|
||||
|
||||
/// The mesh of the anchor marks the canvas keeps.
|
||||
fn kept_mesh(app: &VectorcraftApp) -> Arc<egui::Mesh> {
|
||||
let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
|
||||
let kept = marks.mesh.borrow();
|
||||
Arc::clone(&kept.as_ref().expect("the canvas kept the anchor marks' mesh").mesh)
|
||||
}
|
||||
|
||||
// A drag of the selection moves the kept mesh of its anchor marks instead of tessellating them again: steps of whole
|
||||
// pixels tessellate nothing and leave the mesh a new tessellation gives, a new revision of the same marks keeps it, and
|
||||
// a step of part of a pixel or one that takes the marks past the canvas's edge tessellates them once.
|
||||
#[test]
|
||||
fn a_drag_of_the_selection_moves_the_anchor_marks_mesh_without_tessellating_it() {
|
||||
let (mut app, curve) = canvas_app();
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
let frames = |app: &mut VectorcraftApp, n: usize| {
|
||||
let before = MESHES_BUILT.with(std::cell::Cell::get);
|
||||
for _ in 0..n {
|
||||
canvas_frame(app, &ctx, vec![]);
|
||||
}
|
||||
MESHES_BUILT.with(std::cell::Cell::get) - before
|
||||
};
|
||||
assert_eq!(frames(&mut app, 2), 1, "the first frame tessellates the marks");
|
||||
// A document distance that is `px` physical pixels across on screen.
|
||||
let pixels = |app: &VectorcraftApp, px: f64| px / (app.canvas_view().unwrap().zoom * f64::from(ctx.pixels_per_point()));
|
||||
let step = |app: &mut VectorcraftApp, dx: f64| {
|
||||
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 0], "copy": false})).unwrap();
|
||||
};
|
||||
|
||||
let layer = app.session.active().unwrap().doc.layers[0].id;
|
||||
app.run("layer.setCurrent", json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(frames(&mut app, 2), 0, "a new revision of the same document and selection");
|
||||
|
||||
// The kept mesh matches the one marks built now tessellate; the kept marks go back afterwards, so the drag
|
||||
// goes on moving them.
|
||||
let matches_new = |app: &mut VectorcraftApp, case: &str| {
|
||||
let moved = kept_mesh(app);
|
||||
let kept = app.canvas.selection_marks.take();
|
||||
canvas_frame(app, &ctx, vec![]);
|
||||
let fresh = kept_mesh(app);
|
||||
app.canvas.selection_marks = kept;
|
||||
assert!(!fresh.vertices.is_empty(), "{case}: the marks drew something");
|
||||
assert_eq!(moved.indices, fresh.indices, "{case}: the moved mesh has the triangles of a new one");
|
||||
assert_eq!(moved.vertices.len(), fresh.vertices.len(), "{case}");
|
||||
for (a, b) in moved.vertices.iter().zip(&fresh.vertices) {
|
||||
assert_eq!(a.color, b.color, "{case}");
|
||||
assert!((a.pos - b.pos).length() < 1e-3, "{case}: a moved vertex at {:?}, a new one at {:?}", a.pos, b.pos);
|
||||
}
|
||||
};
|
||||
|
||||
app.session.begin_interaction("Move").unwrap();
|
||||
let built = MARKS_BUILT.with(std::cell::Cell::get);
|
||||
for px in [3.0, 10.0, -4.0] {
|
||||
let dx = pixels(&app, px);
|
||||
step(&mut app, dx);
|
||||
assert_eq!(frames(&mut app, 2), 0, "a drag's step to {px} pixels");
|
||||
}
|
||||
assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks");
|
||||
matches_new(&mut app, "after whole pixels");
|
||||
|
||||
let built = MARKS_BUILT.with(std::cell::Cell::get);
|
||||
let dx = pixels(&app, -4.5);
|
||||
step(&mut app, dx);
|
||||
assert_eq!(frames(&mut app, 2), 1, "a step to part of a pixel");
|
||||
let dx = pixels(&app, -3.5);
|
||||
step(&mut app, dx);
|
||||
assert_eq!(frames(&mut app, 2), 0, "a whole pixel from the marks tessellated at part of one");
|
||||
assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks");
|
||||
matches_new(&mut app, "after part of a pixel and a whole one");
|
||||
// Whole pixels from the last step.
|
||||
let dx = pixels(&app, 1996.5);
|
||||
step(&mut app, dx);
|
||||
assert_eq!(frames(&mut app, 2), 1, "a step past the canvas's edge");
|
||||
app.session.commit_interaction().unwrap();
|
||||
}
|
||||
|
||||
// A move of whole pixels keeps the mesh only when every point's `f32` screen position moves by those whole pixels:
|
||||
// at x = 255.999991 the screen position before a one-pixel move is 255.99998 and after it 257.0, so the marks'
|
||||
// squares would round to other pixels than the moved mesh's.
|
||||
#[test]
|
||||
fn a_whole_pixel_move_keeps_the_mesh_only_when_the_screen_positions_move_by_whole_pixels() {
|
||||
let by = Vec2::new(1.0, 0.0);
|
||||
let options = PathOptionsSettings::default();
|
||||
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(255.5, 10.0)], &options), "a point whose screen position moves one whole pixel");
|
||||
let mut off = kept_at_one_pixel_per_point();
|
||||
assert!(!off.translate(by, [Point::new(255.5, 10.0), Point::new(255.999_991, 10.0)], &options), "a point that moves 1.0000153 pixels");
|
||||
assert_eq!(off.moved, [0.0; 2], "the refused move leaves the mesh where it was");
|
||||
}
|
||||
|
||||
/// A kept mesh of no marks at one physical pixel per point, with the document's coordinates on screen unchanged.
|
||||
fn kept_at_one_pixel_per_point() -> KeptMesh {
|
||||
let screen = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 1000.0));
|
||||
let look = MarkLook {
|
||||
line: Color32::BLACK,
|
||||
fill: Color32::WHITE,
|
||||
edge: Color32::BLACK,
|
||||
anchor: 5.0,
|
||||
large: 7.0,
|
||||
thin: 1.0,
|
||||
medium: 2.0,
|
||||
thick: 3.0,
|
||||
reach: 20.0,
|
||||
};
|
||||
KeptMesh {
|
||||
key: MeshKey {
|
||||
marks: 0,
|
||||
view: CanvasView::new(screen, Point::new(500.0, 500.0), 1.0),
|
||||
rect: screen,
|
||||
clip: screen,
|
||||
pixels_per_point: 1.0,
|
||||
options: egui::epaint::TessellationOptions::default(),
|
||||
look,
|
||||
},
|
||||
mesh: Arc::new(egui::Mesh::default()),
|
||||
moved: [0.0; 2],
|
||||
}
|
||||
}
|
||||
|
||||
// A point whose `f32` screen position moves by exactly one pixel can still put a square's edge on other pixels: an
|
||||
// anchor at x = 252.99998 moves to 253.99998, but its 5 pt square's right edge goes from 255.49998 to 256.5, which
|
||||
// round to 255 and 257, so the moved mesh's edge at 256 is not the one a new tessellation draws. A 6 pt square there
|
||||
// has edges that round one pixel on, but its `f32` width grows from 6 to 6.0000153, and the tessellator compares the
|
||||
// width with its thresholds for drawing a square as a line or a stroke as a fill.
|
||||
#[test]
|
||||
fn a_whole_pixel_move_keeps_the_mesh_only_when_every_square_edge_rounds_by_those_pixels() {
|
||||
let by = Vec2::new(1.0, 0.0);
|
||||
let options = PathOptionsSettings::default();
|
||||
// The `f32` just under 253: 252.99998474121094.
|
||||
let center = f64::from(253.0_f32 - 2.0_f32.powi(-16));
|
||||
let mut kept = kept_at_one_pixel_per_point();
|
||||
assert!(!kept.translate(by, [Point::new(center, 10.0)], &options), "a right edge that rounds two pixels on");
|
||||
assert_eq!(kept.moved, [0.0; 2], "the refused move leaves the mesh where it was");
|
||||
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "edges on whole pixels");
|
||||
// Near the origin a move is whole within the rounding noise: an anchor at x = 2.9999998 (the `f32` just under 3)
|
||||
// moved to 4 keeps its square's width, but the left edge goes from 0.4999998 to 1.5, which round to 0 and 2.
|
||||
let near = f64::from(3.0_f32 - 2.0_f32.powi(-22));
|
||||
let step = Vec2::new(4.0 - near, 0.0);
|
||||
assert!(!kept_at_one_pixel_per_point().translate(step, [Point::new(near, 10.0)], &options), "a left edge that rounds two pixels on");
|
||||
// Anchors and handle ends 6 pt across.
|
||||
let mut six = kept_at_one_pixel_per_point();
|
||||
six.key.look.anchor = 6.0;
|
||||
assert!(!six.translate(by, [Point::new(center, 10.0)], &options), "a square whose width changes");
|
||||
}
|
||||
|
||||
// The tessellator draws a filled square no wider than twice its feathering as a line and rounds it another way, so a
|
||||
// square that small is tessellated again after any move.
|
||||
#[test]
|
||||
#[allow(clippy::field_reassign_with_default)] // `PathOptionsSettings` is non-exhaustive: no struct literal outside its crate
|
||||
fn a_move_tessellates_the_marks_again_when_a_square_is_drawn_as_a_line() {
|
||||
let by = Vec2::new(1.0, 0.0);
|
||||
let mut options = PathOptionsSettings::default();
|
||||
options.anchor_size = Some(2.0);
|
||||
assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 2 pt anchor at 1 pixel per point");
|
||||
// The `f32` just over 2 passes the check on the side, but the square built at x = 252.5 spans 251.5 to 253.5 in
|
||||
// `f32`, 2 pixels wide, so the tessellator draws it as a line.
|
||||
options.anchor_size = Some(f32::from_bits(2.0_f32.to_bits() + 1));
|
||||
assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a square built 2 pixels wide");
|
||||
options.anchor_size = Some(3.0);
|
||||
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 3 pt anchor");
|
||||
}
|
||||
@@ -6023,6 +6023,32 @@ fn the_pasteboard_fade_leaves_exports_unchanged() {
|
||||
assert_eq!(exports(&mut app), plain);
|
||||
}
|
||||
|
||||
/// The fade's pieces around the artboard are painted as one mesh with no feathered edges. Each
|
||||
/// piece used to be filled on its own and faded out along the edges it shares with the next, so a
|
||||
/// lighter line ran from each artboard corner to the edges of the canvas (#10221).
|
||||
#[test]
|
||||
fn the_pasteboard_fade_is_one_mesh_with_no_seam_between_its_pieces() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("prefs.set", json!({"key": "fadeRegionOutsideArtboard", "value": true})).unwrap();
|
||||
app.select_tool("artboard");
|
||||
let ctx = crate::testing::ui_context();
|
||||
let fade = Color32::from_black_alpha(102);
|
||||
let drawn = shapes(&mut app, &ctx);
|
||||
assert!(super::artboards::fades_outside_artboards(&app));
|
||||
let meshes: Vec<_> = drawn
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Shape::Mesh(m) if m.vertices.iter().any(|v| v.color == fade) => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(meshes.len(), 1, "the fade is one mesh");
|
||||
assert!(meshes[0].vertices.iter().all(|v| v.color == fade), "no vertex of the fade fades out (a feathered edge)");
|
||||
// The pieces surround the artboard: more than one quad's two triangles.
|
||||
assert!(meshes[0].indices.len() > 6, "{} indices", meshes[0].indices.len());
|
||||
}
|
||||
|
||||
/// Finished worker renders are uploaded whenever they are not older than what is currently
|
||||
/// displayed on screen. During continuous edit streams (drag previews, held arrow nudges, or
|
||||
/// command bursts) where the document revision advances every frame, intermediate worker frames
|
||||
|
||||
@@ -293,7 +293,7 @@ fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected:
|
||||
let target = crate::panels::transparency_target(app);
|
||||
group(ui, rank::OPACITY, |ui| {
|
||||
let field = Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |ui, _| {
|
||||
let number = NumberField::new(label, Bind::given(Some(crate::panels::shown_percent(opacity))))
|
||||
let number = NumberField::new(label, Bind::given(Some(f64::from(opacity) * 100.0)))
|
||||
.range(0.0..=100.0)
|
||||
.unit("%")
|
||||
.scrub_by_label()
|
||||
|
||||
@@ -6,15 +6,14 @@ use super::*;
|
||||
fn every_tool_cursors_hotspot_is_on_its_glyph() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
crate::icons::register();
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
let mut missed = Vec::new();
|
||||
crate::testing::ui_context()
|
||||
.run_ui(Default::default(), |ui| {
|
||||
let env = Env::of(ui);
|
||||
let ink = rgba_color(env.tokens.tokens().color.overlay.cursor);
|
||||
let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8);
|
||||
// The tool marks are black; their white halo is not a part of the glyph a click lands on.
|
||||
let near_ink = |px: &[u8]| px[3] == 255 && px[..3].iter().all(|value| *value <= 8);
|
||||
for c in GLYPHS {
|
||||
let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue };
|
||||
let Some(image) = painted_image(&env, &painted, 2.0) else {
|
||||
@@ -71,6 +70,42 @@ fn a_tools_move_resize_grab_and_not_allowed_cursors_are_drawn_like_its_own() {
|
||||
assert!(matches!(tool_cursor(Cursor::Busy), cb::Cursor::System(_)), "the wait pointer stays the system's");
|
||||
}
|
||||
|
||||
/// The Selection and Direct Selection arrows, the Hand, the drawing crosshair and a tool cursor draw in black and
|
||||
/// white only, in the Modern and Classic color schemes and in light and dark interfaces: no pixel takes the accent or
|
||||
/// another hue over the artwork.
|
||||
#[test]
|
||||
fn drawing_pointers_draw_in_black_and_white() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::runtime::frame::{FrameInput, set_input};
|
||||
crate::icons::register();
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
let pointers = [Cursor::Arrow, Cursor::ArrowHollow, Cursor::Hand, Cursor::Crosshair, Cursor::Pen];
|
||||
use crate::theme::{Brightness, Scheme};
|
||||
let looks = [(Scheme::Modern, Brightness::Dark), (Scheme::Classic, Brightness::MediumDark), (Scheme::Classic, Brightness::Light)];
|
||||
for (scheme, brightness) in looks {
|
||||
let ctx = crate::testing::ui_context();
|
||||
let prefs = vectorcraft_engine::Prefs { ui_color_scheme: scheme.id().into(), ui_brightness: brightness.id().into(), ..Default::default() };
|
||||
set_input(&ctx, FrameInput::new(crate::app::root_env(&prefs, 1.0, None)));
|
||||
ctx.run_ui(Default::default(), |ui| {
|
||||
let env = Env::of(ui);
|
||||
for c in pointers {
|
||||
let cb::Cursor::Painted(painted) = tool_cursor(c) else { panic!("{c:?} is painted") };
|
||||
let image = painted_image(&env, &painted, 2.0).unwrap_or_else(|| panic!("{c:?} has no image"));
|
||||
let tinted = image
|
||||
.rgba
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.find(|px| px[3] > 0 && px[..3].iter().max().zip(px[..3].iter().min()).is_some_and(|(hi, lo)| hi - lo > 8));
|
||||
assert!(tinted.is_none(), "{scheme:?} {brightness:?} {c:?}: a pixel takes a hue: {tinted:?}");
|
||||
}
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `cursor-` icon name a cursor uses must be in the set the host registers.
|
||||
#[test]
|
||||
fn every_cursor_icon_the_app_names_is_in_its_set() {
|
||||
@@ -87,18 +122,16 @@ fn every_cursor_icon_the_app_names_is_in_its_set() {
|
||||
fn the_painted_pen_nibs_keep_their_breather_holes() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
crate::testing::ui_context()
|
||||
.run_ui(Default::default(), |ui| {
|
||||
let env = Env::of(ui);
|
||||
let tokens = env.tokens.tokens();
|
||||
let ink = rgba_color(tokens.color.overlay.cursor);
|
||||
let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8);
|
||||
// The tool marks are black, drawn on the icon's 24-unit box at one point per unit.
|
||||
let is_ink = |px: &[u8]| px[3] >= 240 && px[..3].iter().all(|value| *value <= 8);
|
||||
let scale = 4.0;
|
||||
let from_art_units = tokens.size.icon.md * scale / 24.0;
|
||||
let from_art_units = scale;
|
||||
for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] {
|
||||
let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else {
|
||||
panic!("{c:?} must have painted tool art");
|
||||
|
||||
@@ -14,15 +14,14 @@ use std::sync::{Arc, Weak};
|
||||
|
||||
use craft::imaging::ui::filter_gallery::{
|
||||
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree,
|
||||
FilterTreeLayout, GalleryFilter, GalleryThumb, LayerId, SessionField,
|
||||
GalleryFilter, GalleryThumb, LayerId, SessionField,
|
||||
};
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, LeastWidth, Props as _, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Picture, PictureSize};
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::notices::{Notice, NoticeLayout};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
@@ -46,9 +45,28 @@ use crate::file_asks::Owner;
|
||||
|
||||
/// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's.
|
||||
const THUMB: usize = 36;
|
||||
/// Sample image dimensions before the dialog scales the image to its display size.
|
||||
const PREVIEW_W: usize = 120;
|
||||
const PREVIEW_H: usize = 84;
|
||||
/// The preview's height over its width.
|
||||
const PREVIEW_ASPECT: (usize, usize) = (10, 7);
|
||||
|
||||
/// The preview's raster: `width` points wide at the screen's density, one device pixel to a texel, with `px`
|
||||
/// document points to a pixel so the filters draw the same at every density.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct PreviewSample {
|
||||
width: usize,
|
||||
height: usize,
|
||||
px: f64,
|
||||
}
|
||||
|
||||
impl PreviewSample {
|
||||
/// A sample `points` wide at `pixels_per_point`; a degenerate width or density gives one pixel.
|
||||
fn new(points: f32, pixels_per_point: f32) -> Self {
|
||||
let ppp = if pixels_per_point.is_finite() && pixels_per_point > 0.0 { pixels_per_point } else { 1.0 };
|
||||
let pixels = f64::from(points * ppp);
|
||||
let width = if pixels.is_finite() { pixels.round().max(1.0) as usize } else { 1 };
|
||||
let (wide, high) = PREVIEW_ASPECT;
|
||||
PreviewSample { width, height: (width * high / wide).max(1), px: 1.0 / f64::from(ppp) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The command the preview and OK run: the whole stack as one undo step.
|
||||
const COMMAND: &str = "command.batch";
|
||||
@@ -435,9 +453,11 @@ impl StackDialog for EffectGalleryDialog {
|
||||
let refusal = held.refusal().map(|(reason, _)| reason.clone());
|
||||
let current = (*selected).min(session.effects.len().saturating_sub(1));
|
||||
let visible = entries_of(&session.effects, index, true);
|
||||
let sample = PreviewSample::new(LeastWidth::SideMenu.points(Env::of(ui).tokens.tokens()), ui.ctx().pixels_per_point());
|
||||
let key = {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
serde_json::to_string(&stack_batch_params(&visible)).unwrap_or_default().hash(&mut hasher);
|
||||
(sample.width, sample.height).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
};
|
||||
let thumbs = Thumbnails::<GalleryThumb>::in_context(ui.ctx(), "effectGallery.thumbs", ThumbnailOptions::new());
|
||||
@@ -465,15 +485,17 @@ impl StackDialog for EffectGalleryDialog {
|
||||
cx.keep_view_open(canvas);
|
||||
}
|
||||
let Some(layer) = effects.get(current) else { return };
|
||||
let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H);
|
||||
let image = || color_image(&preview_rgba(&visible, sample.width, sample.height, sample.px), sample.width, sample.height);
|
||||
// The preview at the start, the category folders in the middle and the settings with the effect layers at
|
||||
// the end, as the Filter Gallery page lays them out.
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui);
|
||||
Picture::new(tl!("Preview"), key, &image).extent(PictureSize::DevicePixels).show(ui);
|
||||
let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).show(ui);
|
||||
if let Some(filter) = tree.picked {
|
||||
changes.push(EffectChange::set_filter(current, filter));
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Stack::new().least_width(LeastWidth::SideMenu).show(ui, |ui, _| {
|
||||
let params = EffectParameters::new(current, layer, index).show(ui);
|
||||
changes.extend(params.change);
|
||||
if params.path.is_some() {
|
||||
@@ -574,12 +596,12 @@ fn effect_label(id: &str) -> String {
|
||||
crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// Where the preview rasters sit: one document point per pixel, origin at the top-left.
|
||||
fn preview_space(w: usize, h: usize) -> PixelSpace {
|
||||
let (wf, hf) = (w as f64, h as f64);
|
||||
/// Where the preview rasters sit: `px` document points per pixel, origin at the top-left.
|
||||
fn preview_space(w: usize, h: usize, px: f64) -> PixelSpace {
|
||||
let (wf, hf) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
to_doc: Affine::scale(px),
|
||||
px,
|
||||
center: Point::new(wf / 2.0, hf / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wf, hf),
|
||||
channels: vectorcraft_effects::pixel::Channels::Rgb,
|
||||
@@ -637,9 +659,9 @@ fn sample_drawing(w: usize, h: usize) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id`
|
||||
/// is not one of those filters or the buffer is the wrong size.
|
||||
fn apply_pixel(id: &str, params: &Map<String, Value>, data: &mut [u8], w: usize, h: usize) {
|
||||
/// Run one raster filter on a premultiplied RGBA buffer of `px` document points to a pixel. Leaves it unchanged when
|
||||
/// `id` is not one of those filters or the buffer is the wrong size.
|
||||
fn apply_pixel(id: &str, params: &Map<String, Value>, data: &mut [u8], w: usize, h: usize, px: f64) {
|
||||
let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return };
|
||||
if n != data.len() || w == 0 || h == 0 {
|
||||
return;
|
||||
@@ -648,20 +670,21 @@ fn apply_pixel(id: &str, params: &Map<String, Value>, data: &mut [u8], w: usize,
|
||||
let Some(vectorcraft_effects::RasterFx::Pixel(fx)) = vectorcraft_effects::raster_effects(std::slice::from_ref(&effect)).into_iter().next() else {
|
||||
return;
|
||||
};
|
||||
fx.apply(data, w, h, &preview_space(w, h));
|
||||
fx.apply(data, w, h, &preview_space(w, h, px));
|
||||
}
|
||||
|
||||
/// A filter's thumbnail: the drawing at one point to a pixel with the filter applied.
|
||||
fn filtered(id: &str, params: &Map<String, Value>, w: usize, h: usize) -> Vec<u8> {
|
||||
let mut data = sample_drawing(w, h);
|
||||
apply_pixel(id, params, &mut data, w, h);
|
||||
apply_pixel(id, params, &mut data, w, h, 1.0);
|
||||
data
|
||||
}
|
||||
|
||||
/// The drawing with `layers` applied in order.
|
||||
fn preview_rgba(layers: &[StackEntry], w: usize, h: usize) -> Vec<u8> {
|
||||
/// The drawing at `px` document points to a pixel with `layers` applied in order.
|
||||
fn preview_rgba(layers: &[StackEntry], w: usize, h: usize, px: f64) -> Vec<u8> {
|
||||
let mut data = sample_drawing(w, h);
|
||||
for layer in layers {
|
||||
apply_pixel(&layer.effect, &layer.params, &mut data, w, h);
|
||||
apply_pixel(&layer.effect, &layer.params, &mut data, w, h, px);
|
||||
}
|
||||
data
|
||||
}
|
||||
@@ -845,6 +868,96 @@ mod tests {
|
||||
assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}");
|
||||
}
|
||||
|
||||
/// The bounds of the first accessibility node named `label` (and of `role`, when given), in `window` points, at
|
||||
/// `scale` pixels to a point.
|
||||
fn bounds(app: &mut VectorcraftApp, window: egui::Rect, scale: f32, label: &str, role: Option<egui::accesskit::Role>) -> Option<egui::Rect> {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let mut nodes = Vec::new();
|
||||
for _ in 0..3 {
|
||||
ctx.enable_accesskit();
|
||||
let mut input = egui::RawInput { screen_rect: Some(window), ..Default::default() };
|
||||
input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale);
|
||||
nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map(|update| update.nodes).unwrap_or_default();
|
||||
}
|
||||
let node = nodes.iter().map(|(_, node)| node).find(|node| {
|
||||
let named = node.label() == Some(label)
|
||||
|| node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label)));
|
||||
named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some()
|
||||
})?;
|
||||
let b = node.bounds()?;
|
||||
Some(egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))
|
||||
}
|
||||
|
||||
/// The preview stands at the start beside the category folders and the settings, side by side, and is larger
|
||||
/// than a filter's thumbnail; in a short window the dialog still fits, and at twice the density the preview keeps
|
||||
/// its size in points. Brazilian Portuguese has the longest labels of the reported layout.
|
||||
#[test]
|
||||
fn gallery_layout_puts_preview_folders_and_settings_side_by_side() {
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Pos2, Rect, vec2};
|
||||
|
||||
let cases = [
|
||||
("en", vec2(1280.0, 800.0), 1.0),
|
||||
("en", vec2(1280.0, 800.0), 2.0),
|
||||
("pt-br", vec2(1280.0, 800.0), 1.0),
|
||||
("pt-br", vec2(900.0, 560.0), 1.0),
|
||||
];
|
||||
let mut widths = Vec::new();
|
||||
for (language, size, scale) in cases {
|
||||
let window = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let bounds = |app: &mut VectorcraftApp, label: &str, role| bounds(app, window, scale, label, role);
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.session.prefs.interface_language = language.to_owned();
|
||||
let lang = app.ui_language();
|
||||
let label = |name: &'static str| crate::i18n::tr(lang, name);
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
bounds(&mut app, "", None);
|
||||
app.run("ui.effectGalleryDialog", json!({})).unwrap();
|
||||
let at = format!("{language} at {size:?} scale {scale}");
|
||||
let gallery = bounds(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("the gallery");
|
||||
let preview = bounds(&mut app, label("Preview"), Some(Role::Image)).expect("the preview");
|
||||
// A filter of the folder that opens with the gallery; the stack's one layer is another filter.
|
||||
let cutout = crate::i18n::effect_name(lang, "artistic.cutout").unwrap();
|
||||
let tile = bounds(&mut app, &cutout, None).expect("the Cutout tile");
|
||||
// The settings' Filter select is named by the framework's own words, which this check reads in English.
|
||||
let filter = bounds(&mut app, "Filter", None);
|
||||
assert!(filter.is_some() || language != "en", "{at}: the settings' Filter select");
|
||||
let ok = bounds(&mut app, label("OK"), Some(Role::Button)).expect("OK");
|
||||
assert_eq!(app.ui_ctx.as_ref().unwrap().pixels_per_point(), scale, "{at}: the window's density");
|
||||
if language == "en" {
|
||||
widths.push(preview.width());
|
||||
}
|
||||
eprintln!("{at}: gallery {gallery:?}, preview {preview:?}, tile {tile:?}, filter {filter:?}, OK {ok:?}");
|
||||
assert!(window.contains_rect(gallery), "{at}: the gallery fits the window: {gallery:?}");
|
||||
assert!(gallery.contains_rect(preview) && gallery.contains_rect(ok), "{at}: the preview and OK are inside the gallery");
|
||||
assert!(preview.right() <= tile.left(), "{at}: the folders stand after the preview: {preview:?} {tile:?}");
|
||||
assert!(preview.top() < tile.bottom() && tile.top() < preview.bottom(), "{at}: the preview and the folders share a line");
|
||||
assert!(preview.width() > 2.0 * tile.width(), "{at}: the preview is larger than a thumbnail: {preview:?} {tile:?}");
|
||||
if let Some(filter) = filter {
|
||||
assert!(tile.right() <= filter.left(), "{at}: the settings stand after the folders: {tile:?} {filter:?}");
|
||||
}
|
||||
}
|
||||
assert!((widths[0] - widths[1]).abs() <= 1.0, "the preview keeps its size in points at twice the density: {widths:?}");
|
||||
}
|
||||
|
||||
/// The preview's raster has a texel per device pixel and draws its filters at document size whatever the
|
||||
/// density; a density that is not a positive number counts as one pixel to a point.
|
||||
#[test]
|
||||
fn preview_sample_follows_the_density() {
|
||||
use super::PreviewSample;
|
||||
let one = PreviewSample::new(200.0, 1.0);
|
||||
let two = PreviewSample::new(200.0, 2.0);
|
||||
assert_eq!((two.width, two.height), (2 * one.width, 2 * one.height));
|
||||
assert_eq!(two.width as f64 * two.px, one.width as f64 * one.px, "the same document width at both densities");
|
||||
assert!(one.height < one.width, "the preview is wider than it is high");
|
||||
for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
|
||||
assert_eq!(PreviewSample::new(200.0, bad), one, "density {bad}");
|
||||
}
|
||||
let empty = PreviewSample::new(0.0, 1.0);
|
||||
assert!(empty.width >= 1 && empty.height >= 1, "{empty:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_preview_is_one_interaction() {
|
||||
let (mut app, ctx, node) = drawing();
|
||||
|
||||
@@ -127,14 +127,13 @@ impl VectorcraftApp {
|
||||
/// after losing its graphics), everything uploaded to the old one is made again: the fonts and
|
||||
/// theme, the canvas, the place cursor's thumbnails and every [`TexCache`]. The host hands it
|
||||
/// the window's context when it creates the app, so the first frame's input has the app's
|
||||
/// commands. Each new context draws its text without hinting ([`crate::ui_fonts::hinting_off`]).
|
||||
/// commands.
|
||||
pub fn adopt_context(&mut self, ctx: &egui::Context) {
|
||||
let tag = context_tag(ctx);
|
||||
self.ui_ctx = Some(ctx.clone());
|
||||
if self.context == tag {
|
||||
return;
|
||||
}
|
||||
crate::ui_fonts::hinting_off(ctx);
|
||||
if self.context != 0 {
|
||||
log::info!("vectorcraft: new graphics context: uploading the UI again");
|
||||
forget_textures();
|
||||
|
||||
@@ -16,6 +16,8 @@ pub(crate) mod export;
|
||||
mod open;
|
||||
mod read_only_save;
|
||||
pub(crate) mod save;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod saved_contents;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_read_only_save;
|
||||
|
||||
@@ -180,7 +180,7 @@ pub(crate) fn opened(app: &mut VectorcraftApp, r: &Value) {
|
||||
if let Some(st) = index.and_then(|i| app.session.documents().get(i))
|
||||
&& let Some(path) = &st.path
|
||||
{
|
||||
app.saves.watch.known_now(st.uid, Path::new(path));
|
||||
app.saves.known_now(st.uid, Path::new(path));
|
||||
}
|
||||
let notes = open_notes(app, r);
|
||||
crate::dialogs::missing_links::after_open(app, r, notes);
|
||||
|
||||
+262
-15
@@ -1,14 +1,16 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads.
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::path::Path;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft::dialogs::save::{SAVE_IN_PROGRESS, SaveDocument, SaveFlow, SaveStep, SaveTarget};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft::host::Files;
|
||||
use craft::host::{FileFilter, PickRequest, Picked, Wake};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft::platform::watch::FileStamp;
|
||||
use craft::platform::watch::FileWatch;
|
||||
use craft::ui::dialog::DialogId;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -48,12 +50,31 @@ struct SaveDone {
|
||||
then: Option<Done>,
|
||||
}
|
||||
|
||||
/// A save whose flow would ask whether to replace its document's file, waiting for the file to be
|
||||
/// compared with the bytes the app last read or wrote.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Checking {
|
||||
path: PathBuf,
|
||||
/// The file's version when it holds those bytes, else `None`.
|
||||
answer: Receiver<Option<FileStamp>>,
|
||||
}
|
||||
|
||||
/// The saves of the app: one [`SaveFlow`] per document, and what the flows need to ask and write.
|
||||
pub(crate) struct Saves {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
flows: HashMap<u64, SaveFlow<u64>>,
|
||||
/// The version of each document's file the app last read or wrote.
|
||||
pub(crate) watch: FileWatch<u64>,
|
||||
/// The digest of the bytes of each document's file, as the app last read or wrote them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
contents: super::saved_contents::SavedContents,
|
||||
/// The saves waiting for a comparison of their document's file with those bytes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
checks: HashMap<u64, Checking>,
|
||||
/// A comparison's save waited in the last pass for a dialog, a file picker or a gesture in
|
||||
/// another document: [`after_ui`] asks for a frame once it no longer has to.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
held: bool,
|
||||
/// The files written beside each document's file, which its next save replaces.
|
||||
pub(crate) written_beside: HashMap<u64, Vec<String>>,
|
||||
/// The files the OK of the replace question allows the save it runs again to replace.
|
||||
@@ -68,6 +89,12 @@ impl Saves {
|
||||
Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
flows: HashMap::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
contents: super::saved_contents::SavedContents::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
checks: HashMap::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
held: false,
|
||||
watch: FileWatch::new(wake),
|
||||
written_beside: HashMap::new(),
|
||||
replace_files_ok: Vec::new(),
|
||||
@@ -76,12 +103,55 @@ impl Saves {
|
||||
}
|
||||
}
|
||||
|
||||
/// The app just read document `uid`'s file at `path`: that version is not a change on disk.
|
||||
pub(crate) fn known_now(&mut self, uid: u64, path: &Path) {
|
||||
self.watch.known_now(uid, path);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.note_contents(uid, path);
|
||||
}
|
||||
|
||||
/// Takes the digest of document `uid`'s file at `path`, the version the watcher just recorded.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn note_contents(&mut self, uid: u64, path: &Path) {
|
||||
match FileStamp::at(path) {
|
||||
// Not differing from the watcher's version: the file has not changed since it was recorded.
|
||||
Some(stamp) if !self.watch.disk_differs(&uid, path, None) => self.contents.note(uid, path, stamp),
|
||||
_ => self.contents.forget(uid),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops tracking document `uid`'s file (the document closed).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn forget(&mut self, uid: u64) {
|
||||
self.watch.forget(&uid);
|
||||
self.contents.forget(uid);
|
||||
self.checks.remove(&uid);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start(&mut self, files: &dyn Files, document: SaveDocument<u64>, target: SaveTarget) -> SaveStep<u64> {
|
||||
let Self { flows, watch, .. } = self;
|
||||
flows.entry(document.key).or_default().start(files, watch, document, target)
|
||||
}
|
||||
|
||||
/// The answer of document `uid`'s file comparison, once it has come (with `wait`, once it
|
||||
/// comes): the file's version when it holds the bytes the app last read or wrote, and the
|
||||
/// file's path. `None` while there is no answer yet, or no comparison.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn answer(&mut self, uid: u64, wait: bool) -> Option<(Option<FileStamp>, PathBuf)> {
|
||||
let check = self.checks.get(&uid)?;
|
||||
let same = if wait {
|
||||
check.answer.recv().ok().flatten()
|
||||
} else {
|
||||
match check.answer.try_recv() {
|
||||
Ok(same) => same,
|
||||
Err(TryRecvError::Empty) => return None,
|
||||
Err(TryRecvError::Disconnected) => None,
|
||||
}
|
||||
};
|
||||
self.checks.remove(&uid).map(|c| (same, c.path))
|
||||
}
|
||||
|
||||
/// Frees the document's flow after a write that wrote nothing.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn release(&mut self, uid: u64) {
|
||||
@@ -91,6 +161,63 @@ impl Saves {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether file comparisons need another frame to collect their answers.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn checks_pending(app: &VectorcraftApp) -> bool {
|
||||
// A save waiting for a dialog or a gesture goes on in the frame after the one that ends it ([`after_ui`]).
|
||||
app.saves.checks.keys().any(|uid| !held(app, *uid))
|
||||
}
|
||||
|
||||
/// Whether document `uid`'s save has to wait: the document shows a dialog's preview or a drag not
|
||||
/// yet committed, which the save would write (typing in progress is saved, as by any Save), or
|
||||
/// writing it activates its document, which would put it under an open dialog or file picker of
|
||||
/// another document, cancel a drag in progress in the active one, or fail while a script runs.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn held(app: &VectorcraftApp, uid: u64) -> bool {
|
||||
if app.session.documents().iter().any(|d| d.uid == uid && d.interaction.as_ref().is_some_and(|it| it.label != "Typing")) {
|
||||
return true;
|
||||
}
|
||||
let active = app.session.active();
|
||||
active.map(|d| d.uid) != Some(uid)
|
||||
&& (app.any_dialog_open()
|
||||
|| app.file_dialog_open()
|
||||
|| active.is_some_and(|d| d.interaction.is_some())
|
||||
|| app.canvas.grab.is_some()
|
||||
|| app.session.script_running())
|
||||
}
|
||||
|
||||
/// Whether document `uid`'s save waits for the comparison of its file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn checking(app: &VectorcraftApp, uid: u64) -> bool {
|
||||
app.saves.checks.contains_key(&uid)
|
||||
}
|
||||
|
||||
/// The web has no file comparisons.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn checking(_: &VectorcraftApp, _: u64) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Asks for one frame when a save waited in the last pass and this pass's UI closed what it
|
||||
/// waited for: the dialog pumps and the canvas run after [`pump`], so nothing else would.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn after_ui(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if app.saves.held && app.saves.checks.keys().any(|uid| !held(app, *uid)) {
|
||||
app.saves.held = false;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// The web has no saves that wait.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn after_ui(_: &mut VectorcraftApp, _: &egui::Context) {}
|
||||
|
||||
/// The web has no file comparisons to collect.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn checks_pending(_: &VectorcraftApp) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Calls the `then` of the document's save, once.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn terminate(app: &mut VectorcraftApp, uid: u64, r: Result<Value, String>) {
|
||||
@@ -107,10 +234,24 @@ fn finish(app: &mut VectorcraftApp, uid: u64, retargets: bool, out: &Result<Valu
|
||||
let written = out.as_ref().ok().filter(|v| v.get("cancelled").is_none() && v.get("pending").is_none());
|
||||
let flow = app.saves.flows.entry(uid).or_default();
|
||||
match written.and_then(|v| v["path"].as_str()) {
|
||||
Some(path) if flow.is_busy() || retargets => flow.written(&mut app.saves.watch, uid, Path::new(path)),
|
||||
Some(path) if flow.is_busy() || retargets => {
|
||||
flow.written(&mut app.saves.watch, uid, Path::new(path));
|
||||
// The document's own file (not a copy's): its digest goes with the version the watcher took.
|
||||
if app.session.documents().iter().any(|d| d.uid == uid && d.path.as_deref() == Some(path)) {
|
||||
app.saves.note_contents(uid, Path::new(path));
|
||||
}
|
||||
}
|
||||
_ => flow.failed(&uid),
|
||||
}
|
||||
if !matches!(out, Ok(v) if v.get("pending").is_some()) {
|
||||
// A comparison still pending belongs to the save this one ends (a save with an explicit path
|
||||
// ran meanwhile): it is dropped and its flow freed, since its answer would ask about the file
|
||||
// with no save left to apply the answer.
|
||||
if app.saves.checks.remove(&uid).is_some()
|
||||
&& let Some(flow) = app.saves.flows.get_mut(&uid)
|
||||
{
|
||||
let _ = flow.cancel(app.host.files());
|
||||
}
|
||||
terminate(app, uid, out.clone());
|
||||
}
|
||||
}
|
||||
@@ -124,10 +265,12 @@ pub(crate) fn allow_replacing(app: &mut VectorcraftApp, files: &[String]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes what the flows and their questions have answered since the last pass: the pick, the
|
||||
/// changed-on-disk question's answer. A save whose document closed is cancelled and forgotten.
|
||||
/// Takes what the flows and their questions have answered since the last pass: the comparison of
|
||||
/// a document's file, the pick, the changed-on-disk question's answer. A save whose document
|
||||
/// closed is cancelled and forgotten. Closed documents' digest state is dropped on every pass.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
resume_checked(app, false);
|
||||
let busy: Vec<u64> = app.saves.flows.iter().filter(|(_, f)| f.is_busy()).map(|(uid, _)| *uid).collect();
|
||||
for uid in busy {
|
||||
if !app.session.documents().iter().any(|d| d.uid == uid) {
|
||||
@@ -136,7 +279,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
if let Some(mut flow) = app.saves.flows.remove(&uid) {
|
||||
flow.cancel(app.host.files());
|
||||
}
|
||||
app.saves.watch.forget(&uid);
|
||||
app.saves.forget(uid);
|
||||
continue;
|
||||
}
|
||||
let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone());
|
||||
@@ -152,6 +295,83 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
app.saves.contents.retain_open(app.session.documents().iter().map(|d| d.uid));
|
||||
}
|
||||
|
||||
/// Goes on with the saves whose file comparison has answered (with `wait`, every one, once it
|
||||
/// answers): an unchanged file is written over, and a changed one is asked about.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn resume_checked(app: &mut VectorcraftApp, wait: bool) {
|
||||
let checking: Vec<u64> = app.saves.checks.keys().copied().collect();
|
||||
for uid in checking {
|
||||
// A closed document's save is cancelled with its flow, in [`pump`].
|
||||
let Some(file) = app.session.documents().iter().find(|d| d.uid == uid).map(|d| d.path.clone()) else {
|
||||
continue;
|
||||
};
|
||||
// Writing activates the save's document: while a dialog or file picker of another document
|
||||
// is open, a drag goes on in it, or a script runs, the answer stays in its channel for a
|
||||
// later pass.
|
||||
if !wait && held(app, uid) {
|
||||
app.saves.held = true;
|
||||
continue;
|
||||
}
|
||||
let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone());
|
||||
let r = scope.run(|| {
|
||||
file_asks::as_automated(app, automated, |app| {
|
||||
// The document now uses another file (a Save As finished meanwhile): the comparison
|
||||
// is dropped and its save cancelled, without asking about the old file.
|
||||
if app.saves.checks.get(&uid).is_some_and(|c| file.as_deref().map(Path::new) != Some(c.path.as_path())) {
|
||||
app.saves.checks.remove(&uid);
|
||||
let step = app.saves.flows.get_mut(&uid).and_then(|f| f.cancel(app.host.files()));
|
||||
return step.map(|step| run_step(app, uid, step));
|
||||
}
|
||||
let (same, path) = app.saves.answer(uid, wait)?;
|
||||
// Still that version: a change made since the comparison is asked about.
|
||||
let Some(stamp) = same.filter(|stamp| FileStamp::at(&path) == Some(*stamp)) else {
|
||||
let asked = ask_changed_on_disk(app, uid, &path);
|
||||
return Some(settle(app, uid, asked));
|
||||
};
|
||||
// The same bytes: the file's version now is the document's, and the flow writes over it.
|
||||
app.saves.watch.known_as(uid, &path, Some(stamp));
|
||||
let step = app.saves.flows.get_mut(&uid).map_or(SaveStep::Busy, SaveFlow::replace);
|
||||
Some(run_step(app, uid, step))
|
||||
})
|
||||
});
|
||||
if let Some(Err(e)) = r
|
||||
&& e != "cancelled"
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for every save's file comparison and goes on with those saves.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) fn wait_for_checks(app: &mut VectorcraftApp) {
|
||||
resume_checked(app, true);
|
||||
}
|
||||
|
||||
/// Waits for every save's file comparison to answer and its thread to end (its wake included),
|
||||
/// leaving each answer for the next [`pump`].
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) fn wait_for_answers(app: &mut VectorcraftApp) {
|
||||
for check in app.saves.checks.values_mut() {
|
||||
let (send, answer) = std::sync::mpsc::channel();
|
||||
if let Ok(same) = check.answer.recv() {
|
||||
let _ = send.send(same);
|
||||
}
|
||||
// The thread drops its sender as it ends, after its wake.
|
||||
let _ = check.answer.recv();
|
||||
check.answer = answer;
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the active document's baseline digest and compares it with the file.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) fn wait_for_contents(app: &VectorcraftApp) -> Option<FileStamp> {
|
||||
let document = app.session.active()?;
|
||||
let path = Path::new(document.path.as_deref()?);
|
||||
app.saves.contents.check(document.uid, path, Wake::none())?.recv().ok().flatten()
|
||||
}
|
||||
|
||||
/// The web has no save flows: nothing answers between passes.
|
||||
@@ -182,6 +402,12 @@ fn next_step(app: &mut VectorcraftApp, uid: u64) -> Option<SaveStep<u64>> {
|
||||
/// Runs `step` of the document `uid`'s save; a failure frees the flow and tells the caller.
|
||||
fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep<u64>) -> Result<Value, String> {
|
||||
let r = proceed(app, step);
|
||||
settle(app, uid, r)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The result `r` of a step of document `uid`'s save; a failure frees the flow and tells the caller.
|
||||
fn settle(app: &mut VectorcraftApp, uid: u64, r: Result<Value, String>) -> Result<Value, String> {
|
||||
if r.is_err() {
|
||||
app.saves.release(uid);
|
||||
terminate(app, uid, r.clone());
|
||||
@@ -189,19 +415,40 @@ fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep<u64>) -> Result<V
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// The changed-on-disk question about document `key`'s file at `path`.
|
||||
fn ask_changed_on_disk(app: &mut VectorcraftApp, key: u64, path: &Path) -> Result<Value, String> {
|
||||
let name = fileio::file_name(&path.to_string_lossy());
|
||||
let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key));
|
||||
let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt));
|
||||
if let Some(done) = app.saves.done.get_mut(&key) {
|
||||
done.question = Some(id);
|
||||
}
|
||||
Ok(json!({ "pending": "changedOnDisk" }))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// Asks the window for a frame, from any thread; does nothing without a window.
|
||||
fn ui_wake(app: &VectorcraftApp) -> Wake {
|
||||
app.ui_ctx.clone().map_or_else(Wake::none, |ctx| Wake::new(move || ctx.request_repaint()))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn proceed(app: &mut VectorcraftApp, step: SaveStep<u64>) -> Result<Value, String> {
|
||||
match step {
|
||||
SaveStep::Picking => Ok(json!({ "pending": "fileDialog" })),
|
||||
SaveStep::AskChangedOnDisk { key, path } => {
|
||||
let name = fileio::file_name(&path.to_string_lossy());
|
||||
let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key));
|
||||
let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt));
|
||||
if let Some(done) = app.saves.done.get_mut(&key) {
|
||||
done.question = Some(id);
|
||||
// Before asking, the file is compared with the bytes the app last read or wrote: a file
|
||||
// whose metadata alone changed (a cloud-sync folder sets attributes on it, or puts the same
|
||||
// bytes back as a new file) is written over without asking (#10734). [`pump`] goes on.
|
||||
// The comparison's thread asks for a frame once it answers: a save started from the UI comes
|
||||
// after this frame's repaint decision.
|
||||
SaveStep::AskChangedOnDisk { key, path } => match app.saves.contents.check(key, &path, ui_wake(app)) {
|
||||
Some(answer) => {
|
||||
app.saves.checks.insert(key, Checking { path, answer });
|
||||
Ok(json!({ "pending": "checkingFile" }))
|
||||
}
|
||||
Ok(json!({ "pending": "changedOnDisk" }))
|
||||
}
|
||||
None => ask_changed_on_disk(app, key, &path),
|
||||
},
|
||||
SaveStep::Write { key, path, target, file_type } => write_step(app, key, &path.to_string_lossy(), target, file_type),
|
||||
SaveStep::Cancelled { key } => {
|
||||
terminate(app, key, Err("cancelled".into()));
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
//! The bytes of each open document's file as the app last read or wrote them, kept as a SHA-256
|
||||
//! digest (#10734). Save asks before replacing a file another app changed, and the save flow
|
||||
//! counts a new change time or a new inode as a change. A cloud-sync folder sets
|
||||
//! attributes on a file after uploading it, or puts the same bytes back as a new file. When the
|
||||
//! file on disk still holds the bytes the app wrote, Save writes without asking.
|
||||
//!
|
||||
//! Files are read and digested on threads of their own: a file in a cloud folder may have to be
|
||||
//! downloaded first. Each thread reads under the file-access scope of the call that started it: a
|
||||
//! file that scope may not read leaves no digest, and Save asks as it does on a change.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use craft::host::Wake;
|
||||
use craft::platform::watch::FileStamp;
|
||||
use sha2::{Digest, Sha256};
|
||||
use vectorcraft_engine::file_access::{self, ScopeHandle};
|
||||
|
||||
/// A version of a document's file: its path, its stamp when read, and the digest of its bytes.
|
||||
#[derive(Clone)]
|
||||
struct Version {
|
||||
path: PathBuf,
|
||||
stamp: FileStamp,
|
||||
digest: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
versions: HashMap<u64, Version>,
|
||||
/// Counts the notes of each document: a digest taken for an older note is dropped.
|
||||
notes: HashMap<u64, u64>,
|
||||
/// The digest being taken for each document's newest note.
|
||||
pending: HashMap<u64, JoinHandle<()>>,
|
||||
}
|
||||
|
||||
/// The digests of the open documents' files.
|
||||
pub(crate) struct SavedContents {
|
||||
state: Arc<Mutex<State>>,
|
||||
}
|
||||
|
||||
fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
|
||||
state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
impl SavedContents {
|
||||
/// No digests yet.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { state: Arc::default() }
|
||||
}
|
||||
|
||||
/// The app just read or wrote document `key`'s file at `path`, and `stamp` is that version.
|
||||
/// The file is opened and its digest taken on a thread of its own. Any stamp change
|
||||
/// before or during the read leaves no digest, so Save asks on a change.
|
||||
pub(crate) fn note(&self, key: u64, path: &Path, stamp: FileStamp) {
|
||||
let note = {
|
||||
let mut state = lock(&self.state);
|
||||
state.versions.remove(&key);
|
||||
state.pending.remove(&key);
|
||||
let note = state.notes.entry(key).or_default();
|
||||
*note = note.wrapping_add(1);
|
||||
*note
|
||||
};
|
||||
let state = Arc::clone(&self.state);
|
||||
let path = path.to_path_buf();
|
||||
let scope = ScopeHandle::capture_now();
|
||||
let work = move || {
|
||||
if !readable(scope, &path) {
|
||||
return;
|
||||
}
|
||||
let Ok(file) = File::open(&path) else { return };
|
||||
let Some(digest) = digest_of(file, stamp) else { return };
|
||||
let mut state = lock(&state);
|
||||
if state.notes.get(&key) == Some(¬e) {
|
||||
state.versions.insert(key, Version { path, stamp, digest });
|
||||
}
|
||||
};
|
||||
// Without a thread nothing is recorded, and Save asks on any change, as before.
|
||||
if let Ok(handle) = std::thread::Builder::new().name("vectorcraft-file-digest".into()).spawn(work) {
|
||||
lock(&self.state).pending.insert(key, handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts comparing document `key`'s file at `path` with the version the app last read or
|
||||
/// wrote, on a thread of its own that first waits for that version's digest. The answer is
|
||||
/// the file's version now when it holds the same bytes, and `None` when the bytes differ, the
|
||||
/// file can't be read (or the caller's scope may not read it), or no digest of `path` was
|
||||
/// taken. `wake` runs once the answer is sent, so a frame collects it. `None` here when no
|
||||
/// thread starts.
|
||||
pub(crate) fn check(&self, key: u64, path: &Path, wake: Wake) -> Option<Receiver<Option<FileStamp>>> {
|
||||
let pending = lock(&self.state).pending.remove(&key);
|
||||
let state = Arc::clone(&self.state);
|
||||
let path = path.to_path_buf();
|
||||
let scope = ScopeHandle::capture_now();
|
||||
let (send, answer) = mpsc::channel();
|
||||
let work = move || {
|
||||
if let Some(handle) = pending {
|
||||
// A digest thread that panicked recorded nothing.
|
||||
let _ = handle.join();
|
||||
}
|
||||
let same = if readable(scope, &path) { unchanged(&state, key, &path) } else { None };
|
||||
// The caller may be gone (its document closed): the answer is dropped.
|
||||
let _ = send.send(same);
|
||||
wake.wake();
|
||||
};
|
||||
std::thread::Builder::new().name("vectorcraft-file-check".into()).spawn(work).ok().map(|_| answer)
|
||||
}
|
||||
|
||||
/// Document `key` closed: its digest is dropped, and one still being taken is not recorded.
|
||||
pub(crate) fn forget(&self, key: u64) {
|
||||
let mut state = lock(&self.state);
|
||||
state.versions.remove(&key);
|
||||
state.pending.remove(&key);
|
||||
let note = state.notes.entry(key).or_default();
|
||||
*note = note.wrapping_add(1);
|
||||
}
|
||||
|
||||
/// Drops closed documents' versions, pending handles and note counters only when needed.
|
||||
/// Removing a note counter prevents its digest thread from recording a version later.
|
||||
pub(crate) fn retain_open(&self, open: impl Iterator<Item = u64> + Clone) {
|
||||
let mut state = lock(&self.state);
|
||||
let is_open = |key: &u64| open.clone().any(|uid| uid == *key);
|
||||
if state.notes.keys().any(|key| !is_open(key)) {
|
||||
state.versions.retain(|key, _| is_open(key));
|
||||
state.pending.retain(|key, _| is_open(key));
|
||||
state.notes.retain(|key, _| is_open(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// May `scope`, the file-access scope of the call that started a thread, read `path`?
|
||||
fn readable(scope: ScopeHandle, path: &Path) -> bool {
|
||||
scope.run(|| file_access::check_read(&path.to_string_lossy()).is_ok())
|
||||
}
|
||||
|
||||
/// [`SavedContents::check`]'s answer, on its thread.
|
||||
fn unchanged(state: &Mutex<State>, key: u64, path: &Path) -> Option<FileStamp> {
|
||||
let version = lock(state).versions.get(&key).filter(|v| v.path == path).cloned()?;
|
||||
let now = FileStamp::at(path)?;
|
||||
if now.len() != version.stamp.len() || digest_of(File::open(path).ok()?, now)? != version.digest || FileStamp::at(path) != Some(now) {
|
||||
return None;
|
||||
}
|
||||
if let Some(v) = lock(state).versions.get_mut(&key).filter(|v| v.digest == version.digest) {
|
||||
v.stamp = now;
|
||||
}
|
||||
Some(now)
|
||||
}
|
||||
|
||||
/// The digest of `file`, read while its full stamp stays at `stamp`; `None` when the stamp
|
||||
/// differs or the file can't be read. A Unix change time alone can also signal changed bytes.
|
||||
fn digest_of(mut file: File, stamp: FileStamp) -> Option<[u8; 32]> {
|
||||
if !file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp) {
|
||||
return None;
|
||||
}
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = file.read(&mut buffer).ok()?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(buffer.get(..n)?);
|
||||
}
|
||||
file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp).then(|| hasher.finalize().into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retaining_open_documents_drops_closed_documents_state() {
|
||||
let folder = crate::tests_folder::Folder::new("saved-contents-retain");
|
||||
let file = folder.file("document", b"saved contents");
|
||||
let path = Path::new(&file);
|
||||
let stamp = FileStamp::at(path).unwrap();
|
||||
let contents = SavedContents::new();
|
||||
for uid in [1, 2] {
|
||||
contents.note(uid, path, stamp);
|
||||
assert!(contents.check(uid, path, Wake::none()).unwrap().recv().unwrap().is_some());
|
||||
}
|
||||
// A third document closes while its digest handle is still retained.
|
||||
contents.note(3, path, stamp);
|
||||
contents.retain_open([2].into_iter());
|
||||
|
||||
{
|
||||
let state = lock(&contents.state);
|
||||
for uid in [1, 3] {
|
||||
assert!(!state.versions.contains_key(&uid));
|
||||
assert!(!state.pending.contains_key(&uid));
|
||||
assert!(!state.notes.contains_key(&uid));
|
||||
}
|
||||
}
|
||||
assert!(contents.check(1, path, Wake::none()).unwrap().recv().unwrap().is_none());
|
||||
assert!(contents.check(3, path, Wake::none()).unwrap().recv().unwrap().is_none());
|
||||
assert!(contents.check(2, path, Wake::none()).unwrap().recv().unwrap().is_some());
|
||||
}
|
||||
|
||||
/// A file in a folder the caller may write but not read is neither digested nor compared.
|
||||
#[test]
|
||||
fn a_file_the_callers_scope_may_not_read_is_not_read() {
|
||||
let folder = crate::tests_folder::Folder::new("saved-contents-write-only");
|
||||
let file = folder.file("document", b"saved contents");
|
||||
let path = Path::new(&file);
|
||||
let stamp = FileStamp::at(path).unwrap();
|
||||
let roots = file_access::AutomationRoots::new(&[], &[path.parent().unwrap()]).unwrap();
|
||||
let contents = SavedContents::new();
|
||||
|
||||
file_access::confine(roots.as_ref(), || contents.note(1, path, stamp));
|
||||
let noted_confined = contents.check(1, path, Wake::none()).unwrap().recv().unwrap();
|
||||
|
||||
contents.note(2, path, stamp);
|
||||
let confined = file_access::confine(roots.as_ref(), || contents.check(2, path, Wake::none())).unwrap().recv().unwrap();
|
||||
let unconfined = contents.check(2, path, Wake::none()).unwrap().recv().unwrap();
|
||||
|
||||
assert!(noted_confined.is_none(), "no digest is taken of a file the scope may not read");
|
||||
assert!(confined.is_none(), "a comparison in a scope that may not read the file does not read it");
|
||||
assert!(unconfined.is_some(), "the digest taken outside that scope still compares");
|
||||
}
|
||||
}
|
||||
@@ -329,6 +329,61 @@ fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() {
|
||||
assert!(h.app.session.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
/// A stand-in for the platform menu bar: the key equivalents it reports.
|
||||
#[derive(Clone, Default)]
|
||||
struct FakeMenu(Rc<RefCell<Vec<craft::menu::Event>>>);
|
||||
|
||||
impl craft::menu::Backend for FakeMenu {
|
||||
fn sync(&mut self, _bar: &craft::menu::MenuBar) {}
|
||||
fn drain(&mut self) -> Vec<craft::menu::Event> {
|
||||
std::mem::take(&mut self.0.borrow_mut())
|
||||
}
|
||||
fn attach(&mut self, _dispatch: craft::menu::Dispatch) {}
|
||||
}
|
||||
|
||||
/// The native menu's Undo and Redo key equivalents, made while a floating panel's or a floating toolbar's OS window
|
||||
/// has the keys and none of its text fields is focused, change the document once each.
|
||||
#[test]
|
||||
fn native_undo_and_redo_from_a_floating_window_change_the_document_once() {
|
||||
for what in ["panel", "toolbar"] {
|
||||
let mut h = Harness::new();
|
||||
h.ctx.set_os(egui::os::OperatingSystem::Mac);
|
||||
let menu = FakeMenu::default();
|
||||
h.app.services.native_menu = Some(craft::menu::NativeMenu::new(Box::new(menu.clone())));
|
||||
let viewport = if what == "panel" {
|
||||
h.float("swatches")
|
||||
} else {
|
||||
h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap();
|
||||
h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap();
|
||||
h.frames(3);
|
||||
let panel = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id);
|
||||
let viewport = h.viewport(&panel);
|
||||
h.host.borrow_mut().focus = viewport;
|
||||
viewport
|
||||
};
|
||||
let [first, second] = [10, 80].map(|x| {
|
||||
let id = h.app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
vectorcraft_doc::NodeId(id)
|
||||
});
|
||||
h.frames(2);
|
||||
let host = craft::ui::runtime::windows::WindowHost::of(&h.ctx);
|
||||
assert!(host.key_window() == viewport && !host.typing(), "{what}: the floating window has the keys, with no field typing");
|
||||
let present = |h: &Harness| {
|
||||
let doc = &h.app.session.active().unwrap().doc;
|
||||
[first, second].map(|id| doc.node(id).is_some())
|
||||
};
|
||||
for (chord, shift, after) in [("Cmd+Z", false, [true, false]), ("Cmd+Shift+Z", true, [true, true])] {
|
||||
menu.0.borrow_mut().push(craft::menu::Event::Key(craft::menu::Chord::parse(chord).unwrap()));
|
||||
h.frame(vec![]);
|
||||
// The key-up reaches the window that has the keys.
|
||||
let modifiers = egui::Modifiers { mac_cmd: true, command: true, shift, ..Default::default() };
|
||||
frame_in(&mut h, viewport, vec![Event::Key { key: Key::Z, physical_key: Some(Key::Z), pressed: false, repeat: false, modifiers }]);
|
||||
h.frames(3);
|
||||
assert_eq!(present(&h), after, "{what}: {chord} changes the document once");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter that commits a field of a floating panel's window, and Escape that cancels one, are the
|
||||
/// field's: with an object selected and the Selection tool, Enter didn't also open the Move dialog
|
||||
/// (#4803).
|
||||
|
||||
@@ -1267,15 +1267,6 @@ pub(crate) fn whole_steps(range: std::ops::RangeInclusive<f64>) -> ChannelRule {
|
||||
rule
|
||||
}
|
||||
|
||||
/// An opacity stored as an f32 fraction (0 to 1), as the percent an Opacity field shows: the whole percent when it
|
||||
/// stores as the same f32, so that an arrow key steps on from it, and the exact percent otherwise. 51 % stores as
|
||||
/// 0.51f32, which reads back as 50.999999 %; an Up press from there would step to 51 % again.
|
||||
pub(crate) fn shown_percent(fraction: f32) -> f64 {
|
||||
let percent = f64::from(fraction) * 100.0;
|
||||
let whole = percent.round();
|
||||
if (whole / 100.0) as f32 == fraction { whole } else { percent }
|
||||
}
|
||||
|
||||
/// A section of a panel or dialog under its heading in label text: the reference app's section headings are regular
|
||||
/// weight, not bold.
|
||||
pub(crate) fn section<'a>(title: impl Into<Label>) -> Section<'a> {
|
||||
|
||||
@@ -452,9 +452,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let copy = craft::ui::runtime::pointer::frame(ui.ctx()).mods.alt;
|
||||
let pass = RefCell::new(Pass::default());
|
||||
let footer = RefCell::new(None);
|
||||
let shown_target = stroke::target_key(&stroke::edit_target(app, ui.ctx()));
|
||||
let shared: &VectorcraftApp = app;
|
||||
let cx = RowCx {
|
||||
app: shared,
|
||||
shown_target,
|
||||
node: node.as_deref(),
|
||||
new_art: &new_art,
|
||||
mix,
|
||||
@@ -751,6 +753,7 @@ struct Pass {
|
||||
/// What a row reads to build itself.
|
||||
struct RowCx<'a> {
|
||||
app: &'a VectorcraftApp,
|
||||
shown_target: u64,
|
||||
node: Option<&'a Node>,
|
||||
new_art: &'a Appearance,
|
||||
mix: Option<&'a Mixed>,
|
||||
@@ -860,10 +863,12 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> {
|
||||
}
|
||||
if let Some(st) = stroke_layer {
|
||||
let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) };
|
||||
let field =
|
||||
if new_art { row_weight(cx.app, Some(st.width), &cx.shown_target) } else { row_weight(cx.app, Some(st.width), &(cx.shown_target, i)) };
|
||||
let pass = cx.pass;
|
||||
row = row.trailing_field(row_weight(cx.app, Some(st.width)), move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))));
|
||||
row = row.trailing_field(field, move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))));
|
||||
} else {
|
||||
row = row.trailing_space(row_weight(cx.app, None));
|
||||
row = row.trailing_space(row_weight(cx.app, None, &()));
|
||||
}
|
||||
let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) };
|
||||
let pass = cx.pass;
|
||||
@@ -894,8 +899,8 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch {
|
||||
/// The weight field of a stroke row, or the room it takes in a fill row: the Stroke panel's field as a small control,
|
||||
/// as the row's swatch is, without the presets list (a step still stops at each preset), so the row's label shows
|
||||
/// whole in the narrowest group.
|
||||
fn row_weight(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
|
||||
stroke::steps_weight(app, weight).size(ControlSize::Sm)
|
||||
fn row_weight(app: &VectorcraftApp, weight: Option<f64>, target: &impl egui::AsIdSalt) -> NumberField<'static> {
|
||||
stroke::steps_weight(app, weight, target).size(ControlSize::Sm)
|
||||
}
|
||||
|
||||
/// A stroke row's notes after the weight: its brush and "Dashed".
|
||||
|
||||
@@ -20,7 +20,6 @@ use craft::ui::form::{Field, FieldGroup};
|
||||
use craft::ui::form::{SliderField, SliderFieldLayout};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::pickers::Select;
|
||||
use craft::ui::runtime::focus::{self, FocusTarget};
|
||||
use craft::ui::text::NumberField;
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
@@ -97,81 +96,13 @@ fn percent_slider(app: &mut VectorcraftApp, ui: &mut Ui, target: &EditTarget, sl
|
||||
let PercentSlider { label, key, range } = slider;
|
||||
Field::new(label).enabled(on).show(ui, |ui, _| {
|
||||
let shown = value.unwrap_or(0.0).clamp(*range.start(), *range.end());
|
||||
// Until the craft-libs pin includes storytold/craft-libs#5024 (`SliderField::edit_target`),
|
||||
// which then replaces this: when the edit target changes, the slider field gets a new id salt
|
||||
// only if its number field held focus in the last pass or holds it now, so an unfinished
|
||||
// value is dropped and never committed to the new target. Otherwise its id stays the same,
|
||||
// including during a drag. When the id changes, the focus moves to the new track if the old
|
||||
// track holds it now, or to the new number field if the old number field holds it now.
|
||||
// Other focus moves keep their destination.
|
||||
let held = ui.scope_id().with(("blend-percent-target", key));
|
||||
let mut kept = ui.ctx().data(|d| d.get_temp::<PercentField>(held)).unwrap_or_default();
|
||||
let previous_round = kept.round;
|
||||
if &kept.target != target {
|
||||
kept.target = target.clone();
|
||||
let ctx = ui.ctx();
|
||||
let track_focused = kept.track.is_some_and(|id| focus::has(ctx, id));
|
||||
let typed_focused = kept.typed.is_some_and(|id| focus::has(ctx, id));
|
||||
if kept.typed_focused || typed_focused {
|
||||
kept.round = kept.round.wrapping_add(1);
|
||||
kept.hand_off = if track_focused {
|
||||
Some("slider")
|
||||
} else if typed_focused {
|
||||
Some("field")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
}
|
||||
let out = SliderField::new(label, Bind::given(shown), range.clone())
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.unit("%")
|
||||
.step(1.0)
|
||||
.enabled(on)
|
||||
.id_salt(("blend-percent", key, kept.round))
|
||||
.edit_target(target)
|
||||
.show(ui);
|
||||
// The slider field's children are keyed "slider" (the track) and "field" (the number field
|
||||
// that takes typing). A measuring pass moves no focus, so the hand-off waits for a pass that
|
||||
// does.
|
||||
let typed = out.edit.response.id.with("field");
|
||||
// Disabled children have no focus stop. A request for one can outlive this target.
|
||||
if !on {
|
||||
kept.hand_off = None;
|
||||
} else if ui.input(|i| i.pointer.any_pressed()) {
|
||||
// Pointer focus moves settle at the end of the pass against the old ids. When these
|
||||
// children are replaced, a primary press on the visible part of the row, on this layer,
|
||||
// focuses the new child under it, even if released in this frame. Other button presses
|
||||
// cancel the hand-off. SliderField exposes only the whole response; response_of supplies
|
||||
// its child rects. A track press gets focus, but its drag cannot start on the replacement
|
||||
// this frame.
|
||||
let pressed = ui.input(|i| {
|
||||
i.events.iter().find_map(|event| match event {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
kept.hand_off = if previous_round != kept.round || kept.hand_off.is_some() {
|
||||
let on_row = |at: &egui::Pos2| {
|
||||
out.edit.response.rect.contains(*at) && ui.clip_rect().contains(*at) && ui.ctx().layer_id_at(*at) == Some(ui.layer_id())
|
||||
};
|
||||
pressed.filter(on_row).and_then(|at| {
|
||||
["field", "slider"].into_iter().find(|child| {
|
||||
craft::ui::contract::response_of(ui, out.edit.response.id.with(child)).is_some_and(|response| response.rect.contains(at))
|
||||
})
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
if let Some(child) = kept.hand_off
|
||||
&& focus::request(ui.ctx(), FocusTarget::Id(out.edit.response.id.with(child)))
|
||||
{
|
||||
kept.hand_off = None;
|
||||
}
|
||||
kept.typed_focused = focus::has(ui.ctx(), typed);
|
||||
kept.typed = Some(typed);
|
||||
kept.track = Some(out.edit.response.id.with("slider"));
|
||||
ui.ctx().data_mut(|d| d.insert_temp(held, kept));
|
||||
apply_edits(app, &out.edit, EditPath::Preview, |app, v, phase| {
|
||||
crate::panels::live_run(app, "Blend Options", "object.blend.options", json!({ key: *v }), phase);
|
||||
});
|
||||
@@ -194,19 +125,6 @@ struct TargetCache {
|
||||
objects: Arc<Vec<(NodeId, Option<NodeId>)>>,
|
||||
}
|
||||
|
||||
/// What the Ramp or Shift slider field keeps between passes: the [`EditTarget`] it last showed, the
|
||||
/// round its id salt is on, the ids of its number field and its track, whether its number field
|
||||
/// held focus in the last pass, and the child that still needs focus in a new round.
|
||||
#[derive(Clone, Default)]
|
||||
struct PercentField {
|
||||
target: EditTarget,
|
||||
round: u64,
|
||||
typed: Option<egui::Id>,
|
||||
track: Option<egui::Id>,
|
||||
typed_focused: bool,
|
||||
hand_off: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// The active document's uid and revert count, with each selected id and its resolved blend id.
|
||||
/// Resolution uses the same nearest-node finder and symbol-part guard as the Blend commands.
|
||||
/// Unchanged document revisions and selections reuse the resolved objects between passes.
|
||||
|
||||
@@ -1901,7 +1901,7 @@ fn opacity_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, tgt:
|
||||
// The row reads dim and takes no edit with nothing it can set.
|
||||
Stack::new().enabled(live).show(ui, |ui, _| {
|
||||
let rule = super::whole_steps(0.0..=100.0);
|
||||
let row = ChannelRow::new(tl!("Opacity").to_string(), Bind::given(super::shown_percent(o)), rule)
|
||||
let row = ChannelRow::new(tl!("Opacity").to_string(), Bind::given(f64::from(o) * 100.0), rule)
|
||||
.unit(ChannelUnit::Percent)
|
||||
.track(track.clone())
|
||||
.checker(true);
|
||||
|
||||
@@ -720,7 +720,7 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui);
|
||||
let shown = stop.map_or(100.0, |s| super::shown_percent(s.opacity));
|
||||
let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0);
|
||||
let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown)))
|
||||
.range(0.0..=100.0)
|
||||
.unit("%")
|
||||
|
||||
@@ -299,8 +299,7 @@ pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(split) = selected_split(app) else { return };
|
||||
// The canvas sets the divider to a ten-thousandth: a hundredth of a percent.
|
||||
let pct = (split * 10_000.0).round() / 100.0;
|
||||
// Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a value
|
||||
// typed for one object when another is selected. The pin bump replaces this with `edit_target`.
|
||||
// A value typed for one object and not yet committed is dropped when another is selected.
|
||||
let target = crate::panels::selection_target(app);
|
||||
let edit = Field::new(tl!("Divider"))
|
||||
.show(ui, |ui, _| {
|
||||
@@ -308,7 +307,7 @@ pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.step(1.0)
|
||||
.unit("%")
|
||||
.id_salt(("divider", &target))
|
||||
.edit_target(&target)
|
||||
.show(ui)
|
||||
.edit
|
||||
})
|
||||
|
||||
@@ -166,10 +166,8 @@ fn slider_row(ui: &mut Ui, params: &mut Value, data: &RowsData, spec: Slider, en
|
||||
.enabled(enabled)
|
||||
.show(ui, |ui, _| {
|
||||
let mut field = SliderField::new(label, Bind::given(value), range.clone()).layout(SliderFieldLayout::Inline).step(1.0).enabled(enabled);
|
||||
// Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a
|
||||
// value typed for one object when another is selected. The pin bump replaces this with `edit_target`.
|
||||
if let Some(target) = &data.target {
|
||||
field = field.id_salt((key, target));
|
||||
field = field.edit_target(target);
|
||||
}
|
||||
if let Some(unit) = unit {
|
||||
field = field.unit(unit);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// PLAN: import paths of craft_ui / craft_draw items are assumed from the crates' own module layout (craft_draw is
|
||||
// not yet a dependency of ui-egui; its owner adds it to Cargo.toml).
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
mod profile_picker;
|
||||
@@ -32,7 +33,9 @@ use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows};
|
||||
use egui::{Rect, Response, Ui, pos2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, StrokeAlign, StrokeLayer, Unit, WidthProfile};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, NodeId, StrokeAlign, StrokeLayer, Unit, WidthProfile,
|
||||
};
|
||||
use vectorcraft_engine::inspect::StrokeMixed;
|
||||
use vectorcraft_tools::PaintDefaults;
|
||||
|
||||
@@ -50,6 +53,15 @@ const ARROWHEAD_ASPECT: (u16, u16) = (2, 1);
|
||||
/// The key of [`StrokePanel::brushed`]: (document uid, revision, active Appearance row).
|
||||
type BrushedKey = (u64, u64, Option<usize>);
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FieldGesture {
|
||||
held: Option<(EditTarget, EditTarget)>,
|
||||
serial: u64,
|
||||
}
|
||||
|
||||
/// Global Edit members in propagation order, with the transforms that place each member.
|
||||
type GlobalEditTarget = Option<Vec<(NodeId, [u64; 6])>>;
|
||||
|
||||
/// What the Stroke panel remembers between frames; `UiState::stroke_panel` holds it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct StrokePanel {
|
||||
@@ -63,6 +75,10 @@ pub(crate) struct StrokePanel {
|
||||
pub brushed: Option<(BrushedKey, Option<bool>)>,
|
||||
/// The running gesture of a Stroke panel select.
|
||||
pub select_gesture: Option<SelectGesture>,
|
||||
/// The editor gesture's starting target and targeting state.
|
||||
editor_gesture: FieldGesture,
|
||||
/// The arrow scale gesture's starting target and targeting state.
|
||||
scale_gesture: FieldGesture,
|
||||
}
|
||||
|
||||
/// The stroke a weight edit goes to.
|
||||
@@ -394,22 +410,125 @@ static BLANK_WEIGHT_STOPS: [f64; 2] = [0.25, 0.5];
|
||||
/// scrubbing by its label, blank when mixed. A plain step stops at each preset (0.52 pt goes down to 0.5 pt, not to
|
||||
/// 0 pt); Shift or Page steps the grid by ten.
|
||||
// PLAN: the sheet names `NumberField<'static, f64>`; `NumberField::length` takes `Option<f64>`.
|
||||
pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
|
||||
let field = steps_weight(app, weight);
|
||||
pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option<f64>, target: &EditTarget) -> NumberField<'static> {
|
||||
let field = steps_weight(app, weight, target);
|
||||
match weight_ladder(app) {
|
||||
Some(l) => field.presets(&l.rows),
|
||||
None => field,
|
||||
}
|
||||
}
|
||||
|
||||
/// The document edit state and session destination before a preview.
|
||||
/// A field drops its unfinished value when either changes.
|
||||
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
|
||||
pub(crate) struct Target {
|
||||
/// The document.
|
||||
doc: u64,
|
||||
/// How many times File > Revert replaced the document's content.
|
||||
reverts: u64,
|
||||
/// The revision of the document that the next preview builds on.
|
||||
revision: u64,
|
||||
/// The pre-preview new-art paint state.
|
||||
new_art: u64,
|
||||
/// Whether new art uses a basic appearance.
|
||||
new_art_basic: bool,
|
||||
/// The selected objects and subjects, in targeting order.
|
||||
objects: Vec<NodeId>,
|
||||
subjects: Vec<NodeId>,
|
||||
/// The active appearance row.
|
||||
row: Option<usize>,
|
||||
/// The selected object inside a dynamic symbol instance: its instance and path through the symbol's art.
|
||||
symbol_part: Option<(NodeId, Vec<u32>)>,
|
||||
/// Whether the Live Paint Bucket's stroke is edited.
|
||||
bucket: bool,
|
||||
/// The type object and characters the Type tool has selected.
|
||||
characters: Option<(NodeId, usize, usize)>,
|
||||
/// The frame ids in thread order when the Type tool has selected the whole story.
|
||||
story: Option<Vec<NodeId>>,
|
||||
/// The members and placement transforms used to propagate Global Edit changes.
|
||||
global_edit: GlobalEditTarget,
|
||||
/// Distinguishes a canceled gesture from a replacement with the same starting content.
|
||||
gesture: u64,
|
||||
}
|
||||
|
||||
/// The edit target of the Stroke panel's fields, `None` without a document.
|
||||
pub(crate) type EditTarget = Option<Target>;
|
||||
|
||||
/// The [`EditTarget`] of the active document.
|
||||
pub(crate) fn edit_target(app: &VectorcraftApp, _ctx: &egui::Context) -> EditTarget {
|
||||
let st = app.session.active()?;
|
||||
Some(Target {
|
||||
doc: st.uid,
|
||||
reverts: st.reverts,
|
||||
revision: st.interaction.as_ref().map_or(st.revision, |it| it.revision),
|
||||
new_art: if may_edit_new_art(app) {
|
||||
paint_digest(vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session))
|
||||
} else {
|
||||
vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session).stroke_width.to_bits()
|
||||
},
|
||||
new_art_basic: app.session.prefs.new_art_basic,
|
||||
objects: st.selection.objects.clone(),
|
||||
subjects: st.selection.subjects().to_vec(),
|
||||
row: app.session.appearance_item(),
|
||||
symbol_part: st.selection.symbol_part.as_ref().map(|part| (part.instance, part.path.clone())),
|
||||
bucket: app.session.tool_paints(true),
|
||||
characters: character::text_editing(app),
|
||||
story: character::text_story(app),
|
||||
global_edit: st.global_edit.as_ref().map(|ge| ge.members.iter().map(|(id, xf)| (*id, xf.as_coeffs().map(f64::to_bits))).collect()),
|
||||
gesture: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn target_key(target: &EditTarget) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
target.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Whether the fields can edit the new-art paint. A selected path the Stroke panel edits directly
|
||||
/// (not a guide, a clipping path or a Live Paint part) is always a target, so with one selected
|
||||
/// the fields edit objects and the target skips formatting the new-art paint.
|
||||
fn may_edit_new_art(app: &VectorcraftApp) -> bool {
|
||||
use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint};
|
||||
let Some(st) = app.session.active() else { return true };
|
||||
if app.session.tool_paints(true) {
|
||||
return true;
|
||||
}
|
||||
let d = &st.doc;
|
||||
let edited_path = |id: NodeId| {
|
||||
d.node(id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, clipping: false, .. }) && !n.is_ruler_guide())
|
||||
&& d.parent_of(id).and_then(|p| d.node(p)).is_none_or(|p| !is_live_paint(p) && p.name.as_deref() != Some(SOURCES_NAME))
|
||||
};
|
||||
!st.selection.objects.iter().any(|id| edited_path(*id))
|
||||
}
|
||||
|
||||
fn paint_digest(paint: &impl std::fmt::Debug) -> u64 {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
struct HashSink(DefaultHasher);
|
||||
impl std::fmt::Write for HashSink {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
self.0.write(s.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let mut sink = HashSink(DefaultHasher::new());
|
||||
let _ = write!(sink, "{paint:?}");
|
||||
sink.0.finish()
|
||||
}
|
||||
|
||||
/// [`weight_number`] without the presets list: a plain step still stops at each preset.
|
||||
pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
|
||||
pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option<f64>, target: &impl egui::AsIdSalt) -> NumberField<'static> {
|
||||
let unit = app.session.stroke_unit();
|
||||
let lengths =
|
||||
crate::fields::bare_points(LengthUnits::new(UnitKind::Points, shown_kind(unit), 72.0), app.session.prefs.numbers_without_units_are_points);
|
||||
let ladder = weight_ladder(app);
|
||||
let field =
|
||||
NumberField::length(tl!("Weight"), Bind::given(weight), lengths).range(0.0..=1000.0).step_arrows(StepArrows::Leading).scrub_by_label();
|
||||
let field = NumberField::length(tl!("Weight"), Bind::given(weight), lengths)
|
||||
.range(0.0..=1000.0)
|
||||
.step_arrows(StepArrows::Leading)
|
||||
.scrub_by_label()
|
||||
.edit_target(target);
|
||||
// The stepper steps the number the field shows; the ladders are in points.
|
||||
let in_points = move |stops: &'static [f64], blank: bool| {
|
||||
let step = crate::fields::stops_stepper(1.0, stops, move |pt| unit.format(pt));
|
||||
@@ -452,8 +571,15 @@ pub(crate) fn apply_weight(app: &mut VectorcraftApp, out: &NumberOutput, target:
|
||||
|
||||
/// The weight field in a row labelled `label` with the side label `side`: the field response and the output of
|
||||
/// the number field when the row's body ran.
|
||||
fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: SideLabel, weight: Option<f64>) -> Inner<Response, NumberOutput> {
|
||||
Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight).show(ui))
|
||||
fn weight_row(
|
||||
app: &VectorcraftApp,
|
||||
ui: &mut Ui,
|
||||
label: &'static str,
|
||||
side: SideLabel,
|
||||
weight: Option<f64>,
|
||||
target: &EditTarget,
|
||||
) -> Inner<Response, NumberOutput> {
|
||||
Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight, target).show(ui))
|
||||
}
|
||||
|
||||
/// The weight field whose link side label (`label`: the Control bar's "Stroke:", the Properties panel's "Stroke")
|
||||
@@ -461,7 +587,8 @@ fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: Side
|
||||
/// Weight: the label beside the Stroke chip says which paint it is the weight of.
|
||||
pub(crate) fn link_field(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, weight: Option<f64>) {
|
||||
let side = SideLabel::new().scrub(true).link().role(FieldLabelRole::Describes).tooltip(TooltipSpec::new(tl!("Stroke options")));
|
||||
let field = weight_row(app, ui, label, side, weight);
|
||||
let target = edit_target(app, ui.ctx());
|
||||
let field = weight_row(app, ui, label, side, weight, &target);
|
||||
let open_id = field.output.id.with("stroke_popover_open");
|
||||
let mut open = ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
|
||||
if let Some(out) = field.inner {
|
||||
@@ -492,30 +619,66 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps a group's starting key while its own gesture runs in the same targeting state.
|
||||
fn gesture_target(gesture: &mut FieldGesture, target: EditTarget) -> EditTarget {
|
||||
let changed = gesture.held.as_ref().is_some_and(|(_, produced)| produced != &target);
|
||||
if changed {
|
||||
gesture.held = None;
|
||||
gesture.serial = gesture.serial.wrapping_add(1);
|
||||
}
|
||||
let mut target = gesture.held.as_ref().map_or(target, |(target, _)| target.clone());
|
||||
if let Some(target) = &mut target {
|
||||
target.gesture = gesture.serial;
|
||||
}
|
||||
target
|
||||
}
|
||||
|
||||
/// Keeps the starting target and the content produced after the component's edits are applied.
|
||||
fn remember_gesture<T>(gesture: &mut FieldGesture, target: &EditTarget, events: &craft::behavior::EditEvents<T>, produced: EditTarget) {
|
||||
for event in events.iter() {
|
||||
match event {
|
||||
EditEvent::Begin { .. } => gesture.held = Some((target.clone(), produced.clone())),
|
||||
EditEvent::Commit { .. } | EditEvent::Cancel { .. } => gesture.held = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some((_, last)) = &mut gesture.held {
|
||||
*last = produced;
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of [`show`].
|
||||
fn rows(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let st = current_stroke(app);
|
||||
let mixed = stroke_mixed(app, ui.ctx());
|
||||
let weight = shown_weight(app, st.as_ref(), &mixed);
|
||||
if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight).inner {
|
||||
let mut target = edit_target(app, ui.ctx());
|
||||
if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight, &target).inner {
|
||||
apply_weight(app, &out, WeightTarget::Shown);
|
||||
target = edit_target(app, ui.ctx());
|
||||
}
|
||||
if app.ui.stroke_panel.hide_options {
|
||||
app.ui.stroke_panel.editor_gesture.held = None;
|
||||
app.ui.stroke_panel.scale_gesture.held = None;
|
||||
return;
|
||||
}
|
||||
let style = style_of(st.as_ref());
|
||||
let editor_target = gesture_target(&mut app.ui.stroke_panel.editor_gesture, target.clone());
|
||||
let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone()))
|
||||
.sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN)
|
||||
.closed(mixed.can_align)
|
||||
.caps_on_closed(true)
|
||||
.mixed(&mixed_of(&mixed))
|
||||
.host_labels(true);
|
||||
.host_labels(true)
|
||||
.edit_target(&editor_target);
|
||||
let output = editor.show(ui);
|
||||
if let (Some(new), Some(field)) = (output.events.landed(), output.field) {
|
||||
apply_style(app, &style, new.clone(), field);
|
||||
target = edit_target(app, ui.ctx());
|
||||
}
|
||||
remember_gesture(&mut app.ui.stroke_panel.editor_gesture, &editor_target, &output.events, target.clone());
|
||||
Divider::horizontal().show(ui);
|
||||
arrow_rows(app, ui, st.as_ref());
|
||||
arrow_rows(app, ui, st.as_ref(), target);
|
||||
Divider::horizontal().show(ui);
|
||||
Field::new(tl!("Profile")).show(ui, |ui, _| {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
@@ -525,8 +688,11 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment.
|
||||
fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
|
||||
/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment. `target`
|
||||
/// is the current edit target used to track scale gestures.
|
||||
fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>, target: EditTarget) {
|
||||
let scale_target = gesture_target(&mut app.ui.stroke_panel.scale_gesture, target.clone());
|
||||
let mut updated = false;
|
||||
let custom: Vec<Arrowhead> = app.session.arrowheads.heads().iter().cloned().map(Arrowhead::Custom).collect();
|
||||
let entries: Vec<Entry<Option<Arrowhead>>> = std::iter::once(None)
|
||||
.chain(Arrowhead::ALL.iter().cloned().map(Some))
|
||||
@@ -551,10 +717,12 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
|
||||
let out = if listed { select } else { select.unlisted_label(unlisted_arrow_name(head.as_ref())) }.show(ui);
|
||||
// A custom head goes with its art, as document.inspect reports it.
|
||||
apply_select(app, key, &out, |app, a| set(app, json!({ key: a })));
|
||||
updated |= out.events.iter().next().is_some();
|
||||
}
|
||||
let swap = IconButton::new(IconId::new("arrow-left-right")).label(tl!("Swap start and end arrowheads")).enabled(st.is_some()).show(ui);
|
||||
if swap.clicked() {
|
||||
app.run("stroke.setAdvanced", json!({"swapArrows": true})).ok();
|
||||
updated = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -568,6 +736,7 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
|
||||
.mode(LinkMode::Equal)
|
||||
.unit_kind(UnitKind::Percent)
|
||||
.enabled(has_head)
|
||||
.edit_target(&scale_target)
|
||||
.show(ui)
|
||||
})
|
||||
.inner;
|
||||
@@ -576,6 +745,13 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
|
||||
}
|
||||
if let Some([a, b]) = out.as_ref().and_then(|out| out.edit.events.landed()).map(|p| (*p).map(|m| m.same().copied().flatten())) {
|
||||
app.run("stroke.setAdvanced", json!({"arrowScale": [a.unwrap_or(scale.0), b.unwrap_or(scale.1)]})).ok();
|
||||
updated = true;
|
||||
}
|
||||
if let Some(out) = &out {
|
||||
let produced = if updated { edit_target(app, ui.ctx()) } else { target };
|
||||
remember_gesture(&mut app.ui.stroke_panel.scale_gesture, &scale_target, &out.edit.events, produced);
|
||||
} else {
|
||||
app.ui.stroke_panel.scale_gesture.held = None;
|
||||
}
|
||||
let aligns: Vec<Entry<ArrowAlign>> = ARROW_ALIGN.iter().map(|(v, _, icon, tip)| Entry::new(*v, *tip).icon(IconId::new(icon))).collect();
|
||||
let out = Field::new(tl!("Align"))
|
||||
@@ -957,6 +1133,9 @@ fn apply_profile_action(app: &mut VectorcraftApp, action: ProfileAction) {
|
||||
ProfileAction::Reset => {
|
||||
crate::dialogs::confirm::ask(app, tl!("Do you want to reset profiles?"), "", "stroke.widthProfile.reset", json!({}));
|
||||
}
|
||||
ProfileAction::Move { name, to } => {
|
||||
crate::menus::invoke(app, "stroke.widthProfile.move", json!({"name": name, "to": to}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1018,6 +1197,15 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
#[test]
|
||||
fn paint_digest_tracks_stroke_width() {
|
||||
let paint = PaintDefaults::default();
|
||||
let mut changed = paint.clone();
|
||||
assert_eq!(paint_digest(&paint), paint_digest(&changed));
|
||||
changed.stroke_width += 1.0;
|
||||
assert_ne!(paint_digest(&paint), paint_digest(&changed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_an_extended_dash_keeps_other_stroke_options_and_is_undoable() {
|
||||
use vectorcraft_engine::Session;
|
||||
@@ -1039,6 +1227,41 @@ mod tests {
|
||||
assert_eq!(current_stroke(&app).unwrap(), after);
|
||||
}
|
||||
|
||||
/// A field group's running gesture keeps the target it began with while its own edits change the stroke, and
|
||||
/// takes the current target again once the gesture ends or the selection changes.
|
||||
#[test]
|
||||
fn a_gesture_keeps_its_starting_target_until_it_ends() {
|
||||
let (mut app, path) = profiled_line(None);
|
||||
let other = app.run("shape.line", json!({"x1": 10, "y1": 80, "x2": 90, "y2": 80})).unwrap();
|
||||
app.run("select.set", json!({"ids": [path["id"]]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let shown = |target: &EditTarget| format!("{target:?}");
|
||||
let event = |e: EditEvent<f64>| craft::behavior::EditEvents::from(e);
|
||||
let id = GestureId::new(1);
|
||||
let mut gesture = FieldGesture::default();
|
||||
|
||||
let start = edit_target(&app, &ctx);
|
||||
remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(10.0), std::sync::Arc::from("Miter"), None)), start.clone());
|
||||
app.run("stroke.set", json!({"miterLimit": 22})).unwrap();
|
||||
let fresh = edit_target(&app, &ctx);
|
||||
assert_ne!(shown(&fresh), shown(&start), "the gesture's own edit changes the stroke's target");
|
||||
remember_gesture(&mut gesture, &start, &craft::behavior::EditEvents::<f64>::new(), fresh.clone());
|
||||
let held = gesture_target(&mut gesture, fresh.clone());
|
||||
assert_eq!(shown(&held), shown(&start), "the running gesture keeps its starting target");
|
||||
|
||||
remember_gesture(&mut gesture, &held, &event(EditEvent::commit(id, Mixed::Same(10.0), 22.0)), fresh.clone());
|
||||
let fresh = edit_target(&app, &ctx);
|
||||
assert_eq!(shown(&gesture_target(&mut gesture, fresh)), shown(&edit_target(&app, &ctx)), "a commit ends it");
|
||||
|
||||
let start = edit_target(&app, &ctx);
|
||||
remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(22.0), std::sync::Arc::from("Miter"), None)), start.clone());
|
||||
app.run("select.set", json!({"ids": [other["id"]]})).unwrap();
|
||||
let fresh = edit_target(&app, &ctx);
|
||||
let now = gesture_target(&mut gesture, fresh);
|
||||
assert_ne!(shown(&now), shown(&start), "another selection ends the held target");
|
||||
assert!(gesture.held.is_none());
|
||||
}
|
||||
|
||||
/// The Profile and arrowhead selects name a current value that is none of their choices on the closed face, and
|
||||
/// the open list keeps only the choices.
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The Variable Width Profile dropdown (`ProfileSelect`): a combo box whose popup shows the width
|
||||
//! profile list with built-in labels and captionless user-added thumbnails, a right-click Delete
|
||||
//! Profile on saved rows, and a footer bar with Add to Profiles…, Delete Profile, and Reset
|
||||
//! Profiles.
|
||||
//! profile list with built-in labels and captionless user-added thumbnails, rows that drag to a new
|
||||
//! place below Uniform, a right-click Delete Profile on saved rows, and a footer bar with Add to
|
||||
//! Profiles…, Delete Profile, and Reset Profiles.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
@@ -9,14 +9,14 @@ use std::collections::HashSet;
|
||||
use craft::behavior::nav::{StepResult, ValueAxes, ValueSteps};
|
||||
use craft::behavior::overlay::MinWidth;
|
||||
use craft::behavior::{
|
||||
CancelReason, ColumnKey, ColumnWidth, DisplayOrder, GesturePhase, HitLevel, HitPriority, IconId, ItemSource, Metrics, NavMove, PartKey, Proposal,
|
||||
Selection, Sense, TypeAhead, WheelPhase, wheel_step,
|
||||
CancelReason, ColumnKey, ColumnWidth, DisplayOrder, EditEvent, GesturePhase, HitLevel, HitPriority, IconId, ItemSource, Metrics, NavMove,
|
||||
PartKey, Proposal, Selection, Sense, TypeAhead, WheelPhase, wheel_step,
|
||||
};
|
||||
use craft::ui::contract::overlay::OverlayFit;
|
||||
use craft::ui::contract::{
|
||||
Access, ActivateOn, Bind, BindMut, CollectionEvent, ColumnSpec, Common, Component, Cx, Edit as _, EditResponse, Focus as _, HoverLead, Input,
|
||||
LeadOnOpen, LeadSource, MeasureCx, Numeric, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Popup, PopupHandle,
|
||||
Props, Role, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _,
|
||||
Props, ReorderRule, Role, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _,
|
||||
};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize};
|
||||
@@ -46,6 +46,10 @@ const SAVED_THUMB_INSET: f32 = 2.0;
|
||||
const FACE: PartKey = PartKey::new("face");
|
||||
const POPUP: &str = "list";
|
||||
const LIST_SALT: &str = "items";
|
||||
/// The id of the Uniform row, the list's first.
|
||||
const UNIFORM_ID: &str = "uniform";
|
||||
/// The rows above the first one a drag can move or land before: Uniform and the divider under it.
|
||||
const PINNED_ROWS: usize = 2;
|
||||
|
||||
/// Row identity in the profile list, keeping the non-interactive divider distinct from any
|
||||
/// user-saved profile name (even a literal `"__profile_separator__"`).
|
||||
@@ -62,6 +66,11 @@ impl ProfileRowKey {
|
||||
ProfileRowKey::Separator => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every profile row but Uniform's, which stays first, drags to a new place.
|
||||
fn is_reorderable(&self) -> bool {
|
||||
self.profile().is_some_and(|id| id != UNIFORM_ID)
|
||||
}
|
||||
}
|
||||
|
||||
/// One silhouette sample `(t, left_offset, right_offset)` returned by `stroke::silhouette`.
|
||||
@@ -150,12 +159,17 @@ pub(super) struct ProfileActions {
|
||||
pub can_reset: bool,
|
||||
}
|
||||
|
||||
/// A management action requested by the dropdown footer or a saved row's menu.
|
||||
/// A management action requested by the dropdown footer, a saved row's menu or a row drag.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ProfileAction {
|
||||
Add,
|
||||
Delete(Option<String>),
|
||||
Reset,
|
||||
/// Move the profile `name` to place `to` among the rows after Uniform (`stroke.widthProfile.move`).
|
||||
Move {
|
||||
name: String,
|
||||
to: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// Output of [`ProfileSelect`]: the underlying profile pick/preview edit and any management action.
|
||||
@@ -530,6 +544,14 @@ impl ProfileSelect {
|
||||
cx.memory::<PickerMemory>().previewed = false;
|
||||
popup.close(cx);
|
||||
}
|
||||
// `to` counts the rows left once the dragged one is out, Uniform and the divider among them.
|
||||
CollectionEvent::Reorder(EditEvent::Set { after, .. } | EditEvent::Commit { after, .. }) => {
|
||||
if after.key.is_reorderable()
|
||||
&& let (Some(name), Some(to)) = (after.key.profile(), after.to.checked_sub(PINNED_ROWS))
|
||||
{
|
||||
self.action = Some(ProfileAction::Move { name: name.to_owned(), to });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -574,6 +596,12 @@ fn show_popup_body(
|
||||
.activate(ActivateOn::Click)
|
||||
.lead_on_open(LeadOnOpen::First)
|
||||
.selection(Bind::given(view.selection.clone()));
|
||||
if rows.separator {
|
||||
list = list
|
||||
.can_drag(|key: &ProfileRowKey| key.is_reorderable())
|
||||
.reorder(ReorderRule::new())
|
||||
.accepts(|drag, _, insert| insert >= PINNED_ROWS && drag.keys.iter().all(ProfileRowKey::is_reorderable));
|
||||
}
|
||||
if let Some(key) = view.reveal {
|
||||
list = list.reveal(key.clone());
|
||||
}
|
||||
|
||||
@@ -634,7 +634,9 @@ fn a_secondary_press_on_ramp_while_selecting_another_blend_drops_its_draft_witho
|
||||
Event::PointerMoved(ramp),
|
||||
Event::PointerButton { pos: ramp, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
assert!(!p.focused_role("Ramp:", Role::SPIN_BUTTON), "a secondary press does not focus Ramp's number field");
|
||||
// The number field keeps the focus it had while the draft was typed: a new edit target drops the draft, not the
|
||||
// focus, and a secondary press moves neither.
|
||||
assert!(p.focused_role("Ramp:", Role::SPIN_BUTTON), "Ramp's number field keeps the focus");
|
||||
assert!(!p.focused_role("Ramp:", Role::SLIDER), "a secondary press does not focus Ramp's track");
|
||||
p.frame_with(vec![Event::PointerButton { pos: ramp, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
p.key(Key::Enter, Modifiers::NONE);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -443,6 +443,52 @@ fn dropdown_row_menu_deletes_saved_profiles_only() {
|
||||
assert!(panel.app().session.profile_entries().any(|e| e.id == "wave"), "the built-ins stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_rows_drag_to_a_new_place_below_uniform() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Modifiers, pos2};
|
||||
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
|
||||
session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
|
||||
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": "Mine"})).unwrap();
|
||||
let order = |panel: &mut crate::tests::panel_harness::Panel| panel.app().session.profile_entries().map(|e| e.id.to_owned()).collect::<Vec<_>>();
|
||||
|
||||
let app = crate::VectorcraftApp::new(session, Default::default());
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
|
||||
let open = |panel: &mut crate::tests::panel_harness::Panel| {
|
||||
if !panel.shows("Lens") {
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
}
|
||||
};
|
||||
|
||||
// Uniform's row does not drag, and nothing lands above it.
|
||||
open(&mut panel);
|
||||
let first = order(&mut panel);
|
||||
panel.drag("Uniform", "Wave", Modifiers::NONE);
|
||||
open(&mut panel);
|
||||
let uniform = panel.rect("Uniform");
|
||||
panel.drag_to("Wave", pos2(uniform.center().x, uniform.top() + 1.0), Modifiers::NONE);
|
||||
assert_eq!(order(&mut panel), first, "Uniform stays first");
|
||||
|
||||
// A saved row dropped on the top edge of Lens's row goes right after Uniform.
|
||||
open(&mut panel);
|
||||
let lens = panel.rect("Lens");
|
||||
panel.drag_to("Mine", pos2(lens.center().x, lens.top() + 1.0), Modifiers::NONE);
|
||||
let moved = order(&mut panel);
|
||||
assert_eq!(&moved[..3], ["uniform", "Mine", "lens"], "{moved:?}");
|
||||
assert_eq!(panel.app().session.prefs.width_profile_order.first().map(String::as_str), Some("Mine"));
|
||||
|
||||
// A built-in moves past the saved profile the same way.
|
||||
open(&mut panel);
|
||||
let mine = panel.rect("Mine");
|
||||
panel.drag_to("Wave", pos2(mine.center().x, mine.top() + 1.0), Modifiers::NONE);
|
||||
let moved = order(&mut panel);
|
||||
assert_eq!(&moved[..3], ["uniform", "wave", "Mine"], "{moved:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_expands_into_available_vertical_space() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
@@ -101,6 +101,11 @@ pub struct Services {
|
||||
/// Open a file (or a folder) in the system's default app for it (desktop: Edit Original, Show
|
||||
/// Package). Without it (the web) those answer with an error.
|
||||
pub open_file: Option<RevealFn>,
|
||||
/// Open a `file:` URL of a file the app wrote (View PDF after Saving, Save for Web's and SVG
|
||||
/// Options' Show in Browser) in the web browser (desktop). The UI runtime's link
|
||||
/// opener opens only `http`, `https` and `mailto` links. Without it the URL goes to egui like
|
||||
/// any other link.
|
||||
pub open_file_url: Option<RevealFn>,
|
||||
/// Open a file in PhotoCraft where it is installed (desktop: Edit Original of a raster image
|
||||
/// with Preferences › File Handling › Use System Defaults for Edit Original off); `Ok(false)`
|
||||
/// when it isn't. Without it Edit Original uses `open_file`.
|
||||
|
||||
@@ -77,8 +77,9 @@ fn samples_show_the_text_in_the_family_or_a_generic_sample() {
|
||||
|
||||
/// A face with no hinting instructions draws a sample in a context the app has adopted, as the font list and the
|
||||
/// font picker draw each family's sample in its own face (a document face of the context): a Hebrew letter that is a
|
||||
/// bar 20 by 700 thousandths of an em, whose blue zones the automatic hinter of skrifa 0.44 never finishes measuring.
|
||||
/// The face is served to the fixture's context only, so the font database other tests read does not change. The
|
||||
/// bar 20 by 700 thousandths of an em. The context hints text in both themes, so the sample goes through skrifa's
|
||||
/// automatic hinter, whose long blue-zone search for such a letter ends with the vendored skrifa 0.44 from craft-libs
|
||||
/// (the `skrifa` entry in the workspace's `[patch.crates-io]`). The face is served to the fixture's context only, so the font database other tests read does not change. The
|
||||
/// sample is one rasterized glyph from that face. It is drawn on a thread of its own, and the test fails when it has
|
||||
/// not ended after 300 s.
|
||||
#[test]
|
||||
@@ -145,9 +146,9 @@ fn a_face_without_hinting_instructions_draws_its_sample() {
|
||||
let (texts, [hinting, light_hinting, dark_hinting], fixture_has_glyph, nonempty_glyph) =
|
||||
rx.recv_timeout(std::time::Duration::from_secs(300)).unwrap_or_else(|e| panic!("drawing the sample: {e}"));
|
||||
assert!(texts.iter().any(|t| t == "\u{5d1}"), "the sample is the letter, in the face: {texts:?}");
|
||||
assert!(!hinting, "a context the app adopts draws text without hinting");
|
||||
assert!(!light_hinting, "the light theme draws text without hinting");
|
||||
assert!(!dark_hinting, "the dark theme draws text without hinting");
|
||||
assert!(hinting, "a context the app adopts hints text");
|
||||
assert!(light_hinting, "the light theme hints text");
|
||||
assert!(dark_hinting, "the dark theme hints text");
|
||||
assert!(fixture_has_glyph, "the sample's face maps U+05D1");
|
||||
assert!(nonempty_glyph, "the sample is one rasterized glyph for U+05D1");
|
||||
}
|
||||
|
||||
@@ -593,3 +593,327 @@ fn acknowledging_import_loss_does_not_overwrite_the_source_with_another_drawing(
|
||||
assert!(after_switch == saved, "drawing B must never overwrite A's file");
|
||||
assert!(after_original != saved, "approval in drawing A must still save A");
|
||||
}
|
||||
|
||||
/// Puts `bytes` at `path` as a new file, as a cloud-sync folder puts a file back after uploading
|
||||
/// it: the file gets a new inode and new change and modification times.
|
||||
fn put_back(path: &str, bytes: &[u8]) {
|
||||
let next = format!("{path}.sync");
|
||||
std::fs::write(&next, bytes).unwrap();
|
||||
std::fs::rename(&next, path).unwrap();
|
||||
}
|
||||
|
||||
/// Once its baseline digest is recorded, Save writes without asking while the file holds the
|
||||
/// bytes the app last read or wrote (#10734), and asks once they differ, even at the same length.
|
||||
#[test]
|
||||
fn save_asks_about_a_changed_file_only_when_its_bytes_changed() {
|
||||
let d = dir("same-bytes");
|
||||
let path = d.join("a.vectorcraft").to_string_lossy().to_string();
|
||||
let mut writer = app();
|
||||
writer.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
rect(&mut writer);
|
||||
writer.run("file.saveAs", json!({"path": path})).unwrap();
|
||||
crate::background::wait_all(&mut writer);
|
||||
let mut app = app();
|
||||
io::open_path(&mut app, &path).unwrap();
|
||||
assert!(io::save::wait_for_contents(&app).is_some(), "the opened file's baseline is recorded before sync");
|
||||
|
||||
let saved = |app: &VectorcraftApp| vectorcraft_format::load(&std::fs::read(&path).unwrap()).unwrap().node_count() == objects(app);
|
||||
// File › Save, once the file has been compared: did it ask?
|
||||
let save = |app: &mut VectorcraftApp| {
|
||||
rect(app);
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
io::save::wait_for_checks(app);
|
||||
crate::background::wait_all(app);
|
||||
if !app.any_dialog_open() {
|
||||
assert!(io::save::wait_for_contents(app).is_some(), "the written file's baseline is recorded before sync");
|
||||
}
|
||||
app.any_dialog_open()
|
||||
};
|
||||
|
||||
// Read from the file: the same bytes put back.
|
||||
put_back(&path, &std::fs::read(&path).unwrap());
|
||||
assert!(!save(&mut app));
|
||||
assert!(saved(&app));
|
||||
|
||||
// Written by that save: the same bytes put back.
|
||||
put_back(&path, &std::fs::read(&path).unwrap());
|
||||
assert!(!save(&mut app));
|
||||
assert!(saved(&app));
|
||||
|
||||
// Other bytes of the same length.
|
||||
let mut other = std::fs::read(&path).unwrap();
|
||||
let last = other.last_mut().unwrap();
|
||||
*last ^= 0xff;
|
||||
put_back(&path, &other);
|
||||
assert!(save(&mut app), "asks whether to replace the file");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), other, "nothing is written before the answer");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// Opens a file saved by another app, with the file then put back (with other bytes of the same
|
||||
/// length unless `same`), and one more object: File › Save compares the file before it writes.
|
||||
fn opened_then_put_back(tag: &str, same: bool) -> (std::path::PathBuf, String, VectorcraftApp) {
|
||||
let d = dir(tag);
|
||||
let path = d.join("a.vectorcraft").to_string_lossy().to_string();
|
||||
let mut writer = app();
|
||||
writer.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
rect(&mut writer);
|
||||
writer.run("file.saveAs", json!({"path": path})).unwrap();
|
||||
crate::background::wait_all(&mut writer);
|
||||
let mut app = app();
|
||||
io::open_path(&mut app, &path).unwrap();
|
||||
assert!(io::save::wait_for_contents(&app).is_some(), "the opened file's baseline is recorded");
|
||||
let mut other = std::fs::read(&path).unwrap();
|
||||
if !same {
|
||||
let last = other.last_mut().unwrap();
|
||||
*last ^= 0xff;
|
||||
}
|
||||
put_back(&path, &other);
|
||||
rect(&mut app);
|
||||
(d, path, app)
|
||||
}
|
||||
|
||||
/// A comparison that answers after the document took another file does not ask about the old one.
|
||||
#[test]
|
||||
fn a_comparison_for_a_file_the_document_no_longer_uses_asks_nothing() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-retargeted", false);
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
let other = d.join("b.vectorcraft").to_string_lossy().to_string();
|
||||
app.session.doc_mut().unwrap().path = Some(other.clone());
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
let asked = app.any_dialog_open();
|
||||
let pending = io::save::checks_pending(&app);
|
||||
let after = std::fs::read(&path).unwrap();
|
||||
// The dropped save freed the flow: the next File › Save writes the new file.
|
||||
let next = app.run("file.save", json!({}));
|
||||
crate::background::wait_all(&mut app);
|
||||
let wrote_new = std::path::Path::new(&other).exists();
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(next.is_ok(), "the next save starts: {next:?}");
|
||||
assert!(wrote_new, "the next save writes the document's new file");
|
||||
assert!(!asked, "no changed-on-disk question about a file the document no longer uses");
|
||||
assert!(!pending, "the comparison is dropped");
|
||||
assert_eq!(after, before, "the old file is not written");
|
||||
}
|
||||
|
||||
/// A comparison that answers while a dialog is open over another document waits for it to close,
|
||||
/// so the save does not activate its own document under the dialog.
|
||||
#[test]
|
||||
fn a_comparison_waits_while_a_dialog_is_open_over_another_document() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-under-dialog", true);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let prompt = craft::ui::dialog::StandardPrompt::changed_on_disk("other");
|
||||
app.dialogs().unwrap().with(|h| h.open(prompt));
|
||||
io::save::wait_for_answers(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
let active = app.session.active_index();
|
||||
let pending = io::save::checks_pending(&app);
|
||||
let unwritten = std::fs::read(&path).unwrap() == before;
|
||||
// Once the dialog closes, the save goes on and writes the file.
|
||||
answer_top(&mut app, false);
|
||||
io::save::pump(&mut app, &ctx);
|
||||
crate::background::wait_all(&mut app);
|
||||
let written = std::fs::read(&path).unwrap() != before;
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert_eq!(active, Some(1), "the document under the dialog stays active");
|
||||
assert!(!pending, "no frames are asked for while the save waits for the dialog");
|
||||
assert!(unwritten, "nothing is written while the dialog is open");
|
||||
assert!(written, "the save finishes once the dialog closes");
|
||||
}
|
||||
|
||||
/// A context whose first frames have run, so it asks for no more frames of its own.
|
||||
fn settled() -> egui::Context {
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..10 {
|
||||
if !ctx.has_requested_repaint() {
|
||||
break;
|
||||
}
|
||||
ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear();
|
||||
}
|
||||
assert!(!ctx.has_requested_repaint(), "the context settled");
|
||||
ctx
|
||||
}
|
||||
|
||||
/// A save that waited for a dialog asks for a frame in the pass whose UI closes the dialog, since
|
||||
/// its pump ran earlier in that pass and an idle app draws no other frame.
|
||||
#[test]
|
||||
fn a_comparison_held_by_a_dialog_asks_for_a_frame_once_the_dialog_closes() {
|
||||
let (d, _path, mut app) = opened_then_put_back("compare-wake", true);
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let prompt = craft::ui::dialog::StandardPrompt::changed_on_disk("other");
|
||||
app.dialogs().unwrap().with(|h| h.open(prompt));
|
||||
io::save::wait_for_answers(&mut app);
|
||||
io::save::pump(&mut app, &egui::Context::default());
|
||||
let open = settled();
|
||||
io::save::after_ui(&mut app, &open);
|
||||
let while_open = open.has_requested_repaint();
|
||||
// The dialog's own pump, which runs after the save's, takes its answer.
|
||||
let id = open_dialogs(&app).pop().map(|d| d.id).expect("a dialog is open");
|
||||
let window = app.ui_ctx.clone().expect("a window context");
|
||||
app.dialogs().unwrap().with(|h| {
|
||||
assert!(h.cancel_by_id(&window, id));
|
||||
let _ = h.take_by_id::<craft::ui::dialog::StandardPrompt>(id);
|
||||
});
|
||||
let closed = settled();
|
||||
io::save::after_ui(&mut app, &closed);
|
||||
let after_close = closed.has_requested_repaint();
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(!while_open, "no frame is asked for while the dialog is open");
|
||||
assert!(after_close, "a frame is asked for once the dialog has closed");
|
||||
}
|
||||
|
||||
/// A comparison that answers while a drag goes on in another document waits for the drag to end,
|
||||
/// so making the save's document active does not cancel the drag.
|
||||
#[test]
|
||||
fn a_comparison_waits_while_a_drag_goes_on_in_another_document() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-under-drag", true);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.begin_interaction("drag").unwrap();
|
||||
io::save::wait_for_answers(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
let active = app.session.active_index();
|
||||
let dragging = app.session.active().is_some_and(|d| d.interaction.is_some());
|
||||
let unwritten = std::fs::read(&path).unwrap() == before;
|
||||
// Once the drag ends, the save goes on and writes the file.
|
||||
app.session.commit_interaction().unwrap();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
crate::background::wait_all(&mut app);
|
||||
let written = std::fs::read(&path).unwrap() != before;
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert_eq!(active, Some(1), "the document with the drag stays active");
|
||||
assert!(dragging, "the drag is not canceled");
|
||||
assert!(unwritten, "nothing is written while the drag goes on");
|
||||
assert!(written, "the save finishes once the drag ends");
|
||||
}
|
||||
|
||||
/// A comparison's thread asks for a frame once it answers: a save started from the UI comes after
|
||||
/// that frame's repaint decision, and an idle app draws no other frame.
|
||||
#[test]
|
||||
fn a_comparison_asks_for_a_frame_once_it_answers() {
|
||||
let (d, _path, mut app) = opened_then_put_back("compare-answer-wake", true);
|
||||
let ctx = settled();
|
||||
app.ui_ctx = Some(ctx.clone());
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
io::save::wait_for_answers(&mut app);
|
||||
let woke = ctx.has_requested_repaint();
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(woke, "the answer asks for a frame");
|
||||
}
|
||||
|
||||
/// A comparison that answers while a dialog previews a change in the save's own document waits for
|
||||
/// the preview to end, so the file never holds a change the dialog's Cancel takes back.
|
||||
#[test]
|
||||
fn a_comparison_waits_while_its_own_document_shows_a_preview() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-own-preview", true);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.begin_interaction("Move").unwrap();
|
||||
io::save::wait_for_answers(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
crate::background::wait_all(&mut app);
|
||||
let unwritten = std::fs::read(&path).unwrap() == before;
|
||||
let previewing = app.session.active().is_some_and(|d| d.interaction.is_some());
|
||||
// Once the preview is canceled, the save goes on and writes the file.
|
||||
app.session.cancel_interaction().unwrap();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
crate::background::wait_all(&mut app);
|
||||
let written = std::fs::read(&path).unwrap() != before;
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(previewing, "the preview stays open");
|
||||
assert!(unwritten, "nothing is written while the preview is shown");
|
||||
assert!(written, "the save finishes once the preview ends");
|
||||
}
|
||||
|
||||
/// A save with an explicit path that ends while a comparison is pending drops the comparison: its
|
||||
/// answer would ask about the file with no save left to apply the answer.
|
||||
#[test]
|
||||
fn a_save_that_ends_first_drops_the_pending_comparison() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-overtaken", true);
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.run("file.saveAs", json!({"path": path})).unwrap();
|
||||
crate::background::wait_all(&mut app);
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
let asked = app.any_dialog_open();
|
||||
let pending = io::save::checks_pending(&app);
|
||||
rect(&mut app);
|
||||
let next = app.run("file.save", json!({}));
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(!asked, "no changed-on-disk question without a save to answer it");
|
||||
assert!(!pending, "the comparison is dropped");
|
||||
assert!(next.is_ok(), "the next save starts: {next:?}");
|
||||
}
|
||||
|
||||
/// A comparison that answers while a script runs waits for the script to end, since writing
|
||||
/// activates the save's document and the engine refuses that while a script runs.
|
||||
#[test]
|
||||
fn a_comparison_waits_while_a_script_runs() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-under-script", true);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.session.execute("script.run", &json!({"source": "1", "name": "t.js"})).unwrap();
|
||||
io::save::wait_for_answers(&mut app);
|
||||
let ctx = egui::Context::default();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
let running = app.session.script_running();
|
||||
let pending = io::save::checks_pending(&app);
|
||||
let unwritten = std::fs::read(&path).unwrap() == before;
|
||||
// Once the script ends, the save goes on and writes the file.
|
||||
for _ in 0..10_000 {
|
||||
if app.session.script_pump().is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ended = !app.session.script_running();
|
||||
io::save::pump(&mut app, &ctx);
|
||||
crate::background::wait_all(&mut app);
|
||||
let written = std::fs::read(&path).unwrap() != before;
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(running, "the script runs while the comparison answers");
|
||||
assert!(!pending, "no frames are asked for while the save waits for the script");
|
||||
assert!(unwritten, "nothing is written while the script runs");
|
||||
assert!(ended, "the script ended");
|
||||
assert!(written, "the save finishes once the script ends");
|
||||
}
|
||||
|
||||
/// Close with Save waits while the save compares the document's file, then closes the document
|
||||
/// once the save has written it.
|
||||
#[test]
|
||||
fn close_waits_while_its_save_compares_the_file() {
|
||||
let (d, path, mut app) = opened_then_put_back("compare-close", true);
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
let uid = app.session.active().unwrap().uid;
|
||||
assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile");
|
||||
crate::unsaved::saving_for_test(&mut app, uid);
|
||||
let ctx = egui::Context::default();
|
||||
crate::unsaved::pump(&mut app, &ctx);
|
||||
let waiting = app.closing.is_some();
|
||||
let open = app.session.documents().len();
|
||||
io::save::wait_for_checks(&mut app);
|
||||
crate::background::wait_all(&mut app);
|
||||
crate::unsaved::pump(&mut app, &ctx);
|
||||
let closed = app.session.documents().is_empty();
|
||||
let written = std::fs::read(&path).unwrap() != before;
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
assert!(waiting, "Close waits for the comparison");
|
||||
assert_eq!(open, 1, "the document stays open while its file is compared");
|
||||
assert!(written, "the save writes the file");
|
||||
assert!(closed, "the document closes once it is saved");
|
||||
}
|
||||
@@ -507,7 +507,8 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m
|
||||
// Tools without options answer with an error; a double click on one does nothing more.
|
||||
app.run("tool.options", json!({ "tool": tool })).ok();
|
||||
}
|
||||
if out.edit_toolbar.as_ref().is_some_and(|button| button.clicked()) {
|
||||
// A measuring pass of the rail reports the same click as the pass that shows it, and the command toggles the drawer.
|
||||
if out.edit_toolbar.as_ref().is_some_and(|button| button.clicked()) && !craft::ui::runtime::measure::active(ui.ctx()) {
|
||||
let params = match &owner {
|
||||
Owner::Toolbar(id) => json!({ "toolbar": bar_of(&app.ui, *id).map(|bar| bar.name.clone()) }),
|
||||
_ => json!({}),
|
||||
|
||||
@@ -24,17 +24,6 @@ pub fn ui_fonts() -> UiFonts<'static> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns font hinting off for all text `ctx` draws, in both themes. With hinting on, egui hints a TrueType face that
|
||||
/// has no hinting instructions (no `fpgm`, no `prep` and no glyph instructions) with skrifa 0.44's automatic hinter,
|
||||
/// whose blue-zone search never ends for some glyphs, such as a tall narrow Hebrew letter, so the font list stops
|
||||
/// responding when a row draws such a face. The font list and the samples get their faces through craft-libs, which
|
||||
/// sets no hinting option per face, so the switch covers every face of the context. Hinting stays off until the
|
||||
/// skrifa blue-zone exit (storytold/craft-libs#5222) is in the build; the craft-libs pin that brings it removes this
|
||||
/// function and its call.
|
||||
pub(crate) fn hinting_off(ctx: &egui::Context) {
|
||||
ctx.all_styles_mut(|style| style.visuals.text_options.font_hinting = false);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FontSelection {
|
||||
language: Lang,
|
||||
|
||||
@@ -200,13 +200,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
/// The save of document `uid` that a Save answer started and that waited on a later frame: once the
|
||||
/// document is saved it closes and the operation goes on; while its dialog or write is still running
|
||||
/// it waits; given up (its Save As cancelled) the document stays open and the operation stops.
|
||||
/// document is saved it closes and the operation goes on; while its dialog, the comparison of its
|
||||
/// file or its write is still running it waits; given up (its Save As cancelled) the document stays
|
||||
/// open and the operation stops.
|
||||
fn finish_save(app: &mut VectorcraftApp, uid: u64) {
|
||||
let doc = app.session.documents().iter().find(|d| d.uid == uid);
|
||||
let saved = doc.is_none_or(|d| !d.is_dirty());
|
||||
let asking = app.dialogs().is_some_and(|d| d.with(|h| !h.open_dialogs().is_empty()));
|
||||
if !saved && (app.file_dialog_open() || asking || app.background.busy_with(uid)) {
|
||||
if !saved && (app.file_dialog_open() || asking || app.background.busy_with(uid) || io::save::checking(app, uid)) {
|
||||
return;
|
||||
}
|
||||
let title = doc.map(|d| d.title()).unwrap_or_default();
|
||||
@@ -291,6 +292,15 @@ pub(crate) fn ready_for_test(app: &mut VectorcraftApp) -> egui::Context {
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Close of document `uid` answered with Save, and the save already started on its own (as the OK
|
||||
/// of the import-loss question starts it): the operation waits for that save.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn saving_for_test(app: &mut VectorcraftApp, uid: u64) {
|
||||
let mut guard = CloseGuard::new(Then::Close.scope(), vec![uid]);
|
||||
let _ = guard.answer(CloseAnswer::Save);
|
||||
app.closing = Some(Closing { guard, front: None, then: Then::Close, saving: Some(uid) });
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+11
-3
@@ -9159,14 +9159,20 @@ The Profile list holds the built-in variable-width profiles (`uniform`, `lens`,
|
||||
right]`) and `current`, the selected stroke's profile (`"custom"` when it isn't listed).
|
||||
`stroke.widthProfile.add {name?}` saves the selected stroke's variable width (default name "Width Profile N"),
|
||||
`stroke.widthProfile.delete {name?}` removes a saved one (default: the selected stroke's; built-ins can't be deleted)
|
||||
and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` takes a built-in id or a saved name.
|
||||
and `stroke.widthProfile.reset` removes every saved one and puts the built-ins back in their first order.
|
||||
`stroke.widthProfile.move {name, to}` moves a built-in or saved profile, named by its id or label, to place `to` among
|
||||
the rows after Uniform (0 is right after Uniform); Uniform stays first, and a `to` past the last row is refused. The
|
||||
order is kept with the preferences, and a profile saved later goes to the end of the list. `stroke.set {profile}`
|
||||
takes a built-in id or a saved name.
|
||||
In the app, the footer of the Profile drop-down (in the Stroke panel, the Control bar and the Properties panel) runs
|
||||
the same three commands: Add to Profiles asks for a name first, Delete Profile removes the selected stroke's saved
|
||||
profile, and Reset Profiles asks for confirmation. Right-clicking a saved profile's row offers Delete Profile for it.
|
||||
profile, and Reset Profiles asks for confirmation. Right-clicking a saved profile's row offers Delete Profile for it,
|
||||
and dragging any row but Uniform's moves it.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"stroke.widthProfile.add","params":{"name":"Ribbon"}}}
|
||||
{"name":"run_command","arguments":{"command":"stroke.set","params":{"ids":[9],"profile":"Ribbon"}}}
|
||||
{"name":"run_command","arguments":{"command":"stroke.widthProfile.move","params":{"name":"Ribbon","to":0}}}
|
||||
```
|
||||
|
||||
## Arrowheads
|
||||
@@ -13067,7 +13073,9 @@ and dots and stroked at the lineweight without the linetype; a pattern hatch wit
|
||||
than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping and dash steps, or past the drawing's budget of
|
||||
2,000,000 dashes or 200,000,000 clipping steps, as its boundary),
|
||||
text and multiline text point type, named blocks symbols
|
||||
(one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface
|
||||
(one per look when their art takes colour "by block"; one per insert scale when they draw dashes or wide polylines,
|
||||
which scale with the insert; and one per depth or set of ancestors when the nesting limit or a block placing one of its
|
||||
own ancestors changes the art they draw), anonymous blocks such as dimensions groups. 3D faces, polyface
|
||||
meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the
|
||||
lines of its visible edges (closed when every edge is visible), and a polygon mesh one path of its M and N lines
|
||||
(smoothed meshes draw their surface's vertices). Indexed colours
|
||||
|
||||
@@ -79,7 +79,7 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer`
|
||||
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
|
||||
| `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) |
|
||||
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on the nightly's commit |
|
||||
|
||||
The signer reads the policy from `nightly-signer`, so a candidate whose CI built the tests once
|
||||
(`build`, `lint` and `test 1/5` to `test 5/5`) is admitted only after `nightly-signer` advances to
|
||||
@@ -97,9 +97,12 @@ a main commit with this policy. Candidates whose CI ran six shards (`cache warm`
|
||||
from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
|
||||
credentials; only the shared callee's sign jobs bind the `release` environment, which must admit
|
||||
`nightly-signer` alongside `release` before the first dispatch.
|
||||
- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally
|
||||
off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on
|
||||
`nightly-signer`. No schedule is registered until activation is reviewed.
|
||||
- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It forwards only
|
||||
a first-attempt scheduled producer to `nightly-sign.yml` on `nightly-signer`, after the
|
||||
SonarCloud check on the producer's commit has completed.
|
||||
- `.github/workflows/sonarcloud.yml`: analyzes main only at the commit a nightly builds. It starts
|
||||
when the producer starts and fails when main has moved past the producer's commit. Pull requests
|
||||
are analyzed on every push as before.
|
||||
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
|
||||
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable
|
||||
commit**; the defining workflow SHA and tooling input must match.
|
||||
@@ -117,8 +120,9 @@ a main commit with this policy. Candidates whose CI ran six shards (`cache warm`
|
||||
- A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml`
|
||||
calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml`
|
||||
is `release.yml`.
|
||||
- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a
|
||||
`refs/heads/nightly-signer` request.
|
||||
- `nightly-dispatch.yml` keeps its exact context guard, a `workflow_run`-only trigger and a
|
||||
`refs/heads/nightly-signer` request, and sends that request only after the SonarCloud check on
|
||||
the producer's commit has completed.
|
||||
|
||||
## The app side of a Nightly build
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DXF and DWG import draw a block's dashes and wide polylines at each insert's scale, with one symbol per scale for such blocks, and keep a block's art apart where the nesting limit or a block placing one of its own ancestors changes what it draws (#10930). Headline numbers unchanged.
|
||||
@@ -2,10 +2,15 @@
|
||||
"""Local regression checks for VectorCraft nightly workflow and signing-policy contracts."""
|
||||
import copy
|
||||
from decimal import Decimal
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
|
||||
@@ -907,5 +912,92 @@ class NightlyDispatchTransport(unittest.TestCase):
|
||||
self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source)
|
||||
self.assertNotIn("'ref': 'release'", self.source)
|
||||
|
||||
|
||||
SONAR_SOURCE = "c" * 40
|
||||
|
||||
|
||||
def dispatch_script():
|
||||
"""The dispatch job's inline Python, as the runner's `shell: python` step receives it."""
|
||||
source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text()
|
||||
block = source.split(" run: |\n", 1)[1]
|
||||
return textwrap.dedent(block)
|
||||
|
||||
|
||||
class FakeGitHub:
|
||||
"""Answers the dispatch script's API reads from scripted poll results and records every request."""
|
||||
|
||||
def __init__(self, polls, run=None):
|
||||
self.polls = list(polls)
|
||||
self.run = run
|
||||
self.requests = []
|
||||
self.now = 0.0
|
||||
|
||||
def open(self, request, timeout):
|
||||
self.requests.append((request.get_method(), request.full_url))
|
||||
if request.get_method() == "POST":
|
||||
payload = b""
|
||||
status = 204
|
||||
elif "/check-runs?" in request.full_url:
|
||||
done = self.polls.pop(0) if self.polls else False
|
||||
rows = [{"head_sha": SONAR_SOURCE, "status": "completed" if done else "in_progress"}]
|
||||
payload, status = json.dumps({"check_runs": rows}).encode(), 200
|
||||
else:
|
||||
runs = [self.run] if self.run else []
|
||||
payload, status = json.dumps({"workflow_runs": runs}).encode(), 200
|
||||
response = io.BytesIO(payload)
|
||||
response.status = status
|
||||
return response
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
|
||||
def run_dispatch(github):
|
||||
producer = {"head_repository": {"full_name": "storytold/vectorcraft"}, "path": ".github/workflows/nightly.yml",
|
||||
"head_branch": "main", "status": "completed", "conclusion": "success", "event": "schedule",
|
||||
"id": 7, "run_attempt": 1, "head_sha": SONAR_SOURCE}
|
||||
event = {"action": "completed", "repository": {"full_name": "storytold/vectorcraft"}, "workflow_run": producer}
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "event.json"
|
||||
path.write_text(json.dumps(event))
|
||||
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_EVENT_NAME": "workflow_run",
|
||||
"GITHUB_EVENT_PATH": str(path), "GH_TOKEN": "token"}
|
||||
with mock.patch.dict(os.environ, env), \
|
||||
mock.patch("urllib.request.build_opener", return_value=github), \
|
||||
mock.patch("time.monotonic", side_effect=lambda: github.now), \
|
||||
mock.patch("time.sleep", side_effect=github.sleep), \
|
||||
mock.patch("builtins.print"):
|
||||
exec(compile(dispatch_script(), "nightly-dispatch.yml", "exec"), {})
|
||||
|
||||
|
||||
class NightlyDispatchWaitsForSonar(unittest.TestCase):
|
||||
"""The signer is dispatched only after the producer commit's SonarCloud check completes."""
|
||||
|
||||
def posts(self, github):
|
||||
return [url for method, url in github.requests if method == "POST"]
|
||||
|
||||
def test_dispatch_waits_for_the_completed_check_of_the_producer_commit(self):
|
||||
github = FakeGitHub([False, False, True])
|
||||
run_dispatch(github)
|
||||
checks = [url for method, url in github.requests if "/check-runs?" in url]
|
||||
self.assertEqual(len(checks), 3)
|
||||
self.assertTrue(all("/commits/" + SONAR_SOURCE + "/" in url and "app_id=12526" in url for url in checks))
|
||||
self.assertEqual(len(self.posts(github)), 1)
|
||||
self.assertEqual(github.requests[-1][0], "POST", "the dispatch comes after the last check read")
|
||||
|
||||
def test_a_sonar_run_that_ended_without_a_check_stops_the_dispatch(self):
|
||||
github = FakeGitHub([], run={"id": 9, "status": "completed", "conclusion": "failure"})
|
||||
with self.assertRaisesRegex(RuntimeError, "ended without an analysis check"):
|
||||
run_dispatch(github)
|
||||
self.assertEqual(self.posts(github), [])
|
||||
self.assertLessEqual(github.now, 21 * 60, "a finished run does not wait for the whole deadline")
|
||||
|
||||
def test_no_analysis_by_the_deadline_stops_the_dispatch(self):
|
||||
github = FakeGitHub([])
|
||||
with self.assertRaisesRegex(RuntimeError, "in time"):
|
||||
run_dispatch(github)
|
||||
self.assertEqual(self.posts(github), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
+197
-8
@@ -6,7 +6,13 @@
|
||||
//! every unit a build compiled or found fresh. The builds of `cargo xtask ci archive` append those
|
||||
//! messages to the file, so the saved entry holds this build and no older builds of updated
|
||||
//! dependencies. Without `CRAFT_CACHE_UNITS` the commands run as they always have.
|
||||
//!
|
||||
//! The trim keeps an unrecorded unit that was built during the job, so the integration tests'
|
||||
//! builds, which stay out of the record, would put their executables in the entry. `ci archive`
|
||||
//! collects those units with [`run_unrecorded`] and deletes them with [`drop_units`] once the
|
||||
//! archives are written.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -31,24 +37,115 @@ pub fn run(cmd: Command, what: &str) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// [`run`] with the record in `file`.
|
||||
fn run_recorded(mut cmd: Command, what: &str, file: &Path) -> Result<(), String> {
|
||||
// After `--` the flag would go to rustc or the test binaries instead of cargo.
|
||||
if cmd.get_args().any(|a| a == "--") {
|
||||
return Err(format!("{what}: a recorded build takes no `--` arguments"));
|
||||
}
|
||||
fn run_recorded(cmd: Command, what: &str, file: &Path) -> Result<(), String> {
|
||||
no_separator(&cmd, what)?;
|
||||
let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
run_routed(cmd, what, &mut record, &format!("recording the build units in {}", file.display()))
|
||||
}
|
||||
|
||||
/// Runs `cmd`, a cargo build shown as `what`, which must exit successfully, with Cargo's messages
|
||||
/// going to `messages` (`doing` names that in an error) and every other stdout line to stdout.
|
||||
fn run_routed(mut cmd: Command, what: &str, messages: &mut impl Write, doing: &str) -> Result<(), String> {
|
||||
no_separator(&cmd, what)?;
|
||||
cmd.args(MESSAGE_FORMAT);
|
||||
eprintln!("$ {what} {}", MESSAGE_FORMAT.join(" "));
|
||||
let mut record = OpenOptions::new().create(true).append(true).open(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
|
||||
let routed = match child.stdout.take() {
|
||||
Some(stdout) => route(BufReader::new(stdout), &mut record, &mut std::io::stdout().lock()),
|
||||
Some(stdout) => route(BufReader::new(stdout), messages, &mut std::io::stdout().lock()),
|
||||
None => Err(std::io::Error::other("no stdout pipe")),
|
||||
};
|
||||
let status = child.wait().map_err(|e| format!("{what}: {e}"))?;
|
||||
routed.map_err(|e| format!("{what}: recording the build units in {}: {e}", file.display()))?;
|
||||
routed.map_err(|e| format!("{what}: {doing}: {e}"))?;
|
||||
if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) }
|
||||
}
|
||||
|
||||
/// After `--` the message-format flag would go to rustc or the test binaries instead of cargo.
|
||||
fn no_separator(cmd: &Command, what: &str) -> Result<(), String> {
|
||||
if cmd.get_args().any(|a| a == "--") { Err(format!("{what}: a recorded build takes no `--` arguments")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Runs `cmd`, a cargo build shown as `what` whose units stay out of the record, which must exit
|
||||
/// successfully. When this leg saves the cache, it returns the unit directories of the integration
|
||||
/// test executables the build compiled or found fresh, for [`drop_units`]; otherwise none.
|
||||
pub fn run_unrecorded(cmd: Command, what: &str) -> Result<Vec<PathBuf>, String> {
|
||||
if file().is_none() {
|
||||
crate::run(cmd, what)?;
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut messages = Vec::new();
|
||||
run_routed(cmd, what, &mut messages, "reading the build messages")?;
|
||||
Ok(integration_units(&messages))
|
||||
}
|
||||
|
||||
/// The unit directory of each integration test executable that Cargo's `messages` name, or the
|
||||
/// executable itself when it lies in no unit directory.
|
||||
fn integration_units(messages: &[u8]) -> Vec<PathBuf> {
|
||||
let mut units = Vec::new();
|
||||
for line in messages.split(|b| *b == b'\n') {
|
||||
let Ok(m) = serde_json::from_slice::<serde_json::Value>(line) else { continue };
|
||||
let integration = m["reason"] == "compiler-artifact"
|
||||
&& m["profile"]["test"] == true
|
||||
&& m["target"]["kind"].as_array().is_some_and(|k| k.iter().any(|k| k == "test"));
|
||||
let Some(exe) = m["executable"].as_str().filter(|_| integration) else { continue };
|
||||
let exe = Path::new(exe);
|
||||
let unit = unit_of(exe).unwrap_or(exe).to_path_buf();
|
||||
if !units.contains(&unit) {
|
||||
units.push(unit);
|
||||
}
|
||||
}
|
||||
units
|
||||
}
|
||||
|
||||
/// The `<profile>/build/<package>/<hash>` directory `path` lies in, as actions/cache-trim finds it.
|
||||
fn unit_of(path: &Path) -> Option<&Path> {
|
||||
path.ancestors().find(|d| {
|
||||
let hash = d.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.len() == 16 && n.bytes().all(|b| b.is_ascii_hexdigit()));
|
||||
hash && d.parent().and_then(Path::parent).and_then(Path::file_name).is_some_and(|n| n == "build")
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes `units` ([`run_unrecorded`]) from the target directory before the cache is saved, except
|
||||
/// those the record names. Nothing later in the build job runs the integration tests' executables:
|
||||
/// the shards run them from their archives. A unit that cannot be deleted is named in a warning and
|
||||
/// stays in the entry.
|
||||
pub fn drop_units(units: &[PathBuf]) {
|
||||
if let Some(record) = file().filter(|_| !units.is_empty()) {
|
||||
drop_units_in(units, &record);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`drop_units`] with the record in `record`; returns how many units it deleted.
|
||||
fn drop_units_in(units: &[PathBuf], record: &Path) -> usize {
|
||||
let recorded = match std::fs::read_to_string(record) {
|
||||
Ok(text) => recorded_units(&text),
|
||||
Err(e) => {
|
||||
println!("::warning::ci archive: {}: {e}; the integration test executables stay in the cache entry", record.display());
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
let mut dropped = 0;
|
||||
for unit in units.iter().filter(|u| !recorded.contains(*u)) {
|
||||
let removed = if unit.is_dir() { std::fs::remove_dir_all(unit) } else { std::fs::remove_file(unit) };
|
||||
match removed {
|
||||
Ok(()) => dropped += 1,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => println!("::warning::ci archive: could not delete {}: {e}; it stays in the cache entry", unit.display()),
|
||||
}
|
||||
}
|
||||
eprintln!("ci archive: deleted {dropped} integration test units, which the cache entry does not keep");
|
||||
dropped
|
||||
}
|
||||
|
||||
/// The unit directories, or files outside one, that the record's messages name.
|
||||
fn recorded_units(record: &str) -> HashSet<PathBuf> {
|
||||
let mut units = HashSet::new();
|
||||
for m in record.lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()) {
|
||||
let named = m["filenames"].as_array().into_iter().flatten().chain([&m["executable"], &m["out_dir"]]);
|
||||
units.extend(named.filter_map(|p| p.as_str()).map(Path::new).map(|p| unit_of(p).unwrap_or(p).to_path_buf()));
|
||||
}
|
||||
units
|
||||
}
|
||||
|
||||
/// Records xtask's own units. `cargo xtask` builds xtask before xtask can record anything, and the
|
||||
/// trim deletes an unrecorded unit from the entry, so the next run would build xtask again. The
|
||||
/// build is fresh by now, so this only prints the messages.
|
||||
@@ -145,4 +242,96 @@ mod tests {
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A `compiler-artifact` message for a target of `kind`, built in the test profile or not.
|
||||
fn artifact(kind: &str, test: bool, executable: Option<&str>, filenames: &[&str]) -> String {
|
||||
serde_json::json!({
|
||||
"reason": "compiler-artifact",
|
||||
"target": { "kind": [kind], "name": "fixture" },
|
||||
"profile": { "test": test },
|
||||
"filenames": filenames,
|
||||
"executable": executable,
|
||||
"fresh": false,
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_integration_test_executables_are_collected() {
|
||||
let it = "/t/debug/build/fixture/0123456789abcdef/out/it-0123456789abcdef";
|
||||
let messages = [
|
||||
artifact("test", true, Some(it), &[it]),
|
||||
// The same unit found fresh by a later build.
|
||||
artifact("test", true, Some(it), &[it]),
|
||||
// The library's test harness: recorded by the unit tests' build, never dropped.
|
||||
artifact("lib", true, Some("/t/debug/build/fixture/fedcba9876543210/out/fixture-fedcba9876543210"), &[]),
|
||||
artifact("lib", false, None, &["/t/debug/build/fixture/1111111111111111/out/libfixture.rlib"]),
|
||||
// An executable outside a unit directory (Cargo's older `deps/` layout).
|
||||
artifact("test", true, Some("/t/debug/deps/other-2222222222222222"), &[]),
|
||||
"running 0 tests".into(),
|
||||
serde_json::json!({ "reason": "build-finished", "success": true }).to_string(),
|
||||
]
|
||||
.join("\n");
|
||||
assert_eq!(
|
||||
integration_units(messages.as_bytes()),
|
||||
[PathBuf::from("/t/debug/build/fixture/0123456789abcdef"), PathBuf::from("/t/debug/deps/other-2222222222222222")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_units_keeps_the_ones_the_record_names() {
|
||||
let dir = std::env::temp_dir().join(format!("xtask-cache-units-drop-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let unit = |hash: &str| dir.join("debug/build/fixture").join(hash);
|
||||
let (dropped, recorded, missing) = (unit("0123456789abcdef"), unit("fedcba9876543210"), unit("1111111111111111"));
|
||||
for u in [&dropped, &recorded] {
|
||||
std::fs::create_dir_all(u.join("out")).unwrap();
|
||||
std::fs::write(u.join("out/bin"), "x").unwrap();
|
||||
}
|
||||
let record = dir.join("units.jsonl");
|
||||
let named = recorded.join("out/bin");
|
||||
std::fs::write(&record, artifact("lib", true, named.to_str(), &[]) + "\n").unwrap();
|
||||
assert_eq!(drop_units_in(&[dropped.clone(), recorded.clone(), missing], &record), 1);
|
||||
assert!(!dropped.exists());
|
||||
assert!(named.exists());
|
||||
// Without a readable record nothing is deleted.
|
||||
assert_eq!(drop_units_in(std::slice::from_ref(&recorded), &dir.join("absent.jsonl")), 0);
|
||||
assert!(named.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_integration_test_build_is_dropped_and_the_record_kept() {
|
||||
let dir = std::env::temp_dir().join(format!("xtask-cache-units-it-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
std::fs::create_dir_all(dir.join("tests")).unwrap();
|
||||
std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"cache-unit-it\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[workspace]\n")
|
||||
.unwrap();
|
||||
std::fs::write(dir.join("src/lib.rs"), "pub fn one() -> u32 { 1 }\n#[test]\nfn unit() {}\n").unwrap();
|
||||
std::fs::write(dir.join("tests/it.rs"), "#[test]\nfn it() { assert_eq!(cache_unit_it::one(), 1); }\n").unwrap();
|
||||
let build = |args: &[&str]| {
|
||||
let mut c = crate::cargo();
|
||||
c.current_dir(&dir)
|
||||
.env("CARGO_TARGET_DIR", dir.join("target"))
|
||||
.env("CARGO_BUILD_BUILD_DIR", dir.join("target"))
|
||||
.env("CARGO_NET_OFFLINE", "true")
|
||||
.args(args);
|
||||
c
|
||||
};
|
||||
let record = dir.join("units.jsonl");
|
||||
run_recorded(build(&["test", "--lib", "--no-run"]), "cargo test --lib --no-run", &record).unwrap();
|
||||
let mut messages = Vec::new();
|
||||
run_routed(build(&["test", "--test", "*", "--no-run"]), "cargo test --test '*' --no-run", &mut messages, "reading").unwrap();
|
||||
let executable = |m: &serde_json::Value| m["executable"].as_str().map(PathBuf::from);
|
||||
let parsed: Vec<serde_json::Value> = messages.split(|b| *b == b'\n').filter_map(|l| serde_json::from_slice(l).ok()).collect();
|
||||
let it = parsed.iter().find(|m| m["target"]["name"] == "it").and_then(executable).unwrap();
|
||||
let record_text = std::fs::read_to_string(&record).unwrap();
|
||||
let harness = record_text.lines().map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap()).find_map(|m| executable(&m)).unwrap();
|
||||
assert!(it.is_file() && harness.is_file());
|
||||
assert_eq!(drop_units_in(&integration_units(&messages), &record), 1);
|
||||
assert!(!it.exists(), "{}", it.display());
|
||||
assert!(harness.is_file(), "{}", harness.display());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -470,8 +470,9 @@ fn cmd_ci_shard() -> Result<(), String> {
|
||||
///
|
||||
/// In a leg that saves the cache, the library and binary tests' builds record their units in
|
||||
/// `CRAFT_CACHE_UNITS` (xtask/src/cache_units.rs), xtask's own build included, and the
|
||||
/// integration tests' builds do not, so the saved entry holds every dependency and
|
||||
/// dev-dependency the tests build with and none of the integration tests' executables.
|
||||
/// integration tests' builds do not. The trim keeps an unrecorded unit built during the job, so
|
||||
/// once the archives are written this deletes the integration tests' executables, and the saved
|
||||
/// entry holds every dependency and dev-dependency the tests build with and none of them.
|
||||
fn cmd_ci_archive() -> Result<(), String> {
|
||||
let var = |key: &str| {
|
||||
std::env::var(key).ok().filter(|v| !v.is_empty()).ok_or_else(|| format!("ci archive: {key} is not set (the gate workflow sets it)"))
|
||||
@@ -484,9 +485,10 @@ fn cmd_ci_archive() -> Result<(), String> {
|
||||
cache_units::record_xtask()?;
|
||||
let checked = shards::run()?;
|
||||
let archived = archived_runs(&checked)?;
|
||||
let mut integration = Vec::new();
|
||||
for (units, r) in archive_builds(&checked) {
|
||||
let (c, what) = test_build(&r, units);
|
||||
if units { cache_units::run(c, &what)? } else { run(c, &what)? }
|
||||
if units { cache_units::run(c, &what)? } else { integration.extend(cache_units::run_unrecorded(c, &what)?) }
|
||||
}
|
||||
for (i, (shard, r)) in checked.iter().zip(archived).enumerate() {
|
||||
let file = dir.join((i + 1).to_string()).join(&name);
|
||||
@@ -505,6 +507,7 @@ fn cmd_ci_archive() -> Result<(), String> {
|
||||
let what = format!("cargo nextest archive {} ({}) --archive-file {}", r.targets.shown(), shards::names(&r.crates), file.display());
|
||||
run(c, &what)?;
|
||||
}
|
||||
cache_units::drop_units(&integration);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
const REV: &str = "bd7c9e342a33796c9b36b33763c5b63883a22b79";
|
||||
const REV: &str = "f9e5cecc9cf1b701b22f6f24a88719b14456323e";
|
||||
const PACKAGES: &[(&str, &str, &str)] = &[
|
||||
("craft-pdf", "0.1.0", REV),
|
||||
("krilla", "0.8.2", REV),
|
||||
|
||||
Reference in new issue
Block a user