Merge main into train/carry10596

This commit is contained in:
dotCooCoo committed 2026-12-05 15:07:54 -08:00
commit 7d1c186423
119 files changed
+13430 -586

No files matched your search

+14 -7
View File
@@ -44,17 +44,19 @@ jobs:
# The workspace crates also build without line tables. A panic still names its file and line.
dev-debug: "0"
# The `build (<os>)` job builds the tests once and writes one nextest archive per shard with
# that shard's test binaries (`cargo xtask ci archive`), then runs the doctests. Five test
# legs download their own archive and run it without building: shards 1 and 2 each run half
# of vectorcraft-ui-egui's tests, and shards 3 to 5 the tests of their own crates
# (xtask/src/shards.rs). The `lint (<os>)` leg runs the other `cargo xtask ci` steps beside
# them, with a dependency cache of its own. `gate (<os>)` passes when the build and every
# test leg that ran passed; `lint (<os>)` is a check of its own.
# that shard's test binaries (`cargo xtask ci archive`), then runs the doctests and the tests
# built without the bundled fonts (`cargo xtask ci after-archive`), whose second build of the
# workspace crates the build job's cache entry keeps. Five test legs download their own archive and
# run it without building: shards 1 and 2 each run half of vectorcraft-ui-egui's tests, and
# shards 3 to 5 the tests of their own crates (xtask/src/shards.rs). The `lint (<os>)` leg
# runs the other `cargo xtask ci` steps beside them, with a dependency cache of its own.
# `gate (<os>)` passes when the build and every test leg that ran passed; `lint (<os>)` is a
# check of its own.
test-shards: 5
shard-command: cargo xtask ci shard
archive-command: cargo xtask ci archive
shard-archives: true
after-archive-command: cargo xtask ci doctests
after-archive-command: cargo xtask ci after-archive
lint-command: cargo xtask ci checks
# A pull request runs only the test shards whose crates its changes reach: the crates that
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
@@ -80,6 +82,11 @@ jobs:
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
libgl1-mesa-dev
# `.rs` files that no workspace module reaches on purpose: fixture trees (the gate's default)
# and the example panel plug-in, a Cargo project of its own that builds for wasm32 only.
unreached-rs-allow: |
**/fixtures/**
crates/plugins/example-panel/**
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
+54 -12
View File
@@ -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.')
+30 -2
View File
@@ -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
+92 -91
View File
@@ -1256,7 +1256,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"egui",
]
@@ -1418,7 +1418,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"rayon",
]
@@ -1486,7 +1486,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"serde",
]
@@ -1536,7 +1536,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"gif",
]
@@ -1681,7 +1681,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"flate2",
]
@@ -1689,7 +1689,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"winsafe",
]
@@ -2470,7 +2470,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
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=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -3862,7 +3862,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"brotli 8.0.4",
"hayro-postscript",
@@ -3871,7 +3871,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3889,7 +3889,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3907,12 +3907,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4895,7 +4895,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -5052,7 +5052,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da#4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da"
source = "git+https://github.com/storytold/craft-libs?rev=bd7c9e342a33796c9b36b33763c5b63883a22b79#bd7c9e342a33796c9b36b33763c5b63883a22b79"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -9292,6 +9292,7 @@ dependencies = [
"rustix 1.1.6",
"serde",
"serde_json",
"sha2 0.10.9",
"toml",
"vectorcraft-apischema",
"vectorcraft-brush",
+42 -42
View File
@@ -10,62 +10,62 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
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" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# Digits typed in any script in numeric fields (`vectorcraft_doc::units`).
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
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" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# 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 = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
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" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -205,13 +205,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
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" }
# 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" }
+3 -2
View File
@@ -18,7 +18,7 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Scores and estimates unchanged.
## Headline numbers
@@ -98,7 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Simplified Chinese | `zh-hans` | partial (most messages translated, #2578; some remain untranslated) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus, dialogs, status and error messages (messages machine-assisted, review pending) |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -124,6 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-12-05: Window › Swatch Strip shows a None chip and the document's color swatches as a strip of chips that wraps to the panel's room: docked on the window's bottom edge it runs across in one line, and in a dock column or a narrow floating window it runs down. A click sets the fill and a right-click or Alt-click sets the stroke (#10951). A VectorCraft addition: headline numbers unchanged.
- 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged.
- 2026-12-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). Headline numbers unchanged.
+1 -1
View File
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "bd7c9e342a33796c9b36b33763c5b63883a22b79", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+117 -9
View File
@@ -1019,7 +1019,8 @@ mod portable {
/// What our last write put on the clipboard, for a read answered late ([`Unanswered::paste`]): a
/// paste does not take what this app copied. Whether the clipboard still holds a copy is
/// [`Clipboard::owns`](ClipboardBackend::owns).
/// [`Clipboard::owns`](ClipboardBackend::owns). A bitmap is known by its size alone, so another
/// app's bitmap of the same size counts as the Copy made here.
#[derive(Clone)]
enum Ours {
Text(String),
@@ -1204,7 +1205,10 @@ mod portable {
/// paste's bitmap read waits. Once it comes,
/// the same read is made again, since the clipboard may have changed hands meanwhile.
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
/// clipboard, read as `ours` was written (its text or its bitmap), holds what `ours` put
/// there; when that takes a read of its own, copied files are read before it, and before a
/// bitmap read the text as well. Otherwise
/// the clipboard is read as
/// [`Clipboard::read_now_or_later`] and the paste read it, the new answer standing in for
/// the read it answers: copied files, else
/// text, else the bitmap, and the bitmap when it is asked for and the text is blank or only
@@ -1220,21 +1224,49 @@ mod portable {
.unwrap_or_else(|why| Answer::failed(request, why))
};
// The late answer may come from an app that lost the clipboard while it was awaited.
let answer = fresh(self.request);
let held = match (&answer, ours) {
(Answer::Text(Ok(now)), Some(Ours::Text(t))) => now == t,
(Answer::Image(Ok(now)), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h),
let mut answer = Some(fresh(self.request));
// The Copy made here is read as it was written, whatever the late read was: a Copy's
// text read that answers late leaves a bitmap Copy with no text to compare.
let written = match ours {
Some(Ours::Text(_)) => Some(Request::Text),
Some(Ours::Image(..)) => Some(Request::Image),
None => None,
};
let mut check = None;
let mut text_first = None;
let mut files_read = false;
if let Some(written) = written.filter(|w| answer.as_ref().is_some_and(|a| a.request() != *w)) {
// Copied files are read first: a Copy made here writes none, and a read of the
// Copy's format that gets no answer leaves the worker busy for the files' read.
let files = answer.take_if(|a| a.request() == Request::Files).unwrap_or_else(|| fresh(Request::Files));
if let Some(f) = copied_file(files.files(), mimes) {
return Some(f);
}
files_read = true;
// The text is read before a bitmap check for the same reason: a bitmap read that
// gets no answer leaves the worker busy for the text's read.
if written == Request::Image && mimes.contains(&TEXT) && !answer.as_ref().is_some_and(|a| a.request() == Request::Text) {
text_first = Some(fresh(Request::Text));
}
check = Some(fresh(written));
}
let held = match (check.as_ref().or(answer.as_ref()), ours) {
(Some(Answer::Text(Ok(now))), Some(Ours::Text(t))) => now == t,
(Some(Answer::Image(Ok(now))), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h),
_ => false,
};
if held {
return None;
}
let mut answer = Some(answer);
let mut read = |request: Request| match answer.take_if(|a| a.request() == request) {
let mut read = |request: Request| match answer
.take_if(|a| a.request() == request)
.or_else(|| check.take_if(|a| a.request() == request))
.or_else(|| text_first.take_if(|a| a.request() == request))
{
Some(answer) => answer,
None => fresh(request),
};
if let Some(f) = copied_file(read(Request::Files).files(), mimes) {
if !files_read && let Some(f) = copied_file(read(Request::Files).files(), mimes) {
return Some(f);
}
let text = if mimes.contains(&TEXT) { read(Request::Text).text().ok().filter(|t| !t.is_empty()) } else { None };
@@ -2080,6 +2112,82 @@ mod portable {
assert!(paste_after_check(2).is_none());
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_paste_after_an_unanswered_text_read_finds_a_bitmap_copied_here() {
// A Copy reads the clipboard's text first; when that read gets no answer in its wait, the
// Copy's art goes out as a `width`×1 bitmap with no text (a placed photo too large for
// the SVG markup to go out as text). The paste then waits for the text read's answer.
let paste_after_copy = |width: usize, fill: u8| {
let (mut cb, release) = slow_owner(move |request| match request {
Request::Image => Answer::Image(Ok(arboard::ImageData { width, height: 1, bytes: Cow::Owned(vec![fill; width * 4]) })),
_ => Answer::failed(request, "none".into()),
});
assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err());
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the text read is kept for the paste");
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
drop(release);
paste.join().ok().flatten()
};
// The bitmap copied here: the paste takes the internal clipboard, not a picture of it.
assert!(paste_after_copy(2, 0).is_none());
// A bitmap is known by its size: another app's bitmap of the same size counts as the Copy.
assert!(paste_after_copy(2, 0xff).is_none());
// Another app's bitmap of another size is pasted.
let pasted = paste_after_copy(3, 0).expect("the other app's bitmap is pasted");
assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1))));
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_paste_after_an_unanswered_text_read_takes_copied_files_before_reading_the_bitmap() {
let d = tempfile::Builder::new().prefix("vectorcraft-late-files-").tempdir().unwrap();
let art = d.path().join("art.png");
let mut png = vec![];
image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
std::fs::write(&art, &png).unwrap();
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let seen = asked.clone();
// The owner offers files and no text; a bitmap read would get no answer in its wait.
let (mut cb, release) = slow_owner(move |request| {
seen.lock().unwrap().push(request);
match request {
Request::Files => Answer::Files(vec![art.clone()]),
_ => Answer::failed(request, "none".into()),
}
});
assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err());
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the text read is kept for the paste");
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
drop(release);
assert_eq!(paste.join().ok().flatten().map(|f| (f.mime, f.data)), Some((PNG, png)));
// The files were read before any bitmap read that could leave the worker busy.
assert_eq!(*asked.lock().unwrap(), [Request::Text, Request::Text, Request::Files]);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_paste_after_an_unanswered_files_read_reads_the_text_before_the_bitmap() {
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let seen = asked.clone();
// The owner offers text and no files; a bitmap read would get no answer in its wait.
let (mut cb, release) = slow_owner(move |request| {
seen.lock().unwrap().push(request);
match request {
Request::Files => Answer::Files(vec![]),
Request::Text => Answer::Text(Ok("copied elsewhere".into())),
Request::Image => Answer::failed(request, "none".into()),
}
});
assert!(cb.read_waiting(Request::Files, Duration::ZERO).files().is_empty());
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the files read is kept for the paste");
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
drop(release);
assert_eq!(paste.join().ok().flatten().map(|f| (f.mime, f.data)), Some((TEXT, b"copied elsewhere".to_vec())));
// The text was read before the bitmap read that could leave the worker busy.
assert_eq!(*asked.lock().unwrap(), [Request::Files, Request::Files, Request::Text, Request::Image]);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_late_answer_to_an_ownership_check_is_pasted_only_while_it_is_awaited() {
+3 -2
View File
@@ -21,9 +21,10 @@ use objc2_core_text::CTFontManagerCopyAvailableFontURLs;
/// The most fonts read from the list (a system has a few thousand faces).
const MAX_FONTS: usize = 1 << 16;
/// Have the font scans read the font files CoreText lists.
/// Have the font scans read the font files CoreText lists, in place of asking the font service for
/// CoreText's fonts a second time.
pub fn install() {
vectorcraft_text::set_platform_font_files(font_files);
vectorcraft_text::set_platform_font_files_complete(font_files);
}
/// The files of the fonts available to the app as CoreText lists them now (fonts registered since
+3 -2
View File
@@ -40,9 +40,10 @@ const MAX_FACE_FILES: u32 = 8;
/// The longest file path taken, in UTF-16 units (Windows' own limit).
const MAX_PATH: u32 = 32_767;
/// Have the font scans read the font files DirectWrite and GDI list.
/// Have the font scans read the font files DirectWrite and GDI list, in place of asking the font
/// service for DirectWrite's collection a second time.
pub fn install() {
vectorcraft_text::set_platform_font_files(font_files);
vectorcraft_text::set_platform_font_files_complete(font_files);
}
/// The local files of the fonts in DirectWrite's system font collection as it is now (fonts
+597 -30
View File
@@ -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
+5 -4
View File
@@ -180,10 +180,11 @@ pub(crate) use export_names::{
use export_names::{distinct_names_by, write_encoded};
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_DOCUMENT_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS,
builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters,
open_extensions, open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters,
places_with_importer, plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export,
writable_format,
};
pub(crate) use formats::{is_own_title, reads};
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro Line truncated
always,
load::open
),
+38 -21
View File
@@ -714,9 +714,18 @@ pub const DOCX_EXTS: &[&str] = &["docx"];
/// Word 97-2003 documents: File → Place sets them as area type with their formatting.
pub const DOC_EXTS: &[&str] = &["doc"];
/// The Place dialog's Word filter: Word documents and Word 97-2003 documents.
/// The Open and Place dialogs' Word filter: Word documents and Word 97-2003 documents.
const WORD_EXTS: &[&str] = &["docx", "doc"];
/// Text, RTF and Word files: File › Open makes a new document of their text, set as File › Place
/// sets it ([`TEXT_EXTS`], [`RTF_EXTS`], [`DOCX_EXTS`] and [`DOC_EXTS`]).
pub const TEXT_DOCUMENT_EXTS: &[&str] = &["txt", "rtf", "docx", "doc"];
/// The Open and Place dialogs' filters of text, RTF and Word files, after the document formats.
fn text_document_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), ("Word", WORD_EXTS)].into_iter()
}
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`],
/// [`DOCX_EXTS`] and [`DOC_EXTS`].
pub const PLACE_EXTS: &[&str] = &[
@@ -915,15 +924,20 @@ pub fn opens_as_other(ext: &str) -> bool {
/// File › Open's extensions and filters for the installed importer plug-ins.
type ImporterPart = (&'static [&'static str], Vec<(&'static str, &'static [&'static str])>);
/// File › Open's part for the installed importer plug-ins: the extensions of "All readable files"
/// ([`OPEN_EXTS`], then the importers' extensions in plug-in id order) and one filter per importer
/// File › Open's part for the installed importer plug-ins ([`importer_open_part`]): the
/// extensions [`open_extensions`] gives, those of "All readable files", and the importers' filters.
type ImporterOpenPart = (&'static [&'static str], &'static [&'static str], Vec<(&'static str, &'static [&'static str])>);
/// File › Open's part for the installed importer plug-ins: the extensions of the documents it reads
/// ([`OPEN_EXTS`], then the importers' extensions in plug-in id order), those of "All readable
/// files" (the same, with [`TEXT_DOCUMENT_EXTS`] after [`OPEN_EXTS`]), and one filter per importer
/// that has extensions left, under its name. An importer's extensions leave out those a built-in
/// format reads, which File › Open reads with that format, and those File › Open opens as something
/// else ([`opens_as_other`]). Made once for each set of installed plug-ins, so it lives as long as
/// the dialogs that hold it.
fn importer_open_part() -> ImporterPart {
/// format reads, which File › Open reads with that format, those of text, RTF and Word files, which
/// File › Open reads as text, and those File › Open opens as something else ([`opens_as_other`]).
/// Made once for each set of installed plug-ins, so it lives as long as the dialogs that hold it.
fn importer_open_part() -> ImporterOpenPart {
use vectorcraft_plugins::registry;
static MADE: std::sync::Mutex<Option<(u64, ImporterPart)>> = std::sync::Mutex::new(None);
static MADE: std::sync::Mutex<Option<(u64, ImporterOpenPart)>> = std::sync::Mutex::new(None);
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
let revision = registry::revision();
if let Some((r, part)) = made.as_ref()
@@ -934,7 +948,8 @@ fn importer_open_part() -> ImporterPart {
let mut exts: Vec<&'static str> = open_exts().to_vec();
let mut filters = Vec::new();
for f in importer_formats() {
let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect();
let own: Vec<&'static str> =
f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !TEXT_DOCUMENT_EXTS.contains(e) && !opens_as_other(e)).collect();
if own.is_empty() {
continue;
}
@@ -946,27 +961,31 @@ fn importer_open_part() -> ImporterPart {
let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) };
filters.push((f.label, own));
}
let all: Vec<&'static str> = open_exts().iter().chain(TEXT_DOCUMENT_EXTS).chain(&exts[open_exts().len()..]).copied().collect();
let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) };
let part = (exts, filters);
let part = (exts, &*Box::leak(all.into_boxed_slice()), filters);
*made = Some((revision, part.clone()));
part
}
/// Every extension File › Open reads as a document: [`OPEN_EXTS`], then the extensions the
/// installed importer plug-ins list that no built-in format reads and that File › Open doesn't open
/// as something else ([`opens_as_other`]), in plug-in id order.
/// as something else ([`opens_as_other`]), in plug-in id order. Text, RTF and Word files
/// ([`TEXT_DOCUMENT_EXTS`]), which File › Open makes a document of, are not among them.
pub fn open_extensions() -> &'static [&'static str] {
importer_open_part().0
}
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
/// swatch and graphic style libraries (which open in their library panels), Libraries panel
/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts
/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed).
/// File › Open's filters: "All readable files" first ([`open_extensions`] with
/// [`TEXT_DOCUMENT_EXTS`]), then one per readable format, then text, RTF and Word (`.docx` and
/// `.doc`), then one per importer plug-in (under its name, with the extensions [`open_extensions`]
/// takes from it), then swatch and graphic style libraries (which open in their library panels),
/// Libraries panel libraries, flattener, PDF, print, perspective grid and export presets and
/// composite fonts (imported), shortcut sets, scripts (checked without running them) and plug-ins
/// (installed).
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
let (all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
let (_, all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(text_document_filters()).chain(importers).chain(other_open_filters())
}
/// [`open_filters`] without the importer plug-ins: "All readable files" lists [`OPEN_EXTS`]. For
@@ -1011,9 +1030,7 @@ pub fn library_open_filters(
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("All placeable files", place_exts()))
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
.chain(std::iter::once(("Text", TEXT_EXTS)))
.chain(std::iter::once(("RTF", RTF_EXTS)))
.chain(std::iter::once(("Word", WORD_EXTS)))
.chain(text_document_filters())
}
/// File › Place's part for the installed importer plug-ins whose manifests set `place`: the
+6 -5
View File
@@ -55,14 +55,15 @@ fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> {
/// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the
/// one `importer` names, which must list the file's extension; else, when no built-in format reads
/// the file, the first installed importer that lists its extension; else `None`.
/// the file and it is no text, RTF or Word file by its extension, the first installed importer
/// that lists its extension; else `None`.
pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plugin>>> {
if let Some(id) = named(p, C)? {
let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?;
check_extension(C, plugin.manifest(), name)?;
return Ok(Some(plugin));
}
if detect(name, bytes).is_some_and(super::formats::reads) {
if detect(name, bytes).is_some_and(super::formats::reads) || super::TEXT_DOCUMENT_EXTS.contains(&extension(name).as_str()) {
return Ok(None);
}
Ok(import::for_extension(&extension(name)).into_iter().next())
@@ -92,12 +93,12 @@ pub(crate) fn for_place(name: &str) -> Option<Arc<Plugin>> {
}
/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no
/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer
/// that reads for `mode` lists it.
/// built-in format reads the extension (nor as text, RTF or Word) and an importer that reads for
/// `mode` lists it.
fn importer_reads(ext: &str, mode: Mode) -> bool {
super::readable_format(ext).is_none()
&& match mode {
Mode::Import => !import::for_extension(ext).is_empty(),
Mode::Import => !super::TEXT_DOCUMENT_EXTS.contains(&ext) && !import::for_extension(ext).is_empty(),
Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(),
}
}
+9 -1
View File
@@ -815,6 +815,14 @@ pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value,
read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false)
}
/// A text, RTF or Word file as a new document of its text, decoded with the `text` options of
/// `document.open`'s params `p` ([`crate::cmd::place::text_document`]); any other file as
/// [`load_with`] reads it with `opts`.
fn text_or_load(name: &str, bytes: &[u8], p: &Value, opts: &LoadOptions) -> Result<Loaded> {
let Some((doc, format, warnings)) = crate::cmd::place::text_document(name, bytes, p)? else { return load_with(name, bytes, opts) };
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
}
/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile
/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no
/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or
@@ -837,7 +845,7 @@ pub fn read_for_open_asking(
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
// The color mode `p` asks for converts the colors after the policies did, through the
// profiles the document keeps.
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
None => (text_or_load(name, bytes, p, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
}
};
let mut file = ReadFile {
+6 -5
View File
@@ -101,7 +101,7 @@ fn opens_every_readable_format() {
let mime = &doc.images[&im.key].mime;
assert_eq!(mime, if name.ends_with("tif") || name.ends_with("bmp") { "image/png" } else { format_for_name(name).unwrap().mime });
}
assert!(s.execute("document.open", &json!({"name": "x.txt", "dataBase64": "aGVsbG8="})).is_err());
assert!(s.execute("document.open", &json!({"name": "x.xyz", "dataBase64": "aGVsbG8="})).is_err());
}
#[test]
@@ -456,13 +456,14 @@ fn open_exts_cover_every_readable_format() {
for e in open_exts() {
assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format");
}
assert!(readable_format("txt").is_none(), "text documents open through their own reader, not a graphic format");
let filters: Vec<_> = open_filters().collect();
assert_eq!(filters[0], ("All readable files", open_exts()));
assert_eq!(filters[0], ("All readable files", &[open_exts(), TEXT_DOCUMENT_EXTS].concat()[..]));
assert_eq!(
filters.len(),
13 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
fonts, shortcut sets, scripts, plug-ins"
16 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
"and text, RTF and Word, swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export \
presets, composite fonts, shortcut sets, scripts, plug-ins"
);
let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter"));
let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT];
+18 -1
View File
@@ -5,6 +5,9 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use super::typemenu::all_texts;
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
use crate::packs::{self, Outcome};
@@ -16,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Language Packs",
[],
None,
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into), missing: [{lang, locale: string|null}…] (the languages of the front document's visible, unlocked type that have no dictionary: each with its pack's locale, null before the index is first fetched; a language the fetched index has no pack for is left out)}",
always,
list
),
@@ -82,9 +85,23 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
"available": backend.is_some(),
"missing": missing(s).iter().map(|m| json!({"lang": m.tag, "locale": m.pack.as_ref().map(|p| &p.locale)})).collect::<Vec<_>>(),
}))
}
/// The languages of the front document's type (the type spell check reads: visible, unlocked) that
/// have no dictionary yet, with the pack for each ([`packs::missing_of`]): what the missing-pack
/// bar offers, and `proof.packs`'s `missing`.
pub fn missing(s: &Session) -> Vec<packs::Missing> {
let Ok(st) = s.doc() else { return Vec::new() };
let texts = all_texts(&st.doc);
let runs = texts.iter().filter_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => Some(t.runs.iter()),
_ => None,
});
packs::missing_of(runs.flatten().filter_map(|r| r.style.language.as_deref()))
}
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
/// store the Craft apps share, which is outside them.
fn not_confined(command: &str) -> Result<()> {
+72 -30
View File
@@ -193,6 +193,76 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given:
Ok((l, slices))
}
/// The story of the text, RTF or Word file `name` holding `bytes`, with its format and warnings; a
/// text file is decoded with the `text` options of `p` (errors of command `cmd`). `None` when the
/// file is none of these.
fn text_story(name: &str, bytes: &[u8], p: &Value, cmd: &str) -> Result<Option<(text::Story, &'static Format, Vec<String>)>> {
// An Affinity file is recognised by its signature, whatever its name says.
if fileio::TEXT_EXTS.contains(&fileio::extension(name).as_str()) && !vectorcraft_affinity::is_affinity(bytes) {
let text = text::import(bytes, text::TextOptions::parse(p, cmd)?, cmd)?;
return Ok(Some((text::Story::plain(text), &text::FORMAT, vec![])));
}
// An RTF file is recognized by its content, whatever its name says (a .txt file is plain text).
if rtf::is_rtf(bytes) {
return Ok(Some((rtf::import(bytes, cmd)?, &rtf::FORMAT, vec![])));
}
// A Word document is recognized by its name or by its package's `word/document.xml`.
if docx::is_docx(name, bytes) {
return Ok(Some((docx::import(bytes, cmd)?, &docx::FORMAT, vec![])));
}
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
// stream.
if doc::is_doc(name, bytes) {
let (story, warnings) = doc::import(bytes, cmd)?;
return Ok(Some((story, &doc::FORMAT, warnings)));
}
Ok(None)
}
/// Whether File › Open reads the file `name` holding `bytes` as a text, RTF or Word document: its
/// extension is one of [`fileio::TEXT_DOCUMENT_EXTS`], and it does not start with a PDF header
/// (`%PDF-`, a digit, `.`, and a digit) or an Affinity signature (such a file opens as that format,
/// whatever its name says).
pub fn opens_as_text(name: &str, bytes: &[u8]) -> bool {
let pdf = bytes.starts_with(b"%PDF-")
&& bytes.get(5).is_some_and(u8::is_ascii_digit)
&& bytes.get(6) == Some(&b'.')
&& bytes.get(7).is_some_and(u8::is_ascii_digit);
fileio::TEXT_DOCUMENT_EXTS.contains(&fileio::extension(name).as_str()) && !pdf && !vectorcraft_affinity::is_affinity(bytes)
}
/// The size of the document File › Open makes of a text, RTF or Word file: a letter page.
const TEXT_DOCUMENT: (f64, f64) = (612.0, 792.0);
/// File › Open of the text, RTF or Word file `name` holding `bytes` (`document.open`, whose params
/// `p` give a text file's `text` options): a new letter-size document whose first layer holds the
/// file's text as area type, in a frame 36 pt inside the artboard, as File › Place sets it, with
/// the file's format and warnings. `None` when the file's extension is not one of
/// [`fileio::TEXT_DOCUMENT_EXTS`], when it starts with a PDF or Affinity signature
/// ([`opens_as_text`]), or when its content is none of these files.
pub(crate) fn text_document(name: &str, bytes: &[u8], p: &Value) -> Result<Option<(Document, &'static Format, Vec<String>)>> {
const C: &str = "document.open";
if !opens_as_text(name, bytes) {
return Ok(None);
}
let Some((story, format, warnings)) = text_story(name, bytes, p, C)? else { return Ok(None) };
// The RTF reader places what it reads of a file cut short; File › Open refuses it as damaged.
if format.id == rtf::FORMAT.id && !rtf::is_complete(bytes) {
return Err(bad(C, format!("`{}` is damaged: it ends inside an RTF group", fileio::file_name(name))));
}
if story.plain_text().trim().is_empty() {
return Err(bad(C, format!("`{}` has no text to open", fileio::file_name(name))));
}
let mut d = Document::new(TEXT_DOCUMENT.0, TEXT_DOCUMENT.1);
let frame = text_frame(d.artboards.first().map(|a| a.rect));
let node = Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(story, frame, &d.setup))));
let node = transformed(node, Affine::translate(frame.origin().to_vec2()));
let layer = d.layers.first().map(|l| l.id);
d.insert(layer, usize::MAX, node)?;
d.title = fileio::file_name(name);
Ok(Some((d, format, warnings)))
}
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
@@ -205,39 +275,11 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: O
if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? {
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
}
// An Affinity file is recognised by its signature, whatever its name says.
if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) {
let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?;
if text.trim().is_empty() {
return Err(bad(cmd, format!("`{name}` has no text to place")));
}
let art = Art::Text(text::Story::plain(text));
return Ok(Loaded { name, format: &text::FORMAT, art, natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
}
// An RTF file is recognized by its content, whatever its name says (a .txt file is plain text).
if rtf::is_rtf(&src.bytes) {
let story = rtf::import(&src.bytes, cmd)?;
if let Some((story, format, warnings)) = text_story(src.name, &src.bytes, p, cmd)? {
if story.plain_text().trim().is_empty() {
return Err(bad(cmd, format!("`{name}` has no text to place")));
}
return Ok(Loaded { name, format: &rtf::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
}
// A Word document is recognized by its name or by its package's `word/document.xml`.
if docx::is_docx(src.name, &src.bytes) {
let story = docx::import(&src.bytes, cmd)?;
if story.plain_text().trim().is_empty() {
return Err(bad(cmd, format!("`{name}` has no text to place")));
}
return Ok(Loaded { name, format: &docx::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
}
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
// stream.
if doc::is_doc(src.name, &src.bytes) {
let (story, warnings) = doc::import(&src.bytes, cmd)?;
if story.plain_text().trim().is_empty() {
return Err(bad(cmd, format!("`{name}` has no text to place")));
}
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
return Ok(Loaded { name, format, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
}
let format = fileio::detect(src.name, &src.bytes);
if format.is_none_or(|f| !fileio::reads(f))
+41
View File
@@ -62,6 +62,41 @@ pub(super) fn is_rtf(bytes: &[u8]) -> bool {
bytes.get(start..).is_some_and(|b| b.starts_with(b"{\\rtf"))
}
/// Does the RTF file `bytes` close every group it opens? A control symbol's escaped brace (`\{`,
/// `\}`), an escaped backslash (`\\`) and the bytes of `\binN` binary data open and close nothing.
/// A file that ends inside a group was cut short; bytes after the outermost group's closing brace
/// are not checked.
pub(super) fn is_complete(bytes: &[u8]) -> bool {
let mut depth = 0usize;
let mut i = 0;
while let Some(&b) = bytes.get(i) {
match b {
b'\\' => {
let (word, n, end) = control_word(bytes, i + 1);
if word != "bin" {
i += 2;
continue;
}
// The binary data's length as `import` reads it; data that runs past the end of the
// file leaves the file incomplete.
let len = usize::try_from(n.unwrap_or(0)).unwrap_or(0);
match end.checked_add(len) {
Some(next) if next <= bytes.len() => i = next,
_ => return false,
}
continue;
}
b'{' => depth += 1,
// The document ends where its outermost group closes; bytes after it are not read.
b'}' if depth <= 1 => return true,
b'}' => depth -= 1,
_ => {}
}
i += 1;
}
false
}
/// The text of an RTF file's `bytes` with its character and paragraph formatting.
pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
if bytes.len() > text::MAX_TEXT {
@@ -717,6 +752,12 @@ mod tests {
let deep = format!("{{\\rtf1 {}x{}}}", "{".repeat(5000), "}".repeat(5000));
assert_eq!(text_of(&read(&deep)), "x");
assert_eq!(text_of(&read(r"{\rtf1 unclosed {\b group")), "unclosed group");
assert!(!is_complete(br"{\rtf1 unclosed {\b group"), "cut short");
assert!(is_complete(br"{\rtf1 a \{ b \} c \\}"), "escaped braces");
assert!(is_complete(b"{\\rtf1 done}\r\n{ trailing bytes"), "bytes after the document's group");
assert!(is_complete(b"{\\rtf1 {\\*\\blipuid x}{\\pict\\bin3 {{{}}"), "binary data");
assert!(!is_complete(b"{\\rtf1 {\\pict\\bin9 }}"), "binary data past the end of the file");
assert!(!is_complete(b"{\\rtf1 {\\pict\\bin99999999999 }}"), "an overflowing binary length");
assert!(import(b"{\\rt", "file.place").is_err(), "not RTF");
assert!(import(b"Plain words", "file.place").is_err(), "not RTF");
}
+9 -1
View File
@@ -608,13 +608,21 @@ impl Transaction {
for st in &mut s.docs {
// Past the newest revision the document reached, so the restored one redraws. A
// document the transaction left as it was keeps its revision, so a run made
// away from the session on it still applies.
// away from the session on it still applies. Putting back an older snapshot, or
// reopening a document the calls closed, counts as a rollback: an object the calls
// made can lose its node ID to a new one. The count never goes below the highest
// one the document reached.
let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect();
let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection);
if !unchanged {
let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision);
st.revision = newest.max(st.revision).saturating_add(1);
}
let rollbacks = reached.iter().map(|d| d.rollbacks).max().unwrap_or(st.rollbacks);
st.rollbacks = rollbacks.max(st.rollbacks);
if reached.is_empty() || reached.iter().any(|d| !Arc::ptr_eq(&d.doc, &st.doc)) {
st.rollbacks = st.rollbacks.saturating_add(1);
}
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
}
s.active = active;
+1
View File
@@ -231,6 +231,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> {
st.selection.prune(&st.doc);
st.history.redo = Arc::unwrap_or_clone(redo);
st.revision += 1;
st.rollbacks += 1;
} else {
s.edit("Exit Symbol Editing Mode", |d, sel| {
finish(d, sel);
+1
View File
@@ -2249,6 +2249,7 @@ fn discard_empty(s: &mut Session, p: &Value) -> Result<Value> {
st.selection.prune(&st.doc);
super::globaledit::follow_history(st);
st.revision += 1;
st.rollbacks += 1;
return Ok(json!({"removed": true}));
}
}
+16 -2
View File
@@ -2,6 +2,8 @@
//! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters)
//! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting).
use std::ops::ControlFlow;
use serde_json::{Value, json};
use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun};
use vectorcraft_geom::{Affine, Rect, shapes};
@@ -40,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Type"],
None,
"{ids?|id?} point type → area type framed by its current layout bounds → {ids}",
has_selection,
|s| has_selected_text_kind(s, |kind| matches!(kind, TextKind::Point), "select point type"),
to_area
),
cmd!(
@@ -49,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
["Type"],
None,
"{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}",
has_selection,
|s| has_selected_text_kind(s, |kind| matches!(kind, TextKind::Area { .. }), "select area type"),
to_point
),
cmd!(
@@ -154,6 +156,18 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// A selected object or one of its descendants has the source kind a conversion needs.
fn has_selected_text_kind(s: &Session, matches_kind: fn(&TextKind) -> bool, reason: &str) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
let found = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).any(|node| {
node.try_walk(&mut |child| {
if matches!(&child.kind, NodeKind::Text(text) if matches_kind(&text.kind)) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
})
.is_break()
});
found.then_some(()).ok_or_else(|| reason.into())
}
/// Text objects among `ids` and their descendants.
pub(crate) fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
let paths = d.index_paths(ids.iter().copied());
+13
View File
@@ -121,6 +121,15 @@ pub struct DocState {
/// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects
/// across that boundary.
pub history_restores: u64,
/// Advances when a canceled interaction, Exit Symbol Editing Mode taking
/// back the entering step, Discard Empty Type taking back the step that made the text, or a command
/// that panicked puts back an older document snapshot. A canceled plug-in run advances it
/// when its calls changed the document. A preview advances it when it discards an earlier preview
/// that allocated node IDs, or fails after discarding an earlier preview's document change.
/// A command run during a tool interaction advances it when it sets aside a preview that allocated
/// node IDs.
/// The same node ID can name different objects across that boundary.
pub rollbacks: u64,
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
/// the UI opens it in a floating window of its own.
pub opened_as_tab: bool,
@@ -556,6 +565,7 @@ impl DocState {
activated: 0,
reverts: 0,
history_restores: 0,
rollbacks: 0,
opened_as_tab: true,
mask_view: None,
spelling_ignored: Default::default(),
@@ -812,6 +822,9 @@ impl DocState {
/// End the interaction in progress, undoing what it changed.
pub(crate) fn undo_interaction(&mut self) {
if let Some(it) = self.interaction.take() {
if !Arc::ptr_eq(&self.doc, &it.doc) {
self.rollbacks += 1;
}
self.doc = it.doc;
self.selection = Arc::unwrap_or_clone(it.selection);
self.sync_new_art();
+141 -1
View File
@@ -59,6 +59,11 @@ pub trait Backend: Send + Sync {
fn index_override(&self) -> Option<String> {
None
}
/// Turns downloading on. Only from the person's own click in the app (an Install or Refresh
/// button, [`enable_downloads`]): no command calls it.
fn enable_downloads(&self) -> Result<(), String> {
Err(not_allowed())
}
}
/// An install running.
@@ -82,6 +87,8 @@ static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refres
static BACKGROUND: AtomicBool = AtomicBool::new(false);
/// Goes up each time the installed packs change.
static GENERATION: AtomicU64 = AtomicU64::new(0);
/// Goes up each time a fetch of the index ends, done or failed ([`index_generation`]).
static INDEX_GENERATION: AtomicU64 = AtomicU64::new(0);
fn jobs() -> MutexGuard<'static, Jobs> {
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
@@ -119,6 +126,18 @@ pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// Goes up each time a fetch of the index ends, done or failed: what [`available`] lists may have changed (a window
/// that keeps the list keys it on this).
pub fn index_generation() -> u64 {
INDEX_GENERATION.load(Ordering::Relaxed)
}
/// `r`, a fetch of the index that ended, counted in [`index_generation`].
fn fetched<T>(r: T) -> T {
INDEX_GENERATION.fetch_add(1, Ordering::Relaxed);
r
}
/// Read the packs folder again: spelling and hyphenation in its languages change.
fn changed() {
craft_proof::packs::reload();
@@ -149,6 +168,33 @@ fn downloads_off() -> String {
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
}
fn not_allowed() -> String {
"only the person using the app can turn on downloading, with their own click".into()
}
/// Turns the font store's downloading on, for every Craft app. The app calls it only for the
/// person's own click on Install or Refresh (never for input the control channel injected), and no
/// command calls it (RFC-0011): an agent can install once the person has turned it on.
pub fn enable_downloads() -> Result<(), String> {
backend().ok_or_else(no_backend)?.enable_downloads()
}
/// An installed pack, as spelling and hyphenation read it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Installed {
/// The pack's locale (`nl`).
pub locale: String,
/// The language's own name, from the pack.
pub name: String,
/// SPDX licence expression of the pack's data.
pub licence: String,
}
/// The packs installed in the store (by this app or another), the ones spelling and hyphenation use.
pub fn installed() -> Vec<Installed> {
craft_proof::packs::installed().into_iter().map(|i| Installed { locale: i.locale, name: i.name, licence: i.licence }).collect()
}
/// The packs the index fetched last lists.
pub fn available() -> Vec<Pack> {
backend().map(|b| b.cached_index()).unwrap_or_default()
@@ -221,6 +267,7 @@ pub fn refresh() -> Result<Outcome, String> {
run(
move || {
let r = b.fetch_index(&cancel).map(|_| ());
INDEX_GENERATION.fetch_add(1, Ordering::Relaxed);
let mut j = jobs();
j.refreshing = None;
if let Err(e) = &r {
@@ -274,7 +321,7 @@ pub fn install(locale: &str) -> Result<Outcome, String> {
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
if !listed(&b.cached_index()) && !listed(&fetched(b.fetch_index(cancel))?) {
return Err(format!("there is no Language pack for {locale}"));
}
b.install(locale, cancel, &mut |done, total| {
@@ -309,6 +356,93 @@ pub fn remove(locale: &str) -> Result<(), String> {
r
}
/// Most languages [`missing`] reports for one document.
const MAX_MISSING: usize = 16;
/// A language the document's type is in that spelling (and hyphenation) can't check yet: what
/// the missing-pack bar offers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Missing {
/// The type's language tag (`hi`, `sr-Latn`).
pub tag: String,
/// The pack the index lists for it; `None` before the index is first fetched, when whether
/// there is one isn't known yet.
pub pack: Option<Pack>,
}
/// Of the language tags `tags` (a document's type's, in order, repeats allowed), those with no
/// dictionary: each with the pack the index lists for it, or, before the index is first fetched,
/// with none. A language the fetched index has no pack for is left out, and so is any language
/// while there is no store to install into ([`crate::cmd::packs::missing`] reads the tags).
pub fn missing_of<'a>(tags: impl IntoIterator<Item = &'a str>) -> Vec<Missing> {
if backend().is_none() {
return Vec::new();
}
let index = available();
let mut out: Vec<Missing> = Vec::new();
let mut seen: Vec<&str> = Vec::new();
for tag in tags {
if seen.contains(&tag) {
continue;
}
seen.push(tag);
// English spells from built-in data; a tag that is no language (`und`, `zxx`) has none.
let lang = craft_proof::ProofLang::from_tag(Some(tag));
if lang == craft_proof::ProofLang::Other || lang.is_english() || craft_proof::missing_dictionary(Some(tag)).is_none() {
continue;
}
let pack = pack_for_tag(tag, &index).cloned();
if pack.is_none() && !index.is_empty() {
continue;
}
// Two tags of one pack (`nl`, `nl-BE`) offer it once.
if pack.is_some() && out.iter().any(|m| m.pack == pack) {
continue;
}
out.push(Missing { tag: tag.to_string(), pack });
if out.len() >= MAX_MISSING {
break;
}
}
out
}
/// The pack for a language tag: the whole tag's (`pt-pt`), else each shorter prefix's
/// (`sr-latn` for `sr-Latn-RS`, `nl` for `nl-NL`), the first `packs` lists. A variant after the
/// region is tried without the region before the region alone (`ca-ES-valencia` is the
/// `ca-valencia` pack's). `None` for English and for a tag no pack is for.
pub fn pack_for_tag<'a>(tag: &str, packs: &'a [Pack]) -> Option<&'a Pack> {
pack_candidates(tag).iter().find_map(|c| packs.iter().find(|p| &p.locale == c))
}
/// Whether `subtag`, after a tag's language (and script), is a region: two letters or three digits.
fn is_region(subtag: &str) -> bool {
(subtag.len() == 2 && subtag.bytes().all(|b| b.is_ascii_alphabetic())) || (subtag.len() == 3 && subtag.bytes().all(|b| b.is_ascii_digit()))
}
/// The pack locales [`pack_for_tag`] tries for `tag`, best first.
fn pack_candidates(tag: &str) -> Vec<String> {
// A tag is a handful of short subtags; anything longer is junk and only its start is read.
let tag: String = tag.trim().chars().take(64).collect::<String>().replace('_', "-").to_ascii_lowercase();
let parts: Vec<&str> = tag.split('-').collect();
let base = parts.first().copied().unwrap_or("");
if base.is_empty() || base == "en" {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for n in (1..=parts.len()).rev() {
let prefix = parts.get(..n).unwrap_or_default();
// The prefix, then without its regions: the variant's pack before the region alone.
let stripped: Vec<&str> = prefix.iter().enumerate().filter(|(i, p)| *i == 0 || !is_region(p)).map(|(_, p)| *p).collect();
for c in [prefix.join("-"), stripped.join("-")] {
if !out.contains(&c) {
out.push(c);
}
}
}
out
}
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
/// packs), pinned by the sha256 of its `index.json`. The font store reads
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
@@ -380,6 +514,12 @@ impl Backend for FontStoreBackend {
fn index_override(&self) -> Option<String> {
craft_font_store::language_pack_index_overridden()
}
fn enable_downloads(&self) -> Result<(), String> {
// The store is opened as an agent's, which can't turn downloading on: the same folder,
// opened as the person's, does (the setting is a file in it, read on each use).
craft_font_store::FontStore::new(self.store.dir().to_path_buf(), craft_font_store::Caller::User).enable_network().map_err(|e| e.to_string())
}
}
/// The font store backend in `dir`, for tests that need the real store without a request.
+55 -3
View File
@@ -869,7 +869,9 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first
/// point, so its position does not change the result, and an area within roundoff of its own
/// bounding box's is counted as none.
/// bounding box's is counted as none. A subpath that crosses itself, such as a figure eight whose
/// loops turn opposite ways and cancel in its signed area, is measured by the area it fills under
/// nonzero, which every loop counts toward.
fn encloses(outline: &kurbo::BezPath) -> bool {
let mut subpaths: Vec<kurbo::BezPath> = Vec::new();
for el in outline.elements() {
@@ -883,11 +885,35 @@ fn encloses(outline: &kurbo::BezPath) -> bool {
subpaths.into_iter().any(|mut sub| {
let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false };
sub.apply_affine(kurbo::Affine::translate(-start.to_vec2()));
let area = kurbo::Shape::area(&sub).abs();
area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area()
let floor = 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area();
let counts = |area: f64| area > 0.0 && area > floor;
counts(kurbo::Shape::area(&sub).abs())
|| (!collinear(&sub)
&& vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(&sub), vectorcraft_geom::FillRule::NonZero)
.is_ok_and(counts))
})
}
/// Whether every point and control point of `sub` lies within roundoff of one straight line, as
/// in a frame collapsed to a line, which encloses no area however the path operations snap it.
fn collinear(sub: &kurbo::BezPath) -> bool {
let points: Vec<kurbo::Point> = sub
.elements()
.iter()
.flat_map(|e| match *e {
kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => vec![p],
kurbo::PathEl::QuadTo(a, p) => vec![a, p],
kurbo::PathEl::CurveTo(a, b, p) => vec![a, b, p],
kurbo::PathEl::ClosePath => vec![],
})
.collect();
let Some(&first) = points.first() else { return true };
let Some(&far) = points.iter().max_by(|a, b| a.distance(first).total_cmp(&b.distance(first))) else { return true };
let axis = far - first;
let length = axis.hypot();
length == 0.0 || points.iter().all(|p| axis.cross(*p - first).abs() <= 64.0 * f64::EPSILON * length * length)
}
/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the
/// outline with its overlaps resolved, thin strips included, has an area. An outline the path
/// operations refuse is judged by [`encloses`] alone.
@@ -2536,6 +2562,32 @@ mod tests {
assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed");
}
#[test]
fn a_figure_eight_clip_outline_fills_its_loops() {
let mut eight = kurbo::BezPath::new();
eight.move_to((0.0, 0.0));
eight.line_to((10.0, 10.0));
eight.line_to((10.0, 0.0));
eight.line_to((0.0, 10.0));
eight.close_path();
assert!(kurbo::Shape::area(&eight).abs() < 1e-9, "the loops cancel in the signed area");
assert!(encloses(&eight), "each loop of the figure eight encloses an area");
assert!(fills(&eight, vectorcraft_geom::FillRule::NonZero));
assert!(fills(&eight, vectorcraft_geom::FillRule::EvenOdd));
let mut line = kurbo::BezPath::new();
line.move_to((0.0, 0.0));
line.line_to((10.0, 10.0));
line.close_path();
assert!(!encloses(&line), "a closed line still encloses nothing");
let mut flat = kurbo::BezPath::new();
flat.move_to((0.0, 0.0));
flat.line_to((1000.0, 0.001));
flat.line_to((2000.0, 0.002));
flat.line_to((1000.0, 0.001));
flat.close_path();
assert!(!encloses(&flat), "a frame collapsed onto a shallow diagonal encloses nothing");
}
#[test]
fn a_made_id_above_two_to_the_53_stays_exact() {
let made = |v: Value| made_id(&(Data::Undefined, v));
+15 -2
View File
@@ -373,6 +373,9 @@ impl Session {
let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection;
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
if previewed {
if st.doc.peek_next_id() > interaction.doc.peek_next_id() {
st.rollbacks += 1;
}
st.doc = interaction.doc.clone();
if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) {
shown_base_selection(&mut st.selection, shown_doc, &st.doc);
@@ -667,7 +670,7 @@ impl Session {
// `defaultsOnly: true`, and one after it.
let tool_paints = self.tool_paints(false) || self.tool_paints(true);
let new_art_basic = self.prefs.new_art_basic;
let (paint, restore_paint, inherited, last_preview_paint) = {
let (paint, restore_paint, inherited, last_preview_paint, discarded_uid, freed_ids, discarded) = {
let menu = self.menu.clone();
let st = self.doc_mut()?;
let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) };
@@ -678,6 +681,8 @@ impl Session {
st.revision += 1;
}
let undone = std::mem::replace(&mut st.doc, it.doc.clone());
let freed_ids = undone.peek_next_id() > it.doc.peek_next_id();
let discarded = !Arc::ptr_eq(&undone, &it.doc);
let isolation = it.isolation;
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
// the paints the interaction began with.
@@ -711,7 +716,7 @@ impl Session {
// undone with it.
st.restore_isolation(isolation, &undone);
cmd::globaledit::follow_history(st);
(paint, restore_paint, inherited, last_preview_paint)
(paint, restore_paint, inherited, last_preview_paint, st.uid, freed_ids, discarded)
};
// The paints before the previews that build on each other: a preview that starts from the
// interaction's paints (or from the inherited ones) starts a new run of them. A field that
@@ -757,6 +762,14 @@ impl Session {
}
let after_paint = r.is_ok().then(|| (base, self.paint.clone()));
let after_item = self.active_appearance_item.clone();
// A preview advances rollbacks when it discards an earlier preview that allocated node IDs, or
// fails after discarding an earlier preview's document change, even when the command activates
// another document.
if let Some(st) = self.docs.iter_mut().find(|d| d.uid == discarded_uid)
&& (freed_ids || (r.is_err() && discarded))
{
st.rollbacks += 1;
}
let st = self.doc_mut()?;
if let Some(it) = &mut st.interaction {
it.active_appearance_item =
+3
View File
@@ -473,6 +473,9 @@ impl Session {
for (uid, doc, selection, interaction, history) in snapshot {
// A document the command closed stays closed.
let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { continue };
if !std::sync::Arc::ptr_eq(&st.doc, &doc) {
st.rollbacks += 1;
}
st.doc = doc;
st.selection = selection;
st.interaction = interaction;
+184
View File
@@ -829,6 +829,190 @@ fn canceling_undo_groups_in_two_documents_drops_the_edits_of_both_from_the_journ
assert_eq!(ids.last(), Some(&"edit.undoGroup.end"));
}
/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which puts back an older snapshot, so
/// it advances `rollbacks`; leaving after an edit adds a step and leaves it as it is.
#[test]
fn leaving_symbol_editing_advances_rollbacks_only_when_taking_back_the_entering_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
for edited in [false, true] {
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("symbol.edit", &json!({})).unwrap();
if edited {
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
}
s.execute("symbol.exitEditing", &json!({})).unwrap();
if edited {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "leaving after an edit keeps the rollback count");
} else {
assert!(s.doc().unwrap().rollbacks > rollbacks, "taking back the entering step advances the rollback count");
}
}
}
/// Discard Empty Type advances `rollbacks` when it takes back the step that made the empty text, which frees the
/// text's node ID; when it removes the text as a new step instead, it leaves the count as it is.
#[test]
fn discard_empty_type_advances_rollbacks_only_when_taking_back_the_step_that_made_the_text() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let made = s.execute("text.create", &json!({"x": 10, "y": 40, "text": ""})).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("text.discardEmpty", &json!({"id": made["id"]})).unwrap();
assert!(s.doc().unwrap().rollbacks > rollbacks, "taking back the step that made the text advances the rollback count");
let kept = s.execute("text.create", &json!({"x": 10, "y": 80, "text": ""})).unwrap();
s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("text.discardEmpty", &json!({"id": kept["id"]})).unwrap();
assert!(s.doc().unwrap().doc.node(NodeId(kept["id"].as_u64().unwrap())).is_none(), "the empty text is removed");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "removing the text as a new step keeps the rollback count");
}
/// A command that panics after changing a document advances that document's `rollbacks` when the document is put
/// back; one that panics before changing it leaves the count as it is.
#[test]
fn a_panicking_command_advances_rollbacks_only_when_it_changed_the_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = NodeId(s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap()["id"].as_u64().unwrap());
for changed in [false, true] {
let rollbacks = s.doc().unwrap().rollbacks;
let r = s.run_guarded("test.panic", |s| {
if changed {
let st = s.doc_mut()?;
std::sync::Arc::make_mut(&mut st.doc).remove(a)?;
}
s.run_nested(|_| panic!("boom"))
});
assert!(matches!(r, Err(EngineError::Internal { .. })), "the panic is returned as an internal error");
if changed {
assert!(s.doc().unwrap().rollbacks > rollbacks, "putting back the changed document advances the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a panic before any change keeps the rollback count");
}
}
}
/// Canceling an interaction whose preview changed the document advances `rollbacks`; canceling one that changed
/// nothing leaves it as it is.
#[test]
fn interaction_cancellation_advances_rollbacks_only_when_restoring() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for previewed in [true, false] {
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
if previewed {
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
}
s.cancel_interaction().unwrap();
if previewed {
assert!(s.doc().unwrap().rollbacks > rollbacks, "a canceled preview advances the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a cancel with no preview keeps the rollback count");
}
}
}
/// A preview advances `rollbacks` when it discards earlier art and frees its node IDs, whether it
/// succeeds or fails. A failed preview also advances it when it discards an earlier document change
/// without freeing IDs. A successful preview that draws the earlier art again also advances the count.
#[test]
fn a_preview_that_discards_earlier_art_and_frees_its_ids_advances_rollbacks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error");
assert!(s.doc().unwrap().rollbacks > rollbacks, "a failed preview after a drawn preview advances the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a failed preview with nothing previewed keeps the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("shape.rectangle", &rect_step(30)["params"]).unwrap();
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that replaces earlier drawn art advances the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
let starting_doc = s.doc().unwrap().doc.clone();
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("select.set", &json!({"ids": []})).unwrap();
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "a selection-only preview leaves the starting document Arc");
assert_eq!(
s.doc().unwrap().rollbacks,
rollbacks + 1,
"a preview that leaves the starting document after a drawn preview advances the rollback count"
);
s.cancel_interaction().unwrap();
let kept = s.execute("shape.rectangle", &rect_step(5)["params"]).unwrap()["id"].clone();
let rollbacks = s.doc().unwrap().rollbacks;
let starting_doc = s.doc().unwrap().doc.clone();
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
let steps = json!({"commands": [
{"command": "select.set", "params": {"ids": [kept]}},
{"command": "object.move", "params": {"dx": 5, "dy": 0}}
]});
s.preview("command.batch", &steps).unwrap();
assert!(!std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "the move changes the document");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that moves art instead of drawing it advances the rollback count");
s.cancel_interaction().unwrap();
}
/// A command run during a tool interaction sets the preview aside and can reuse the node IDs the
/// preview allocated, so it advances `rollbacks`; with no IDs allocated by the preview it does not.
#[test]
fn a_command_outside_a_tool_interaction_advances_rollbacks_only_when_the_preview_allocated_ids() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.begin_interaction("Rectangle").unwrap();
// A tool interaction routes the command through outside_interaction.
s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true;
let preview_id = s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap()["id"].clone();
let rollbacks = s.doc().unwrap().rollbacks;
let command_id = s.execute("shape.rectangle", &rect_step(30)["params"]).unwrap()["id"].clone();
assert_eq!(command_id, preview_id, "a command outside a tool interaction reuses the rectangle preview's node ID");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "setting aside a preview that allocated IDs advances the rollback count");
s.cancel_interaction().unwrap();
for previewed in [true, false] {
s.begin_interaction("Rectangle").unwrap();
s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true;
if previewed {
s.preview("select.none", &json!({})).unwrap();
}
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("shape.rectangle", &rect_step(50)["params"]).unwrap();
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a command with no preview IDs keeps the rollback count, previewed: {previewed}");
s.cancel_interaction().unwrap();
}
}
/// A preview that activates another document advances rollbacks in the document whose art it discards.
#[test]
fn a_preview_that_activates_another_document_advances_only_the_source_rollbacks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
let source_rollbacks = s.documents()[0].rollbacks;
let destination_rollbacks = s.documents()[1].rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("document.activate", &json!({"index": 1})).unwrap();
assert_eq!(s.active_index(), Some(1), "the activation preview makes the destination document active");
assert!(s.documents()[0].rollbacks > source_rollbacks, "discarding the rectangle preview advances the source document's rollback count");
assert_eq!(s.documents()[1].rollbacks, destination_rollbacks, "the activation preview keeps the destination document's rollback count unchanged");
}
/// A cancel drops only the canceled groups' own entries from the journal: an edit made in another
/// document while a group was open stays in that document and in the journal.
#[test]
+31 -6
View File
@@ -4275,19 +4275,44 @@ fn convert_point_area_roundtrip() {
assert_eq!(tt.plain_text(), "Some words");
}
/// Convert To Area Type with no point type selected, and Convert To Point Type with no area type
/// selected, record no undo step and reply with the objects. With point type and area type
/// selected, Convert To Area Type converts the point type in one undo step, and Convert To Point
/// Type then converts both in another.
#[test]
fn converting_type_to_the_kind_it_is_records_no_undo_step() {
fn type_conversion_availability_requires_its_source_kind() {
let mut s = session();
let point = text(&mut s, "Point");
let area = id_of(&s.execute("text.create", &json!({"x": 0, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap());
let rectangle = rect(&mut s, 200.0, 50.0, 20.0, 20.0);
let to_area = find_command("type.convertToAreaType").unwrap();
let to_point = find_command("type.convertToPointType").unwrap();
for (selection, can_convert_to_area, can_convert_to_point) in
[(&[point][..], true, false), (&[area][..], false, true), (&[rectangle][..], false, false), (&[area, point][..], true, true)]
{
sel(&mut s, selection);
for (spec, can_convert) in [(to_area, can_convert_to_area), (to_point, can_convert_to_point)] {
let info = spec.info(&s);
assert_eq!(info.enabled, can_convert, "{} on {selection:?}", info.id);
assert_eq!(info.disabled_reason.is_some(), !can_convert, "{} on {selection:?}", info.id);
}
}
sel(&mut s, &[rectangle, point]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
sel(&mut s, &[group]);
assert!(to_area.info(&s).enabled);
assert!(!to_point.info(&s).enabled);
}
/// An inapplicable conversion is disabled and leaves undo history intact. With point type and
/// area type selected, Convert To Area Type converts the point type in one undo step, and
/// Convert To Point Type then converts both in another.
#[test]
fn inapplicable_type_conversions_record_no_undo_step() {
let mut s = session();
let p = text(&mut s, "Point");
let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap());
for (c, id) in [("type.convertToAreaType", a), ("type.convertToPointType", p)] {
select_with_a_step_to_redo(&mut s, &[id]);
let before = history(&s);
assert_eq!(s.execute(c, &json!({})).unwrap(), json!({"ids": [id.0]}), "{c}");
assert!(matches!(s.execute(c, &json!({})), Err(EngineError::Disabled(..))), "{c}");
assert_eq!(history(&s), before, "{c}");
}
for c in ["type.convertToAreaType", "type.convertToPointType"] {
+97
View File
@@ -265,3 +265,100 @@ fn a_script_cannot_install_a_pack() {
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs");
}
/// A backend that only lists `packs` (the index fetched last), for what the missing-pack bar offers.
struct Listing {
dir: PathBuf,
packs: Vec<Pack>,
}
impl Backend for Listing {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
false
}
fn cached_index(&self) -> Vec<Pack> {
self.packs.clone()
}
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
Err("downloading is off".into())
}
fn install(&self, _: &str, _: &Cancel, _: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
Err("downloading is off".into())
}
fn remove(&self, _: &str) -> std::result::Result<(), String> {
Ok(())
}
}
fn pack(locale: &str) -> Pack {
Pack { locale: locale.into(), name: locale.into(), size: 1, licence: "MIT".into(), class: "Embeddable".into(), spelling: true, hyphenation: true }
}
/// `proof.packs`'s `missing`, as (lang, locale).
fn missing(s: &mut Session) -> Vec<(String, Value)> {
let r = s.execute("proof.packs", &json!({})).unwrap();
r["missing"].as_array().unwrap().iter().map(|m| (m["lang"].as_str().unwrap().to_string(), m["locale"].clone())).collect()
}
/// The missing-pack bar offers the languages of the document's type that have no dictionary: a
/// pack the index lists, or, before the index was ever fetched, the language alone; never one the
/// fetched index has no pack for, nor English.
#[test]
fn the_languages_with_no_dictionary_are_offered_their_pack() {
let _turn = packs_lock();
let root = folder("missing");
let _reset = Reset(root.clone());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "The house"})).unwrap();
// Konkani: no system has a Hunspell dictionary for it, so the check can't depend on the machine.
let id = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "घर"})).unwrap()["id"].clone();
s.execute("text.setFormat", &json!({"ids": [id], "language": "Konkani"})).unwrap();
assert!(missing(&mut s).is_empty(), "no store, nothing to offer");
let listing = |packs: Vec<Pack>| Some(Arc::new(Listing { dir: root.clone(), packs }) as Arc<dyn Backend>);
packs::set_backend(listing(vec![]));
assert_eq!(missing(&mut s), [("kok".to_string(), Value::Null)], "before the first fetch, the language alone");
packs::set_backend(listing(vec![pack("nl"), pack("kok")]));
assert_eq!(missing(&mut s), [("kok".to_string(), json!("kok"))], "the pack the index lists");
packs::set_backend(listing(vec![pack("nl")]));
assert!(missing(&mut s).is_empty(), "the index has no pack for it");
}
/// A pack is found for a tag's region and variant forms (`sr-Latn-RS` is `sr-latn`'s, `nl-BE`
/// is `nl`'s), not for English.
#[test]
fn a_tag_finds_its_pack_without_its_region() {
let index = [pack("nl"), pack("sr-latn"), pack("ca-valencia"), pack("pt-pt")];
let found = |tag: &str| packs::pack_for_tag(tag, &index).map(|p| p.locale.clone());
assert_eq!(found("nl-BE").as_deref(), Some("nl"));
assert_eq!(found("sr-Latn-RS").as_deref(), Some("sr-latn"));
assert_eq!(found("ca-ES-valencia").as_deref(), Some("ca-valencia"));
assert_eq!(found("pt_PT").as_deref(), Some("pt-pt"));
assert_eq!(found("en-NL"), None);
assert_eq!(found("fy"), None);
}
/// Downloading is turned on in the shared store only by the app for the person's click
/// (`packs::enable_downloads`); a backend that can't (a stand-in) refuses.
#[test]
fn the_persons_click_turns_downloading_on_in_the_shared_store() {
let _turn = packs_lock();
let root = folder("consent");
let _reset = Reset(root.clone());
let mut s = dutch_session();
assert!(packs::enable_downloads().is_err(), "no store");
packs::set_backend(Some(Arc::new(Listing { dir: root.clone(), packs: vec![] })));
assert!(packs::enable_downloads().is_err(), "a backend that can't turn it on");
packs::set_backend(Some(packs::font_store_in(root.clone())));
assert_eq!(s.execute("proof.packs", &json!({})).unwrap()["downloads"], false);
packs::enable_downloads().unwrap();
assert_eq!(s.execute("proof.packs", &json!({})).unwrap()["downloads"], true, "the store the agent opened sees it on");
}
+47
View File
@@ -8131,6 +8131,19 @@ fn install_select_all_then_remove(s: &mut Session, id: &str) {
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
}
/// Installs a filter `id` that calls `shape.rectangle` and then returns no objects.
fn install_draw_rectangle_then_remove(s: &mut Session, id: &str) {
let grant = json!(["doc.read", "doc.write", "commands"]);
let manifest =
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["shape.rectangle"]}}"#);
let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))
(data (i32.const 0x2000) "shape.rectangle")
(data (i32.const 0x2100) "{\22x\22:0,\22y\22:0,\22width\22:5,\22height\22:5}")"#;
let first = "(drop (call $vc_call (i32.const 0x2000) (i32.const 15) (i32.const 0x2100) (i32.const 34)))";
let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, first, r#"{"objects":[]}"#)).unwrap();
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
}
/// Runs the job of a run that [`FilterRun::begin_calls`] started as the web build's plug-in worker
/// does, making each command call in `s` → its output.
fn run_job_away(s: &mut Session, job: &cmd::plugin::FilterJob) -> Vec<u8> {
@@ -8201,6 +8214,40 @@ fn a_calling_run_made_away_from_the_session_that_ends_changes_nothing() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A run made away from the session that ends after its calls changed the document advances `rollbacks`.
/// A run whose calls only changed the selection or that ends before any call keeps the rollback count.
#[test]
fn an_ended_calling_run_advances_rollbacks_only_when_its_calls_changed_the_document() {
use cmd::plugin::FilterRun;
let id = "test.engine.callsawayrollback";
let draw_id = "test.engine.callsawayrollbackdraw";
let mut s = session();
install_select_all_then_remove(&mut s, id);
install_draw_rectangle_then_remove(&mut s, draw_id);
let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
for (plugin_id, called, changed_document) in [(draw_id, true, true), (id, true, false), (id, false, false)] {
run(&mut s, "select.set", json!({"ids": [a.0]}));
let rollbacks = s.doc().unwrap().rollbacks;
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": plugin_id})).unwrap();
let doc = s.doc().unwrap().doc.clone();
if called {
run_job_away(&mut s, &job);
assert_eq!(!std::sync::Arc::ptr_eq(&doc, &s.doc().unwrap().doc), changed_document, "the calls change only the intended state");
assert_ne!(s.doc().unwrap().selection.objects, vec![a], "the calls change the selection");
}
s.end_plugin_calls();
if changed_document {
assert!(s.doc().unwrap().rollbacks > rollbacks, "an ended run whose calls changed the document advances the rollback count");
} else if called {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run whose calls only changed the selection keeps the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run with no calls keeps the rollback count");
}
}
run(&mut s, "plugin.remove", json!({"id": draw_id}));
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// An output handed in for a run that holds the documents is dropped when that run ends: a later
/// run with the same input and params is not given it, and `plugin.run` without its own output is
/// refused.
+110 -3
View File
@@ -1162,8 +1162,115 @@ fn place_reads_what_open_reads_and_text_files() {
let word: (&str, &[&str]) = ("Word", &["docx", "doc"]);
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word)));
assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
assert!(
!cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))),
"Open doesn't read text, RTF or Word files"
// File › Open lists them in "All readable files", after the formats it reads, and in filters
// of their own after the format filters; the documents File › Open reads (Batch's source files,
// `openExtensions`) leave them out.
let open: Vec<_> = cmd::fileio::open_filters().collect();
assert_eq!(open[0].0, "All readable files");
assert!(open[0].1.starts_with(cmd::fileio::place_exts()), "{:?}", open[0].1);
let text = open.iter().position(|f| f.0 == "Text").expect("File › Open has a Text filter");
assert_eq!(open.get(text..text + 3), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
assert_eq!(
open.get(text - 1).map(|f| f.0),
cmd::fileio::FORMATS.iter().rfind(|f| cmd::fileio::reads(f)).map(|f| f.label),
"after the format filters"
);
assert!(!cmd::fileio::open_extensions().iter().any(|e| ["txt", "rtf", "docx", "doc"].contains(e)));
}
fn open_text(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result<Value> {
let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)});
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
o.extend(e);
}
s.execute("document.open", &p)
}
/// The opened document's one object: its text and frame bounds.
fn opened_text(s: &Session) -> (String, Rect) {
let st = s.doc().unwrap();
let layer = &st.doc.layers[0];
let [n] = layer.children().map_or(&[][..], Vec::as_slice) else { panic!("one object on the first layer: {:?}", layer.children()) };
let NodeKind::Text(t) = &n.kind else { panic!("not type: {:?}", n.kind) };
assert!(matches!(t.kind, TextKind::Area { .. }), "area type");
(t.plain_text(), n.geometric_bounds().unwrap())
}
/// File › Open of a text file makes a new letter-size document whose text, read with the Text
/// Import Options given, is area type 36 pt inside the artboard; it has no path, so Save asks for a
/// name, and nothing to undo.
#[test]
fn open_makes_a_new_document_of_a_text_file_with_its_options() {
let mut s = Session::new();
let text = b"Caf\xE9 au lait,\r\nplease.\r\n\r\nThanks";
let opts = json!({"text": {"characterSet": "cyrillic", "removeLineReturns": true, "removeParagraphReturns": true}});
let r = open_text(&mut s, "order.txt", text, opts).unwrap();
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("txt"), Some("order.txt")));
let (body, frame) = opened_text(&s);
assert_eq!(body, "Cafй au lait, please.\nThanks", "decoded as Cyrillic, lines joined, blank lines dropped");
assert!(close(frame, Rect::new(36.0, 36.0, 576.0, 756.0)), "a letter page less a 36 pt margin: {frame:?}");
let st = s.doc().unwrap();
assert_eq!(st.doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>(), [Rect::new(0.0, 0.0, 612.0, 792.0)]);
assert_eq!((st.path.as_deref(), st.history.undo.len()), (None, 0));
// Without options each line is a paragraph, read as UTF-8.
open_text(&mut s, "order.txt", "Café\r\nau lait".as_bytes(), json!({})).unwrap();
assert_eq!(opened_text(&s).0, "Café\nau lait");
assert_eq!(s.documents().len(), 2, "each open is a document of its own");
}
#[test]
fn open_makes_a_new_document_of_an_rtf_or_word_file() {
let mut s = Session::new();
let r = open_text(&mut s, "letter.rtf", LETTER_RTF.as_bytes(), json!({})).unwrap();
assert_eq!(r["format"], "rtf");
assert_eq!(opened_text(&s).0, "Plain and bold words2.\nCentered café");
let body = r#"<w:p><w:r><w:t>Minutes</w:t></w:r></w:p><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Agreed</w:t></w:r></w:p>"#;
let r = open_text(&mut s, "minutes.docx", &docx(body, STYLES), json!({})).unwrap();
assert_eq!(r["format"], "docx");
assert_eq!(opened_text(&s).0, "Minutes\nAgreed");
let doc = Word97 { pieces: vec![("Old memo\r", true)], ..Word97::default() }.build();
let r = open_text(&mut s, "memo.doc", &doc, json!({})).unwrap();
assert_eq!(r["format"], "doc");
assert_eq!(opened_text(&s).0, "Old memo");
}
/// A file without text, bad Text Import Options and a damaged file open nothing.
#[test]
fn text_files_that_cant_be_read_open_no_document() {
let mut s = Session::new();
let e = open_text(&mut s, "blank.txt", b" \r\n\t\r\n", json!({})).unwrap_err().to_string();
assert!(e.contains("`blank.txt` has no text to open"), "{e}");
let e = open_text(&mut s, "notes.txt", b"words", json!({"text": {"characterSet": "klingon"}})).unwrap_err().to_string();
assert!(e.contains("text.characterSet `klingon`"), "{e}");
assert!(open_text(&mut s, "broken.docx", b"PK\x03\x04 not a package", json!({})).is_err());
assert!(open_text(&mut s, "plain.rtf", b"Plain words, not RTF", json!({})).is_err(), "an .rtf file that isn't RTF");
let e = open_text(&mut s, "broken.rtf", br"{\rtf1 unclosed {\b group", json!({})).unwrap_err().to_string();
assert!(e.contains("`broken.rtf` is damaged"), "a truncated RTF file: {e}");
assert_eq!(s.documents().len(), 0);
open_text(&mut s, "escaped.rtf", br"{\rtf1 a \{ brace \} and \\ slash}", json!({})).unwrap();
assert_eq!(s.documents().len(), 1, "escaped braces don't count as groups");
}
/// A file whose content is a format File › Open reads (a PDF file) opens as that format even when
/// it is named `.txt`, as it did before text files opened.
#[test]
fn a_pdf_named_txt_opens_as_a_pdf() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
let pdf = s.execute("document.exportPdf", &json!({})).unwrap();
let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().expect("dataBase64")).unwrap();
assert!(pdf.starts_with(b"%PDF"));
let r = open_text(&mut s, "drawing.txt", &pdf, json!({})).unwrap();
assert_eq!(r["format"], "pdf", "{r}");
let st = s.doc().unwrap();
assert!(!st.doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).any(|n| matches!(n.kind, NodeKind::Text(_))), "no text");
assert!(!cmd::place::opens_as_text("drawing.txt", &pdf), "File › Open asks no Text Import Options for it");
// Text that only looks like the start of a drawing is still text.
open_text(&mut s, "notes.txt", b"<svg is the opening tag", json!({})).unwrap();
assert_eq!(opened_text(&s).0, "<svg is the opening tag");
open_text(&mut s, "notes.txt", b"%PDF is the marker to look for", json!({})).unwrap();
assert_eq!(opened_text(&s).0, "%PDF is the marker to look for");
open_text(&mut s, "notes.txt", b"%PDF-1 is the prefix to look for", json!({})).unwrap();
assert_eq!(opened_text(&s).0, "%PDF-1 is the prefix to look for");
}
+15
View File
@@ -264,6 +264,21 @@ fn file_open_lists_only_the_extensions_it_opens_with_an_importer() {
s.execute("plugin.remove", &json!({"id": "test.claimedonly"})).unwrap();
}
/// A text file opens as a document of its text even when an importer lists `.txt`: the importer
/// reads it only when `importer` names it, and File › Open's filter for it leaves `.txt` out.
#[test]
fn text_files_open_as_text_unless_an_importer_is_named() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.textclaim", r#"["txt","tcx"]"#, "{}"), RECT));
assert_eq!(open(&mut s, "notes.txt", b"words", json!({})).unwrap()["format"], "txt");
assert_eq!(open(&mut s, "notes.txt", b"words", json!({"importer": "plugin.test.textclaim"})).unwrap()["format"], "plugin.test.textclaim");
let filters: Vec<_> = fileio::open_filters().collect();
assert!(filters.contains(&("Test test.textclaim", &["tcx"][..])), "{filters:?}");
assert_eq!(filters[0].1.iter().filter(|e| **e == "txt").count(), 1, "All readable files lists .txt once");
assert!(!fileio::open_extensions().contains(&"txt"));
s.execute("plugin.remove", &json!({"id": "test.textclaim"})).unwrap();
}
/// Several importers list one extension: the one whose id sorts first opens the file, and
/// `importer` picks another (by its format id or its id).
#[test]
+1 -1
View File
@@ -364,7 +364,7 @@ pub fn tool_definitions() -> Vec<Value> {
"open_file",
"Open file",
&format!(
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. A text, RTF or Word file (.txt, .rtf, .docx, .doc) opens as a new letter-size document of its text as area type. A file with one of those extensions that starts with a PDF header or an Affinity signature opens as that format instead. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
open_exts().join(", .")
),
obj(
+1 -1
View File
@@ -47,7 +47,7 @@ pub use effects::stroke::width_outline;
pub use fx::pinned_appearance_for_geometry_edit;
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
pub use live::expand_live;
pub use pattern::render_pattern_swatch;
pub use pattern::{render_pattern_swatch, render_pattern_swatch_words};
pub use vectorcraft_effects as effects;
pub use vello_cpu;
+4 -5
View File
@@ -243,11 +243,11 @@ pub fn supersample_factor(w: u32, h: u32) -> Option<u32> {
})
}
/// Average each `k`×`k` block of `src` (`w`×`h` pixels of 4 premultiplied bytes) into one pixel.
pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
let (ow, oh) = (w / k.max(1), h / k.max(1));
/// Average each `k`×`k` block of `src` (pixels of 4 premultiplied bytes in rows `w` wide) into one
/// pixel of `out`, whose rows are `w` / `k` pixels wide.
pub(crate) fn downsample(src: &[u8], w: usize, k: usize, out: &mut [u8]) {
let ow = w / k.max(1);
let n = (k * k).max(1) as u32;
let mut out = vec![0u8; ow * oh * 4];
for (o, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (ox, oy) = (o % ow.max(1), o / ow.max(1));
let mut acc = [0u32; 4];
@@ -263,7 +263,6 @@ pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
*d = ((a + n / 2) / n).min(255) as u8;
}
}
out
}
/// For each of `to` pixels spread over `from` (both above 0), the `from` pixels under it and the
+24 -7
View File
@@ -28,6 +28,7 @@ use vello_cpu::{Pixmap, RenderContext};
use crate::ink::Ink;
use crate::lru::{self, FrameCache};
use crate::renderer::FramePixels;
use crate::{Frame, RenderOptions, Rendered, Renderer};
/// Largest super-tile raster side (pixels).
@@ -170,15 +171,21 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 {
/// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as
/// `ink` paints them.
fn rasterize(
fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, size: (u16, u16), ink: Ink, images: (bool, bool)) -> (Pixmap, bool) {
rasterize_as(r, doc, def, (region, size), ink, images, |r, ctx| r.finish(ctx, r.raster))
}
/// [`rasterize`] of `region` into `size` pixels, with the pixels taken from the context by
/// `finish`.
fn rasterize_as<T>(
r: &mut Renderer,
doc: &Document,
def: &PatternDef,
region: Rect,
size: (u16, u16),
(region, size): (Rect, (u16, u16)),
ink: Ink,
(mark_undecoded_images, smooth_images): (bool, bool),
) -> (Pixmap, bool) {
finish: impl FnOnce(&mut Renderer, &mut RenderContext) -> T,
) -> (T, bool) {
let (w, h) = (size.0.max(1), size.1.max(1));
let mut ctx = crate::single_threaded_context(w, h);
let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9))
@@ -213,7 +220,7 @@ fn rasterize(
r.draw_arc(&mut ctx, &frame, a);
}
}
(r.finish(&mut ctx, r.raster), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
(finish(r, &mut ctx), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
}
/// Run `f` with the shared off-screen renderer (None when nested too deep: a pattern whose art
@@ -334,13 +341,23 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
/// A swatch thumbnail of pattern `name`: the tiling around the tile, fitted into `size`².
pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Rendered> {
pattern_swatch(doc, name, size)
}
/// [`render_pattern_swatch`] with the pixels in words of four bytes, as
/// [`Renderer::render_words`] returns them.
pub fn render_pattern_swatch_words(doc: &Document, name: &str, size: u32) -> Option<Rendered<Vec<u32>>> {
pattern_swatch(doc, name, size)
}
fn pattern_swatch<P: FramePixels>(doc: &Document, name: &str, size: u32) -> Option<Rendered<P>> {
let def = doc.pattern(name)?;
let (w, h) = (def.width(), def.height());
let side = w.max(h);
let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side));
let px = size.clamp(1, 1024) as u16;
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, (false, true)))?;
Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) })
let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, (region, (px, px)), Ink::Display, (false, true), P::finish))?;
Some(Rendered { width: px as u32, height: px as u32, pixels })
}
impl Renderer {
+78 -10
View File
@@ -189,9 +189,11 @@ impl Renderer {
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
self.hairline = hairline;
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
let mut pixels = P::blank(w as usize * h as usize);
downsample(&big.pixels, big.width as usize, k as usize, pixels.bytes_mut());
#[cfg(test)]
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
drop(big);
let pixels = P::from_bytes(pixels);
self.stats.micros = now().saturating_sub(start);
return Rendered { width: w, height: h, pixels };
}
@@ -455,6 +457,12 @@ impl Renderer {
self.region(doc, region, scale, opts)
}
/// [`Self::render_region_with`] with the pixels in words of four bytes, as
/// [`Self::render_words`] returns them.
pub fn render_region_with_words(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<Vec<u32>> {
self.region(doc, region, scale, opts)
}
fn region<P: FramePixels>(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<P> {
let (w, h) = region_pixels(region, scale);
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
@@ -485,6 +493,16 @@ impl Renderer {
/// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]).
pub fn render_node_with(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
self.node(doc, n, w, h, view, opts)
}
/// [`Self::render_node`] with the pixels in words of four bytes, as [`Self::render_words`]
/// returns them.
pub fn render_node_words(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<Rendered<Vec<u32>>> {
self.node(doc, n, w, h, view, &RenderOptions::default())
}
fn node<P: FramePixels>(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered<P>> {
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
self.check_plugins(doc);
self.check_symbols(doc);
@@ -499,7 +517,7 @@ impl Renderer {
/// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page
/// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`].
#[allow(clippy::too_many_arguments)]
fn node_pixels(
fn node_pixels<P: FramePixels>(
&mut self,
doc: &Document,
n: &Arc<Node>,
@@ -509,7 +527,7 @@ impl Renderer {
opts: &RenderOptions,
forced: bool,
cell: u32,
) -> Vec<u8> {
) -> P {
if opts.supersample
&& opts.anti_alias == AntiAlias::Art
&& let Some(k) = supersample_factor(u32::from(w), u32::from(h))
@@ -518,9 +536,13 @@ impl Renderer {
// `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16.
let (bw, bh) = (u32::from(w) * k, u32::from(h) * k);
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
let big: Vec<u8> = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
self.hairline = hairline;
return downsample(&big, bw as usize, bh as usize, k as usize);
let mut pixels = P::blank(usize::from(w) * usize::from(h));
downsample(&big, bw as usize, k as usize, pixels.bytes_mut());
#[cfg(test)]
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
return pixels;
}
let px = 1.0 / view.determinant().abs().sqrt().max(1e-12);
let mut ctx = single_threaded_context(w, h);
@@ -538,10 +560,10 @@ impl Renderer {
} else {
self.draw_arc(&mut ctx, &frame, n);
}
let pm = self.finish(&mut ctx, self.raster);
let pixels = P::finish(self, &mut ctx);
self.end_frame();
self.raster = raster;
group::into_bytes(pm)
pixels
}
/// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into
@@ -565,6 +587,42 @@ impl Renderer {
background: Option<[u8; 4]>,
opts: &RenderOptions,
) -> Option<Rendered> {
self.node_thumbnail(doc, n, size, background, opts)
}
/// [`Self::render_node_thumbnail`] with the pixels in words of four bytes, as
/// [`Self::render_words`] returns them.
pub fn render_node_thumbnail_words(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option<Rendered<Vec<u32>>> {
self.node_thumbnail(doc, n, size, background, &RenderOptions::default())
}
/// [`Self::render_thumbnail`] with the pixels in words of four bytes, as
/// [`Self::render_words`] returns them.
pub fn render_thumbnail_words(&mut self, doc: &Document, id: NodeId, size: u32) -> Option<Rendered<Vec<u32>>> {
self.node_thumbnail(doc, doc.node(id)?, size, None, &RenderOptions::default())
}
/// [`Self::render_node_thumbnail_with`] with the pixels in words of four bytes, as
/// [`Self::render_words`] returns them.
pub fn render_node_thumbnail_words_with(
&mut self,
doc: &Document,
n: &Node,
size: u32,
background: Option<[u8; 4]>,
opts: &RenderOptions,
) -> Option<Rendered<Vec<u32>>> {
self.node_thumbnail(doc, n, size, background, opts)
}
fn node_thumbnail<P: FramePixels>(
&mut self,
doc: &Document,
n: &Node,
size: u32,
background: Option<[u8; 4]>,
opts: &RenderOptions,
) -> Option<Rendered<P>> {
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
self.check_plugins(doc);
self.check_symbols(doc);
@@ -573,9 +631,9 @@ impl Renderer {
// A 1-pixel margin on each side, unless the thumbnail is too small to keep one.
let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6);
let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2());
let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
let mut pixels: P = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
if let Some(bg) = background {
over_background(&mut pixels, bg);
over_background(pixels.bytes_mut(), bg);
}
Some(Rendered { width: w as u32, height: w as u32, pixels })
}
@@ -605,6 +663,8 @@ pub(crate) trait FramePixels: Sized {
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self;
/// The pixels in `bytes` (four a pixel).
fn from_bytes(bytes: Vec<u8>) -> Self;
/// `pixels` transparent pixels, to be written through [`Self::bytes_mut`].
fn blank(pixels: usize) -> Self;
/// The pixels as bytes, four a pixel.
fn bytes_mut(&mut self) -> &mut [u8];
}
@@ -618,6 +678,10 @@ impl FramePixels for Vec<u8> {
bytes
}
fn blank(pixels: usize) -> Self {
vec![0; pixels * 4]
}
fn bytes_mut(&mut self) -> &mut [u8] {
self
}
@@ -646,6 +710,10 @@ impl FramePixels for Vec<u32> {
bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect()
}
fn blank(pixels: usize) -> Self {
vec![0; pixels]
}
fn bytes_mut(&mut self) -> &mut [u8] {
bytemuck::cast_slice_mut(self)
}
+92 -2
View File
@@ -1,10 +1,12 @@
//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns,
//! rendered straight into the words.
//! rendered straight into the words. Node renders, thumbnails, regions with options and pattern
//! swatches render in words the same way.
use std::cell::Cell;
use vectorcraft_color::{BlendMode as Blend, Color, Paint};
use vectorcraft_doc::{Appearance, ColorMode, Node};
use vectorcraft_doc::pattern::pattern_paint;
use vectorcraft_doc::{Appearance, ColorMode, Node, PatternDef};
use vectorcraft_geom::shapes;
use crate::group::FINISHED;
@@ -95,3 +97,91 @@ fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() {
let words = Renderer::new().render_region_words(&plain, region, 1.3, false);
assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy");
}
/// The page of [`page`] with [`square`], [`blending_group`] and a square filled with the pattern
/// "Checks" (a red square in a 20 pt tile) on it.
fn patterned() -> Document {
page(ColorMode::Rgb, |d| {
let red = rect(d, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0));
let mut def = PatternDef::new("Checks", vec![Arc::new(red)]);
def.tile = Rect::new(0.0, 0.0, 20.0, 20.0);
d.patterns.push(def);
let filled = Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0);
let filled = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 90.0, 90.0)), filled);
vec![square(d), blending_group(d), filled]
})
}
fn same_bytes(words: &Rendered<Vec<u32>>, bytes: &Rendered, what: &str) {
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the size");
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "{what}: the same bytes");
}
#[test]
fn nodes_thumbnails_and_swatches_in_words_hold_the_bytes_of_the_same_renders_in_bytes() {
let d = patterned();
let nodes = d.layers[0].children().expect("a layer").to_vec();
let view = Affine::scale(0.7) * Affine::translate((-4.0, -9.0));
let supersampled = RenderOptions { supersample: true, precise: true, image_mips: true, ..Default::default() };
for (i, n) in nodes.iter().enumerate() {
let bytes = Renderer::new().render_node(&d, n, 53, 41, view).expect("a node render");
let words = Renderer::new().render_node_words(&d, n, 53, 41, view).expect("a node render");
same_bytes(&words, &bytes, &format!("node {i}"));
for (what, background, opts) in [
("transparent", None, RenderOptions::default()),
("on white", Some([255; 4]), RenderOptions::default()),
("on a translucent color", Some([10, 200, 90, 128]), RenderOptions::default()),
("supersampled", None, supersampled.clone()),
("supersampled on white", Some([255; 4]), supersampled.clone()),
] {
let bytes = Renderer::new().render_node_thumbnail_with(&d, n, 37, background, &opts).expect("a thumbnail");
let words = Renderer::new().render_node_thumbnail_words_with(&d, n, 37, background, &opts).expect("a thumbnail");
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail, {what}"));
}
let bytes = Renderer::new().render_node_thumbnail(&d, n, 31, Some([255; 4])).expect("a thumbnail");
let words = Renderer::new().render_node_thumbnail_words(&d, n, 31, Some([255; 4])).expect("a thumbnail");
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail on white, default options"));
let bytes = Renderer::new().render_thumbnail(&d, n.id, 29).expect("a thumbnail");
let words = Renderer::new().render_thumbnail_words(&d, n.id, 29).expect("a thumbnail");
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail by id"));
}
let region = Rect::new(5.0, 15.0, 70.0, 90.0);
for (what, opts) in [("outline", RenderOptions { outline: true, ..Default::default() }), ("supersampled", supersampled)] {
let bytes = Renderer::new().render_region_with(&d, region, 1.3, &opts);
let words = Renderer::new().render_region_with_words(&d, region, 1.3, &opts);
same_bytes(&words, &bytes, &format!("the region, {what}"));
}
let bytes = render_pattern_swatch(&d, "Checks", 23).expect("a swatch");
let words = render_pattern_swatch_words(&d, "Checks", 23).expect("a swatch");
same_bytes(&words, &bytes, "the pattern swatch");
assert!(render_pattern_swatch_words(&d, "Missing", 23).is_none(), "a pattern the document lacks has no swatch");
assert!(Renderer::new().render_thumbnail_words(&d, NodeId(u64::MAX), 29).is_none(), "a node the document lacks has no thumbnail");
}
#[test]
fn nodes_thumbnails_and_swatches_in_words_are_returned_in_the_buffer_they_rendered_into() {
let d = patterned();
let n = d.layers[0].children().expect("a layer")[1].clone();
let mut r = Renderer::new();
let out = r.render_node_words(&d, &n, 40, 40, Affine::IDENTITY).expect("a node render");
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a node's words are returned without a copy");
let supersampled = RenderOptions { supersample: true, ..Default::default() };
for background in [None, Some([255; 4])] {
for (what, opts) in [("", RenderOptions::default()), (" supersampled", supersampled.clone())] {
let out = r.render_node_thumbnail_words_with(&d, &n, 48, background, &opts).expect("a thumbnail");
let at = out.pixels.as_ptr() as usize;
assert_eq!(at, finished(), "background {background:?}{what}: a thumbnail's words are returned without a copy");
}
}
let out = r.render_node_thumbnail_words(&d, &n, 48, Some([255; 4])).expect("a thumbnail");
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail on a color's words are returned without a copy");
let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &supersampled);
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a supersampled frame's words are returned without a copy");
let out = r.render_thumbnail_words(&d, n.id, 32).expect("a thumbnail");
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail's words by id are returned without a copy");
let plain = page(ColorMode::Rgb, |d| vec![square(d)]);
let out = r.render_region_with_words(&plain, Rect::new(5.0, 15.0, 70.0, 90.0), 1.3, &RenderOptions::default());
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a region's words with options are returned without a copy");
let out = render_pattern_swatch_words(&d, "Checks", 20).expect("a swatch");
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a swatch's words are returned without a copy");
}
+4 -4
View File
@@ -46,12 +46,12 @@ use cache::GlyphCache;
use cache::{CanonicalNames, GlyphColours, GlyphImages};
pub use composite::{CompositeCoverage, LentCompositeFonts};
use craft::font_catalog::Catalog;
#[cfg(test)]
pub(crate) use dirs::sfnt_of;
pub use dirs::{
PlatformFontFiles, app_font_dir, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, system_font_dirs,
user_font_dirs,
PlatformFontFiles, app_font_dir, set_app_font_dir, set_platform_font_files, set_platform_font_files_complete, set_user_font_dirs,
set_user_font_dirs_confined, system_font_dirs, user_font_dirs,
};
#[cfg(test)]
pub(crate) use dirs::{sfnt_of, uses_font_service};
use face::Instances;
pub(crate) use face::PathAlignHeights;
pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat};
+29 -3
View File
@@ -47,6 +47,22 @@ pub fn set_platform_font_files(list: PlatformFontFiles) {
let _ = list;
}
/// [`set_platform_font_files`] for a lister that lists every font the platform's font service
/// lists. [`FontDb::global`]'s scan then reads the lister's files and does not also ask the font
/// service, which opens every installed face a second time. Only the first lister set counts.
pub fn set_platform_font_files_complete(list: PlatformFontFiles) {
#[cfg(not(target_arch = "wasm32"))]
if PLATFORM_FONT_FILES.set(list).is_ok() {
LISTER_IS_COMPLETE.store(true, std::sync::atomic::Ordering::Relaxed);
}
#[cfg(target_arch = "wasm32")]
let _ = list;
}
/// Whether the lister was set with [`set_platform_font_files_complete`].
#[cfg(not(target_arch = "wasm32"))]
static LISTER_IS_COMPLETE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The most files [`platform_font_files`] takes from the lister.
#[cfg(not(target_arch = "wasm32"))]
const MAX_PLATFORM_FILES: usize = 1 << 16;
@@ -64,10 +80,20 @@ fn platform_font_files() -> Vec<PathBuf> {
Vec::new()
}
/// The catalog of [`FontDb::global`]: the platform's font folders and font service, the font
/// store, VectorCraft's own folders ([`app_dirs`]) and the files [`set_platform_font_files`] lists.
/// Whether [`system_catalog`] asks the platform's font service: not when the lister was set with
/// [`set_platform_font_files_complete`].
pub(crate) fn uses_font_service() -> bool {
#[cfg(not(target_arch = "wasm32"))]
return !LISTER_IS_COMPLETE.load(std::sync::atomic::Ordering::Relaxed);
#[cfg(target_arch = "wasm32")]
true
}
/// The catalog of [`FontDb::global`]: the platform's font folders, the platform's font service
/// ([`uses_font_service`]), the font store, VectorCraft's own folders ([`app_dirs`]) and the files
/// [`set_platform_font_files`] lists.
pub(super) fn system_catalog() -> Catalog {
let catalog = Catalog::new(FontEnv::from_process()).with_lister(Arc::new(platform_font_files));
let catalog = Catalog::new(FontEnv::from_process()).with_font_service(uses_font_service()).with_lister(Arc::new(platform_font_files));
catalog.set_app_dirs(app_dirs());
catalog
}
+2 -2
View File
@@ -49,8 +49,8 @@ pub use fontdb::{
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate,
GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat,
PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts,
app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs,
set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_platform_font_files_complete,
set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
+3 -1
View File
@@ -760,7 +760,9 @@ fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged() {
use std::sync::Mutex;
static FILES: Mutex<Vec<String>> = Mutex::new(Vec::new());
let list = |files: Vec<String>| *FILES.lock().unwrap_or_else(|e| e.into_inner()) = files;
set_platform_font_files(|| FILES.lock().unwrap_or_else(|e| e.into_inner()).clone());
assert!(crate::fontdb::uses_font_service(), "without a complete lister the scan asks the font service");
set_platform_font_files_complete(|| FILES.lock().unwrap_or_else(|e| e.into_inner()).clone());
assert!(!crate::fontdb::uses_font_service(), "with a complete lister the scan does not also ask the font service");
let file = service_font();
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let _ = std::fs::remove_file(&file);
+4 -1
View File
@@ -64,7 +64,7 @@ vectorcraft-cad = { workspace = true }
vectorcraft-eps = { workspace = true }
vectorcraft-format = { workspace = true }
egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_emoji_fonts"] }
# With egui's `bytemuck`: copies rendered rasters into egui images whole (`canvas::color_image`).
# With egui's `bytemuck`: hands rendered rasters to egui images in their own buffers (`canvas::color_image_owned`).
# `default_fonts`: egui 0.37 makes its bundled faces opt-in, and a dependency's dev-features do not
# reach our tests; `theme::install_fonts` starts from `FontDefinitions::default()`, which is empty
# without them (production would lay out tofu, and the no-interface-fonts tests would bind nothing).
@@ -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
+7
View File
@@ -181,6 +181,7 @@ impl VectorcraftApp {
multi_color: None,
global_edit_count: None,
shape_angle: None,
shape_edit_target: None,
radius_corners: None,
selected_rectangles: None,
trace_presets: None,
@@ -253,6 +254,8 @@ impl VectorcraftApp {
trace_runs: Default::default(),
concept_runs: Default::default(),
retype_runs: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
language_packs: Default::default(),
recovery: Default::default(),
closing: None,
prefs: None,
@@ -668,6 +671,7 @@ impl VectorcraftApp {
if !self.background.jobs.is_empty()
|| !self.opening.pending.is_empty()
|| !self.opening.converting.is_empty()
|| io::save::checks_pending(self)
|| plugin_runs::any_pending(self)
|| !self.placing.pending.is_empty()
|| !self.trace_runs.running.is_empty()
@@ -696,6 +700,7 @@ impl VectorcraftApp {
if self.session.poll_language_packs() {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
crate::language_packs::tick(self, ctx);
if self.session.plugins_loading() {
if self.session.poll_plugin_loads() {
ctx.request_repaint_after(std::time::Duration::from_millis(50));
@@ -768,6 +773,7 @@ impl VectorcraftApp {
&& let Some(view) = app.canvas_view()
{
chrome::isolation_bar(app, ui, view.rect);
crate::language_packs::bar(app, ui, view.rect);
}
});
}
@@ -787,6 +793,7 @@ impl VectorcraftApp {
self.handle_input(&ctx);
self.ui_frame(ui);
self.window_keys(&ctx);
io::save::after_ui(self, &ctx);
// What the canvas, a panel, a dialog or a window key changed in this pass reaches
// the plug-ins that react to it now, since an idle app draws no further frame; a
// line a handler wrote shows in the next one. The handlers' time counts toward the
+2
View File
@@ -160,6 +160,8 @@ pub struct CanvasCache {
pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>,
/// The selected live shape's angle, for (document uid, revision, kind of shape).
pub shape_angle: Option<ShapeAngleCache>,
/// The shape-wide edit target, for (document uid, revision).
pub(crate) shape_edit_target: Option<((u64, u64), egui::IdSalt)>,
/// The corners a live shape's Corner Radius field sets, as one hash, for (document uid,
/// File › Revert count, revision).
pub(crate) radius_corners: Option<((u64, u64, u64), u64)>,
+3 -1
View File
@@ -51,7 +51,9 @@ pub use fill::Fill;
use home::home;
pub use panes::{Layout as TileLayout, Panes};
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
pub(crate) use raster::{KeptFrame, color_image_owned, render_job};
#[cfg(test)]
pub(crate) use raster::{assert_handed_over, clear_handed_over};
pub(crate) use rulers::{general_lengths, stroke_lengths};
pub use selection::HoverObjectKey;
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions};
+20 -14
View File
@@ -18,25 +18,13 @@ use super::{BodyKind, in_gesture};
use crate::doc_windows::Win;
use crate::{CacheKey, VectorcraftApp};
/// The rendered raster `img` as an egui image. Both are premultiplied RGBA8, so its bytes are copied
/// over whole instead of pixel by pixel, which costs milliseconds for a canvas on a large screen.
/// A raster whose bytes don't match its size gives an empty image of that size.
pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImage {
let size = [img.width as usize, img.height as usize];
let expected = size[0].saturating_mul(size[1]).saturating_mul(4);
if expected == img.pixels.len() {
let pixels: Vec<egui::Color32> = bytemuck::cast_slice(&img.pixels).to_vec();
egui::ColorImage::new(size, pixels)
} else {
egui::ColorImage::new(size, vec![egui::Color32::TRANSPARENT; size[0].saturating_mul(size[1])])
}
}
/// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui
/// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to
/// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty
/// image of that size.
pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered<Vec<u32>>) -> egui::ColorImage {
#[cfg(test)]
HANDED_OVER.with(|p| p.set(img.pixels.as_ptr() as usize));
let size = [img.width as usize, img.height as usize];
if size[0].saturating_mul(size[1]) == img.pixels.len() {
let pixels: Vec<egui::Color32> = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec());
@@ -764,6 +752,24 @@ thread_local! {
/// frame the test finished before it lands in the wait. A test that answers the job from
/// another thread sets [`std::time::Duration::MAX`] to wait for that answer.
pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell<std::time::Duration> = const { std::cell::Cell::new(std::time::Duration::ZERO) };
/// The address of the words the last [`color_image_owned`] on this thread was given.
static HANDED_OVER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Clears what [`assert_handed_over`] checks, before the image it checks is made.
#[cfg(test)]
pub(crate) fn clear_handed_over() {
HANDED_OVER.with(|p| p.set(0));
}
/// Asserts that `image` was made by [`color_image_owned`] on this thread since
/// [`clear_handed_over`], in the words it was given: the pixels were handed over, not copied.
#[cfg(test)]
#[track_caller]
pub(crate) fn assert_handed_over(image: &egui::ColorImage, what: &str) {
let given = HANDED_OVER.with(std::cell::Cell::get);
assert!(given != 0, "{what}: the image is made from words handed over");
assert_eq!(image.pixels.as_ptr() as usize, given, "{what}: the image holds the words it was given, not a copy");
}
/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds.
+103 -4
View File
@@ -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));
@@ -1283,3 +1283,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");
}
+1 -1
View File
@@ -7400,7 +7400,7 @@ fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_in
let color = color_image_owned(frame);
assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied");
let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts);
assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels");
assert!(bytemuck::cast_slice::<Color32, u8>(&color.pixels) == bytes.pixels.as_slice(), "the image holds the frame's pixels");
assert_eq!(color.size, [256, 128]);
// A raster whose pixels don't match its size gives an empty image of that size.
let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] };
+28 -12
View File
@@ -6,10 +6,11 @@ use craft::ui::display::{Divider, Elide, Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::popover::Popover;
use craft::ui::shell::{BarGrip, OptionsBarPlace};
use craft::ui::style::SurfaceKind;
use craft::ui::text::NumberField;
use egui::Ui;
use egui::{Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
@@ -281,14 +282,17 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui) {
ranked(ui, rank::DETAIL, |ui| stroke_panel::profile_select(app, ui));
}
/// The Control bar's Opacity group: its link, which opens the Transparency panel and scrubs the field, and the
/// field, showing `opacity`. Only a selection takes the edit.
const PANEL_POPOVER_W: f32 = 260.0;
const PANEL_POPOVER_MIN_TALL: f32 = 200.0;
/// The Control bar's Opacity group: its link, which opens the Transparency panel in a popover anchored to it
/// and scrubs the field, and the field, showing `opacity`. Only a selection takes the edit.
fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected: bool) {
let label = tl!("Opacity:");
let (mut link, mut typed) = (false, None);
let target = crate::panels::transparency_target(app);
group(ui, rank::OPACITY, |ui| {
Field::new(label).side(SideLabel::new().link().scrub(true)).show(ui, |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))))
.range(0.0..=100.0)
.unit("%")
@@ -298,10 +302,19 @@ fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected:
link |= number.link;
typed = number.edit.events.committed().copied().flatten().or(typed);
});
let open_id = field.output.id.with("transparency_popover_open");
let mut open = ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
if link {
open = !open;
}
Popover::new(tl!("Transparency"), Bind::bound(&mut open)).opened_by(&field.output).show(ui, |ui, _| {
ui.scope(|ui| {
ui.set_max_width(PANEL_POPOVER_W);
crate::panels::transparency::show(app, ui);
});
});
ui.data_mut(|d| d.insert_temp(open_id, open));
});
if link {
app.ui.open_panel = Some("transparency".into());
}
if let Some(o) = typed.filter(|_| selected) {
app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok();
}
@@ -311,14 +324,17 @@ fn opacity_field(app: &mut VectorcraftApp, ui: &mut Ui, opacity: f32, selected:
/// Global Edit Options. A narrow bar leaves out Global Edit Options first, then Recolor Artwork, then the Style
/// link with its picker.
fn style_group(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut open = false;
ranked(ui, rank::GROUP, |ui| {
open |= crate::panels::option_link(tl!("Style:")).show(ui).clicked();
let link = crate::panels::option_link(tl!("Style:")).show(ui);
let tall = (ui.ctx().content_rect().height() * 0.6).max(PANEL_POPOVER_MIN_TALL);
Popover::new(tl!("Graphic Styles"), Bind::kept()).collection_body().overlay(|overlay| overlay.opened_by(&link, Trigger::Click)).show(
ui,
|ui, _| {
ui.allocate_ui(vec2(PANEL_POPOVER_W, tall), |ui| crate::panels::graphic_styles::show(app, ui));
},
);
crate::panels::graphic_styles::style_picker(app, ui);
});
if open {
app.ui.open_panel = Some("graphicStyles".into());
}
// Recolor Artwork, when the selection has colours to recolour.
let colored = app.session.active().is_some_and(|st| crate::canvas::has_colors(&st.doc, &st.selection.objects));
if colored {
+57
View File
@@ -3629,3 +3629,60 @@ fn the_control_bar_selects_similar_objects() {
bar.app().run("window.control.options", json!({"group": "objectOptions"})).unwrap();
assert!(bar.settle().find("Select Similar Objects").is_some(), "Object Options on again");
}
/// Clicking Stroke:, Opacity: or Style: on the Control bar opens its panel in a popover anchored to that link rather
/// than at the window's left edge or in the dock flyout; Stroke: in the Control bar stays independent of Properties'
/// Stroke row.
#[test]
fn control_bar_panel_links_open_anchored_popovers() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone();
app.run("select.set", json!({ "ids": [id] })).unwrap();
let mut bar = Shown::new(app, egui::vec2(2400.0, 700.0), |app, ui| {
super::control_bar(app, ui);
crate::panels::properties::show(app, ui);
});
bar.room(egui::vec2(2400.0, 700.0)).settle();
let assert_anchored = |bar: &Shown, link: &Target, content: &Target, label: &str| {
assert!(link.rect.left() > 80.0, "{label}: link {:?} sits past the left edge", link.rect);
assert!(content.rect.top() >= link.rect.bottom() - 2.0, "{label}: popover {:?} opens below {:?}", content.rect, link.rect);
assert!(
(content.rect.center().x - link.rect.center().x).abs() < 220.0 && content.rect.left() > 40.0,
"{label}: popover {:?} anchors horizontally near {:?}, not on the left side",
content.rect,
link.rect
);
assert!(bar.app().ui.open_panel.is_none(), "{label}: opens as a popover rather than a dock flyout");
};
// Stroke: opens its popover under the Control bar's link and leaves Properties' Stroke row closed.
let stroke_link = caption(&bar, "Stroke:").expect("Stroke: link");
assert!(bar.find("Dashed line").is_none(), "Stroke popover starts closed");
bar.click_on(&stroke_link).settle();
let dashed: Vec<_> = bar.fixture.by_role(Role::CHECK_BOX).into_iter().filter(|t| bar.tree().name_of(t.node) == Some("Dashed line")).collect();
assert_eq!(dashed.len(), 1, "Control bar and Properties keep separate Stroke popovers: {dashed:?}, names: {:?}", bar.names());
assert_anchored(&bar, &stroke_link, &dashed[0], "Stroke:");
bar.click_on(&stroke_link).settle();
assert!(bar.find("Dashed line").is_none(), "a second click closes the Stroke popover");
// Opacity: opens Transparency in an anchored popover.
let opacity_link = caption(&bar, "Opacity:").expect("Opacity: link");
assert!(bar.find("Isolate Blending").is_none(), "Transparency popover starts closed");
bar.click_on(&opacity_link).settle();
let isolate = bar.find("Isolate Blending").unwrap_or_else(|| panic!("Transparency popover opens: {:?}", bar.names()));
assert_anchored(&bar, &opacity_link, &isolate, "Opacity:");
bar.click_on(&opacity_link).settle();
assert!(bar.find("Isolate Blending").is_none(), "a second click closes Transparency");
// Style: opens Graphic Styles in an anchored popover.
let style_link = caption(&bar, "Style:").expect("Style: link");
assert!(bar.find("Break Link to Graphic Style").is_none(), "Graphic Styles popover starts closed");
bar.click_on(&style_link).settle();
let break_link = bar.find("Break Link to Graphic Style").unwrap_or_else(|| panic!("Graphic Styles popover opens: {:?}", bar.names()));
assert_anchored(&bar, &style_link, &break_link, "Style:");
bar.click_on(&style_link).settle();
assert!(bar.find("Break Link to Graphic Style").is_none(), "a second click closes Graphic Styles");
}
+43 -12
View File
@@ -34,7 +34,7 @@ use vectorcraft_engine::cmd::swatchlib;
use vectorcraft_engine::script::DialogAnswer;
use super::preview::LivePreview;
use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values};
use crate::panels::color::{WorkingRgb, color_of_values, gamut, gamut_of, model_values};
use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries};
use crate::panels::{color_json, srgba};
use crate::{VectorcraftApp, screen_color};
@@ -236,10 +236,10 @@ fn library_index(app: &VectorcraftApp, limit: &str) -> Option<usize> {
colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1)
}
/// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's
/// The CMYK profile of `inks` as the picker's CMYK converter, so its CMYK fields follow the document's
/// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB.
fn working_cmyk() -> Option<CmykConverter> {
let bytes = cms::icc_bytes(&cms::active().settings().cmyk).ok()?;
fn working_cmyk(inks: &cms::Cms) -> Option<CmykConverter> {
let bytes = cms::icc_bytes(&inks.settings().cmyk).ok()?;
CmykConverter::new(Arc::new(Profile::parse(&bytes).ok()?)).ok()
}
@@ -295,7 +295,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
(None, false) => "fill",
};
let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk);
let mut dialog = picker(app, key, &color, cmyk);
let mut dialog = picker(app, key, &color, cmyk, None);
// The host replaces a picker only for the same document and artboard.
if let Some((document, _, index, _)) = artboard {
dialog = dialog.instance((document, index));
@@ -327,15 +327,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's
/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks.
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog {
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color))
/// swatches and libraries, and with `cmyk` (a CMYK document) the CMYK inks. `inks`: the profiles of the
/// document the picker edits when that is not the front document; it shows a CMYK color, tests the
/// gamut and fills the CMYK fields through them. `None`: the active profiles.
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool, inks: Option<&Arc<cms::Cms>>) -> ColorPickerDialog {
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba_in(color, inks))
.eyedropper(true)
.add_to_swatches(false)
.gamut(gamut(app))
.gamut(inks.map_or_else(|| gamut(app), |i| gamut_of(i.clone())))
.working_rgb(WorkingRgb)
.swatch_view(swatch_view(app));
if cmyk && let Some(converter) = working_cmyk() {
if let Some(cms) = picker_cmyk(cmyk, inks)
&& let Some(converter) = working_cmyk(&cms)
{
dialog = dialog.cmyk(&converter);
}
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
@@ -344,6 +348,13 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPi
dialog
}
/// The color-management context whose CMYK profile the picker's CMYK fields convert through: `inks`
/// whenever given, in an RGB document too, else the active profiles in a CMYK document (`cmyk`).
/// `None`: the picker's built-in coated CMYK.
fn picker_cmyk(cmyk: bool, inks: Option<&Arc<cms::Cms>>) -> Option<Arc<cms::Cms>> {
inks.cloned().or_else(|| cmyk.then(cms::active))
}
/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`:
/// the run's own active document is in CMYK, which the session does not show between slices;
/// `profiles`: the RGB and CMYK profiles that document is assigned, which OK converts the pick through. It
@@ -352,14 +363,15 @@ pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool
let Some(dialogs) = app.dialogs() else { return };
// The given colour's own values, so that OK can tell an untouched pick from another model's.
// The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given.
let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false);
let inks = script_inks(&profiles);
let dialog = picker(app, SCRIPT_KEY, &color, cmyk, Some(&inks)).kept(model_values(&color)).web_colors_remembered(false);
let id = dialogs.with(|h| h.open(dialog));
app.color_dialogs.pickers.retain(|o| o.id != id);
let target = Target::Script { color, cmyk, profiles };
app.color_dialogs.pickers.push(Open {
id,
target,
start: srgba(&color),
start: srgba_in(&color, Some(&inks)),
keep: false,
preview: LivePreview::default(),
view: Vec::new(),
@@ -367,6 +379,25 @@ pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool
});
}
/// The color-management context whose CMYK profile a script's picker shows its CMYK fields in: the
/// script's document assigned `profiles`, which may not be the window's front document.
fn script_inks(profiles: &(Option<String>, Option<String>)) -> Arc<cms::Cms> {
cms::for_document(profiles.0.as_deref(), profiles.1.as_deref())
}
/// `color` as display sRGB: a CMYK color through the CMYK profile of `inks`, anything else as
/// [`srgba`] shows it. An RGB color keeps the active RGB profile, which the picker's RGB fields
/// ([`WorkingRgb`]) read its channel values in.
fn srgba_in(color: &Color, inks: Option<&Arc<cms::Cms>>) -> Srgba {
match (inks, color) {
(Some(inks), Color::Cmyk { .. }) => {
let [r, g, b] = inks.display_rgb(color);
Srgba::rgb(r, g, b)
}
_ => srgba(color),
}
}
/// The key of the Color Picker a script opens.
pub(crate) const SCRIPT_KEY: &str = "script";
@@ -494,3 +494,37 @@ fn the_canvas_stays_open_under_the_picker() {
step(&mut app, &ctx, vec![]);
assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the picker leaves the selection");
}
#[test]
fn a_script_picker_shows_cmyk_in_the_scripts_document_profile() {
// The front document keeps the working CMYK profile; the script's document is assigned another.
let (mut app, _ctx) = app();
assert_ne!(cms::active().settings().cmyk, cms::FOGRA52_CMYK, "the front document uses another CMYK profile");
let color = Color::Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 };
open_for_script(&mut app, color, true, (None, Some(cms::FOGRA52_CMYK.to_string())));
let open = app.color_dialogs.pickers.last().unwrap();
let [r, g, b] = cms::for_document(None, Some(cms::FOGRA52_CMYK)).display_rgb(&color);
assert_eq!(open.start, Srgba::rgb(r, g, b), "the picker shows the color through the script document's profile");
assert_ne!(open.start, srgba(&color), "the front document's profile shows the color differently");
let inks = script_inks(&(None, Some(cms::FOGRA52_CMYK.to_string())));
assert_eq!(inks.settings().cmyk, cms::FOGRA52_CMYK, "the CMYK fields and gamut use the script document's profile");
}
#[test]
fn a_script_picker_in_an_rgb_document_fills_cmyk_fields_in_the_scripts_profile() {
// An RGB document can carry its own CMYK profile; the picker's CMYK fields convert through it.
let inks = script_inks(&(None, Some(cms::FOGRA52_CMYK.to_string())));
let fields = picker_cmyk(false, Some(&inks)).map(|c| c.settings().cmyk.clone());
assert_eq!(fields.as_deref(), Some(cms::FOGRA52_CMYK), "the script document's CMYK profile, in an RGB document too");
assert!(picker_cmyk(false, None).is_none(), "the front RGB document keeps the built-in CMYK fields");
}
#[test]
fn a_script_picker_opens_an_rgb_color_as_its_rgb_fields_read_it() {
// The RGB fields read channel values in the working RGB profile, so the opening swatch matches them.
let inks = script_inks(&(Some(cms::WIDE_GAMUT_RGB.to_string()), None));
let color = Color::rgb(0.5, 0.3, 0.2);
let [r, g, b] = inks.display_rgb(&color);
assert_ne!(Srgba::rgb(r, g, b), srgba(&color), "the two RGB profiles show the color differently");
assert_eq!(srgba_in(&color, Some(&inks)), srgba(&color), "the opening color and the RGB fields use one profile");
}
@@ -349,22 +349,21 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) -
mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color());
}
}
crate::canvas::color_image(&rendered)
crate::canvas::color_image_owned(rendered)
}
/// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing.
fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize, color: Color32) {
fn mark_line(image: &mut vectorcraft_render::Rendered<Vec<u32>>, y: f32, thickness: usize, color: Color32) {
if !y.is_finite() || y < 0.0 {
return;
}
let (width, height) = (image.width as usize, image.height as usize);
let first = y as usize;
let word = u32::from_ne_bytes(color.to_array());
for row in first..first.saturating_add(thickness).min(height) {
let start = row.saturating_mul(width).saturating_mul(4);
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width.saturating_mul(4))) {
for pixel in line.as_chunks_mut::<4>().0 {
pixel.copy_from_slice(&color.to_array());
}
let start = row.saturating_mul(width);
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width)) {
line.fill(word);
}
}
}
@@ -372,7 +371,7 @@ fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize,
/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the
/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own
/// colors) into `px` pixels at `ppp` pixels per point.
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered {
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered<Vec<u32>> {
let (w, h) = px;
let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp));
let font = sample_font(f);
@@ -384,8 +383,8 @@ pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16),
let t = TextObject::point(Point::new(INSET, baseline), &sample, style);
let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t))));
let view = Affine::scale(f64::from(ppp));
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] };
RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty)
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h)] };
RENDERER.with(|r| r.borrow_mut().render_node_words(&doc, &node, w, h, view)).unwrap_or_else(empty)
}
#[cfg(test)]
@@ -477,4 +476,16 @@ mod zoom_tests {
assert_eq!(fields(&panel)["zoom"], json!(400), "canceling an older popup must not undo the later automation edit");
assert_eq!(panel.value_role("Zoom", Role::COMBO_BOX).as_deref(), Some("400%"));
}
/// The sample's image holds the pixels the sample was rendered into, with its lines drawn in.
#[test]
fn the_sample_image_is_handed_over_with_its_lines_drawn_in() {
let f = CompositeFont::new("Sample draft", "Source Sans 3", "Regular");
crate::canvas::clear_handed_over();
let image = image(&f, 100, &[Mark::Baseline], 1.0, Color32::BLACK);
crate::canvas::assert_handed_over(&image, "the sample");
let [w, _] = image.size;
let line = image.pixels.chunks(w).any(|row| row.iter().all(|p| *p == Mark::Baseline.color()));
assert!(line, "the baseline is drawn across the sample");
}
}
@@ -585,6 +585,7 @@ fn the_sample_draws_color_glyphs_in_their_colors() {
colr.size = 300.0;
f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }];
let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK);
let img = vectorcraft_render::Rendered { width: img.width, height: img.height, pixels: bytemuck::cast_slice::<u32, u8>(&img.pixels).to_vec() };
let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| {
let p = img.pixel(x, y);
p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200
+14 -2
View File
@@ -672,8 +672,8 @@ fn thumbnail(doc: &Document, art: &Node) -> egui::ColorImage {
static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new());
}
RENDERER
.with(|r| r.borrow_mut().render_node_thumbnail(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
.map_or_else(blank, |img| crate::canvas::color_image(&img))
.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
.map_or_else(blank, crate::canvas::color_image_owned)
}
/// The designs among `selection`'s rows.
@@ -909,6 +909,18 @@ mod tests {
app.run("select.set", json!({"ids": [g]})).unwrap();
}
/// A design's preview holds the pixels it was rendered into.
#[test]
fn a_designs_preview_is_handed_to_its_image_without_a_copy() {
let (app, _ctx) = app_with_design();
let doc = &app.session.active().unwrap().doc;
let design = doc.graph_designs.first().expect("the new design");
crate::canvas::clear_handed_over();
let image = super::thumbnail(doc, &design.art);
assert_eq!(image.size, [super::PREVIEW_PX as usize; 2], "the preview's size");
crate::canvas::assert_handed_over(&image, "the design's preview");
}
/// The open dialog's fields, as automation lists them.
fn fields(app: &VectorcraftApp) -> Value {
app.dialogs().unwrap().with(|host| host.open_dialogs()).last().unwrap().fields.clone().unwrap()
+1
View File
@@ -211,6 +211,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
super::find_links::pump,
);
super::missing_fonts::open_next(app);
super::text_import::open_next(app);
pumps!(app, ctx;
super::dxf_import::pump,
super::import_pdf::pump,
+121 -2
View File
@@ -1,7 +1,9 @@
//! Text Import Options: placing a text file asks how to read it (platform and character set) and
//! what to clean up (line breaks inside paragraphs, blank lines between them, runs of spaces). OK
//! places it as area type (`file.place` with `text`) and remembers the options: the next text file
//! starts from them, and is placed with them when Show Import Options is off.
//! starts from them, and is placed with them when Show Import Options is off. Opening a text file
//! (File › Open, Open Recent, a drop) asks the same: OK opens it as a new document of its text
//! (`document.open` with `text`) and remembers the options.
//!
//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]),
//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off) and `spaces` (how
@@ -45,7 +47,11 @@ const SPACES: std::ops::RangeInclusive<i64> = 2..=100;
/// Is the file `p` names (`path` or `name`) a text file?
pub fn is_text(p: &Value) -> bool {
let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default();
is_text_name(p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default())
}
/// Is the file named `name` a text file, by its extension?
fn is_text_name(name: &str) -> bool {
vectorcraft_engine::cmd::fileio::TEXT_EXTS.contains(&vectorcraft_engine::cmd::fileio::extension(name).as_str())
}
@@ -106,6 +112,60 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
json!({ "dialog": KIND })
}
/// A text file File › Open asks about: its name, bytes, path and `document.open` params.
#[derive(Clone, Debug)]
pub struct TextOpen {
name: String,
bytes: Vec<u8>,
path: Option<String>,
params: Value,
}
/// File › Open of the file `name` holding `bytes` (read from `path`) with `document.open`'s params
/// `p` asks how to read it first (true) when it is a text file that opens as text (not a PDF or
/// Affinity file named `.txt`) and `p` gives no `text` options and names no importer: OK opens it as a new document with the options and remembers them for the
/// next text file, and an error keeps the dialog open. The dialog starts from the options
/// confirmed last. While any dialog is open, the file waits its turn ([`open_next`]).
pub fn offer_open(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> bool {
if !is_text_name(name)
|| !vectorcraft_engine::cmd::place::opens_as_text(name, bytes)
|| p.get("text").is_some()
|| p.get("importer").is_some_and(|v| !v.is_null())
|| app.ui_ctx.is_none()
{
return false;
}
let file = TextOpen { name: name.to_string(), bytes: bytes.to_vec(), path, params: p.clone() };
if app.any_dialog_open() || !app.ui.text_opens.is_empty() {
app.ui.text_opens.push(file);
return true;
}
ask_open(app, file)
}
/// Asks about the next text file File › Open waits to open, once no dialog is open.
pub(crate) fn open_next(app: &mut VectorcraftApp) {
if app.ui.text_opens.is_empty() || app.any_dialog_open() {
return;
}
let file = app.ui.text_opens.remove(0);
ask_open(app, file);
}
/// Text Import Options for the text file `file` File › Open opens.
fn ask_open(app: &mut VectorcraftApp, file: TextOpen) -> bool {
let ctx = app.ui_ctx.clone().unwrap_or_default();
let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok();
open_held(app, dialog, move |app, result| {
let mut p = file.params.clone();
p["text"] = options(&result.fields);
crate::io::open_document(app, &file.name, &file.bytes, file.path.clone(), &p)?;
app.ui.text_import = p["text"].clone();
Ok(())
})
.is_some()
}
/// The `text` options a text file is placed with when Show Import Options is off: those confirmed
/// last, else `file.place`'s defaults.
pub fn last_options(app: &VectorcraftApp) -> Value {
@@ -409,4 +469,63 @@ mod tests {
assert_eq!((objects(0), objects(1)), (1, 0), "placed in the document it was dropped on");
assert_eq!(app.session.active_index(), Some(0));
}
/// File › Open of a text file asks for its import options, starting from the ones confirmed
/// last, and opens nothing until OK: OK opens a new document of its text read with them and
/// remembers them, and Cancel opens nothing. Text files opened together are asked about one at
/// a time. An RTF file opens without asking.
#[test]
fn opening_a_text_file_asks_for_the_import_options_then_opens_a_document() {
let mut app = host::app();
app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"});
let text = [b"\x93\xFA\x96\x7B\r\n".as_slice(), b"one\r\n\r\ntwo"].concat();
assert_eq!(crate::io::open_bytes(&mut app, "notes.txt", &text, None).unwrap(), Value::Null);
assert!(app.session.documents().is_empty(), "nothing opens before OK");
assert_eq!(host::fields(&app, KIND)["characterSet"], "shiftJis");
host::set(&app, KIND, "removeParagraphReturns", json!(true));
host::confirm(&mut app, KIND).unwrap();
assert!(!host::is_open(&app, KIND));
assert_eq!(app.session.documents().len(), 1);
assert_eq!(placed_text(&app).as_deref(), Some("日本\none\ntwo"), "decoded as Shift JIS, the blank line dropped");
assert_eq!(app.ui.text_import["removeParagraphReturns"], true, "remembered for the next file");
assert_eq!(app.session.doc().unwrap().title(), "notes.txt");
// Two text files opened together are asked about in turn: Cancel on the first opens
// nothing, and the second is asked about next.
crate::io::open_bytes(&mut app, "other.txt", b"three", None).unwrap();
crate::io::open_bytes(&mut app, "last.txt", b"four", None).unwrap();
assert!(host::is_open(&app, KIND));
host::cancel(&app, KIND);
let ctx = app.ui_ctx.clone().unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(app.session.documents().len(), 1, "Cancel opens nothing");
host::confirm(&mut app, KIND).unwrap();
assert_eq!((app.session.documents().len(), placed_text(&app).as_deref()), (2, Some("four")));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!host::is_open(&app, KIND), "no file is left to ask about");
let rtf = br"{\rtf1 Rich {\b words}}";
crate::io::open_bytes(&mut app, "rich.rtf", rtf, None).unwrap();
assert!(!host::is_open(&app, KIND));
assert_eq!((app.session.documents().len(), placed_text(&app).as_deref()), (3, Some("Rich words")));
}
/// A text file opened while another dialog is open waits for that dialog to close before
/// Text Import Options asks about it.
#[test]
fn a_text_file_opened_under_another_dialog_waits_for_it_to_close() {
let mut app = host::app();
let other = crate::dialogs::circle_options::open(&mut app);
let other = other["dialog"].as_str().expect("dialog kind").to_string();
assert!(host::is_open(&app, &other));
crate::io::open_bytes(&mut app, "notes.txt", b"words", None).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!host::is_open(&app, KIND), "Text Import Options waits while another dialog is open");
host::cancel(&app, &other);
crate::dialogs::host::pump(&mut app, &ctx);
assert!(host::is_open(&app, KIND), "asked once the other dialog closes");
host::confirm(&mut app, KIND).unwrap();
assert_eq!(placed_text(&app).as_deref(), Some("words"));
}
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2125,7 +2125,7 @@ fn command_ids(s: &str) -> Vec<&str> {
/// the messages each one lacks.
const COMPLETE_MESSAGES: &[&str] = &[
"cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca",
"nl", "da", "id", "bg",
"nl", "da", "id", "bg", "gu",
];
/// Crates whose error and status messages reach the status bar, the crates whose errors the
+2
View File
@@ -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;
+11 -6
View File
@@ -69,10 +69,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt
return load(app, p).map(|_| Value::Null);
}
// A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF
// drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import
// Options), unless `p` says how its layers come in.
// drawing (DXF Import Options), a text file (Text Import Options, unless `p` gives `text`) and
// a PSD file with several layers or with slices (PSD Import Options), unless `p` says how its
// layers come in.
if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None)
|| crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None)
|| crate::dialogs::text_import::offer_open(app, name, bytes, path.clone(), p)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None))
{
return Ok(Value::Null);
@@ -178,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);
@@ -513,7 +515,9 @@ fn check_import_size(path: &str, explicit: bool) -> Result<(), String> {
use std::io::Read as _;
use vectorcraft_plugins::import;
let ext = fileio::extension(path);
if !explicit && (fileio::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) {
if !explicit
&& (fileio::readable_format(&ext).is_some() || fileio::TEXT_DOCUMENT_EXTS.contains(&ext.as_str()) || import::for_extension(&ext).is_empty())
{
return Ok(());
}
if std::fs::metadata(path).map_or(true, |m| m.len() <= import::MAX_INPUT_BYTES as u64) {
@@ -676,10 +680,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
if crate::dialogs::dxf_import::convert_in_background(app, path, &bytes, Some(path.to_string()), None) {
return Ok(Value::Null);
}
// A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers
// or with slices asks first, as at once.
// A PDF with several pages or a password, a DXF drawing, a text file, or a PSD file with
// several layers or with slices asks first, as at once.
if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None)
|| crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None)
|| crate::dialogs::text_import::offer_open(app, path, &bytes, Some(path.to_string()), p)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None))
{
note_recent(app, path);
+262 -15
View File
@@ -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()));
+224
View File
@@ -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(&note) {
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");
}
}
+57
View File
@@ -0,0 +1,57 @@
//! Language packs in the window (#4936): Preferences › Language Packs lists the packs that spell-check and
//! hyphenate languages other than English, with Install and Remove, and the missing-pack bar over the canvas offers
//! the pack for a language the document's type is in. The engine does the work ([`vectorcraft_engine::packs`]):
//! installs run on its thread, and the buttons go through `proof.installPack`, `proof.removePack` and
//! `proof.packs {refresh}`, as an agent's would.
//!
//! The one step no command takes is turning on the font store's downloading (RFC-0011): the person's own click on
//! Install, Get Language Pack or Refresh List is their consent, and it turns downloading on for every Craft app. A
//! click the control channel injected never does; an agent can install once the person has turned it on.
//!
//! The web build has no font store yet (storytold/craft-libs#745): the page says so and the bar never shows.
#[cfg(target_arch = "wasm32")]
use craft::theme::variant::Tone;
use craft::ui::contract::{Show as _, ShowContainer as _};
use craft::ui::display::Text;
use craft::ui::layout_components::Stack;
#[cfg(target_arch = "wasm32")]
use craft::ui::notices::Notice;
use egui::Ui;
use crate::VectorcraftApp;
#[cfg(not(target_arch = "wasm32"))]
mod desktop;
#[cfg(not(target_arch = "wasm32"))]
pub use desktop::Runtime;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use desktop::{bar, tick};
/// The Preferences page's id (its English title), beside the categories of the engine's preference table.
pub const PAGE: &str = "Language Packs";
/// Once a frame: nothing on the web.
#[cfg(target_arch = "wasm32")]
pub(crate) fn tick(_app: &mut VectorcraftApp, _ctx: &egui::Context) {}
/// The missing-pack bar: never on the web, which can't install packs.
#[cfg(target_arch = "wasm32")]
pub(crate) fn bar(_app: &mut VectorcraftApp, _ui: &mut Ui, _area: egui::Rect) {}
/// Preferences › Language Packs: what packs are, then (on the desktop) whether downloading is on, the installed packs
/// with Remove, and the packs of the list with Install, each with its progress or its last failure.
pub(crate) fn page(app: &mut VectorcraftApp, ui: &mut Ui) {
Stack::new().show(ui, |ui, _| {
Text::new(tl!("Language packs add spelling and hyphenation for languages other than English. They are shared with the other Craft apps."))
.show(ui);
#[cfg(target_arch = "wasm32")]
{
let _ = &app;
Notice::new(Tone::Info, tl!("Language packs can't be installed in the browser yet: only English is spell-checked here.")).show(ui);
}
#[cfg(not(target_arch = "wasm32"))]
desktop::page(app, ui);
});
}
@@ -0,0 +1,425 @@
//! The desktop's Language packs: the Preferences page's list and the missing-pack bar, over the engine's packs
//! ([`vectorcraft_engine::packs`]), which the web build doesn't have.
use std::collections::{BTreeMap, BTreeSet};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Progress, Text};
use craft::ui::layout_components::Row;
use craft::ui::notices::Notice;
use craft::ui::patterns::language_packs::{
self, BarOffer, BarState, Consent, LanguagePackWords, MissingPackBar, injected, shown, shown_error, size_text,
};
use craft::ui::runtime::env::Env;
use egui::Ui;
use serde_json::json;
use vectorcraft_engine::packs::{self, Missing, Pack};
use crate::VectorcraftApp;
/// Most characters of a language's name shown (an index may name it at any length).
const MAX_NAME: usize = 40;
/// How long the bar keeps what it worked out while the document is being edited.
const MISSING_REFRESH_SECS: f64 = 1.0;
/// The window's pack state.
#[derive(Default)]
pub struct Runtime {
/// Failures of the window's own (turning downloading on, a command it ran), by locale or language tag (`""`:
/// the list), shown until the next try. The engine keeps the installs' own.
errors: BTreeMap<String, String>,
/// The keys of `errors` that say only the person can turn downloading on: dropped once it is on.
refused: BTreeSet<String>,
/// (document, pack locale or language tag) pairs whose bar was closed.
dismissed: BTreeSet<(u64, String)>,
/// The language tag whose bar asked for the list: its pack installs once the list arrives.
wanted: Option<String>,
/// The installs running when last looked at, to announce each one's end.
running: BTreeSet<String>,
/// What the bar offers for the front document, what it was worked out from, and when.
missing: Option<(MissingKey, f64, Vec<Missing>)>,
/// The index fetched last, and what it was read for (the list is read from disk, so not every frame).
index: Option<(IndexKey, Vec<Pack>)>,
}
impl Runtime {
/// Keeps `message` as the failure for `key`, in place of a refusal it had: downloading coming on drops only
/// refusals, so this one stays.
fn fail(&mut self, key: impl Into<String>, message: String) {
let key = key.into();
self.refused.remove(&key);
self.errors.insert(key, message);
}
/// Forgets the failure (or refusal) for `key`: a new try is starting.
fn clear(&mut self, key: &str) {
self.refused.remove(key);
self.errors.remove(key);
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct MissingKey {
document: u64,
revision: u64,
/// The installed packs changed.
generation: u64,
/// A fetch of the list started or ended.
refreshing: bool,
/// A fetch of the list ended (one can start and end between two frames).
index: u64,
}
/// Whether a fetch of the list was running, the fetches that ended, and the installed packs' generation.
type IndexKey = (bool, u64, u64);
/// A language as the window names it: the interface's name for a document language (`Hindi`), with the pack's own
/// name after it when that differs (`Hindi (हिन्दी)`); the pack's own name alone for a language the documents'
/// list doesn't have; the tag when there is neither.
pub(crate) fn language_name(tag: &str, own: Option<&str>) -> String {
let own = own.map(|o| shown(o, MAX_NAME)).filter(|o| !o.is_empty());
let primary = |t: &str| t.split(['-', '_']).next().unwrap_or_default().to_ascii_lowercase();
let languages = vectorcraft_doc::setup::LANGUAGES;
let known = languages
.iter()
.find(|(_, t, _)| t.eq_ignore_ascii_case(tag))
.or_else(|| languages.iter().find(|(_, t, _)| primary(t) == primary(tag)))
.map(|(name, _, _)| tl!(name).to_string());
match (known, own) {
(Some(k), Some(o)) if k != o => format!("{k} ({o})"),
(Some(k), _) => k,
(None, Some(o)) => o,
(None, None) => shown(tag, MAX_NAME),
}
}
/// What a pack provides, as the list says it.
fn provides(p: &Pack) -> String {
match (p.spelling, p.hyphenation) {
(true, true) => tl!("Spelling and hyphenation").to_string(),
(true, false) => tl!("Spelling").to_string(),
(false, true) => tl!("Hyphenation").to_string(),
(false, false) => String::new(),
}
}
/// Once a frame: announces the installs that ended, and installs the pack the bar asked the list for once it
/// arrives.
pub(crate) fn tick(app: &mut VectorcraftApp, ctx: &egui::Context) {
if !app.language_packs.refused.is_empty() && packs::backend().is_some_and(|b| b.downloads_on()) {
// Downloading came on (Refresh List, the bar, another Craft app): the refusals no longer hold.
let refused = std::mem::take(&mut app.language_packs.refused);
app.language_packs.errors.retain(|key, _| !refused.contains(key));
}
let status = packs::status();
let now: BTreeSet<String> = status.installing.iter().map(|(l, _, _)| l.clone()).collect();
let ended: Vec<String> = app.language_packs.running.difference(&now).cloned().collect();
// The installs running now, an agent's too, and the ones the window started that haven't ended.
app.language_packs.running = now;
if !ended.is_empty() {
for locale in ended {
// The status bar is a live region: the end is announced wherever focus is.
announce_end(app, &locale, status.errors.get(&locale).map(String::as_str));
}
app.language_packs.missing = None;
}
if status.refreshing {
return;
}
let Some(tag) = app.language_packs.wanted.take() else { return };
app.language_packs.index = None;
app.language_packs.missing = None;
if let Some(e) = status.errors.get("") {
let message = crate::i18n::fmt(tl!("Couldn't get the list of Language packs: {error}"), &[("error", &shown_error(e))]);
app.language_packs.fail(tag, message.clone());
app.status(message);
} else if let Some(pack) = packs::pack_for_tag(&tag, &packs::available()).cloned() {
// The person's click asked for it, and turned downloading on.
install(app, &pack.locale);
// The session already checked for work this frame. Wake it even if the install ends before the next check.
ctx.request_repaint();
} else {
let name = language_name(&tag, None);
app.status(crate::i18n::fmt(tl!("There is no Language pack for {language} yet."), &[("language", &name)]));
}
}
/// Handles the shared consent decision and remembers which messages are only temporary refusals.
fn consent(app: &mut VectorcraftApp, ui: &Ui, injected: bool, key: &str) -> bool {
app.language_packs.clear(key);
let Some(backend) = packs::backend() else { return false };
let decision = language_packs::consent(backend.downloads_on(), injected, packs::enable_downloads);
if let Some(message) = decision.message(&Env::of(ui).words::<LanguagePackWords>()) {
app.language_packs.fail(key, message);
if decision == Consent::Refused {
app.language_packs.refused.insert(key.to_string());
}
}
decision.is_on()
}
/// `proof.installPack` for `locale`; a refusal is kept for its row. An install that started is watched from now on,
/// so its end is announced even when it ends before the next frame looks; one that is done already is announced now.
fn install(app: &mut VectorcraftApp, locale: &str) {
app.language_packs.clear(locale);
match app.run("proof.installPack", json!({ "locale": locale })) {
Ok(r) if r["installed"] == true => announce_end(app, locale, None),
Ok(_) => {
app.language_packs.running.insert(locale.to_string());
}
Err(e) => {
app.language_packs.fail(locale.to_string(), shown_error(&e));
announce_end(app, locale, Some(&e));
}
}
app.language_packs.missing = None;
}
/// Says in the status bar, a live region, that the install of `locale` ended: installed, or its `error`.
fn announce_end(app: &mut VectorcraftApp, locale: &str, error: Option<&str>) {
let own = packs::installed().into_iter().find(|i| i.locale == locale).map(|i| i.name);
let name = language_name(locale, own.as_deref());
let message = match error {
Some(e) => {
crate::i18n::fmt(tl!("Couldn't install the {language} Language pack: {error}"), &[("language", &name), ("error", &shown_error(e))])
}
None => crate::i18n::fmt(tl!("The {language} Language pack is installed."), &[("language", &name)]),
};
app.status(message);
}
/// Removes through `proof.removePack`; a failure is kept for its row and announced.
fn remove(app: &mut VectorcraftApp, locale: &str) {
app.language_packs.clear(locale);
let own = packs::installed().into_iter().find(|p| p.locale == locale).map(|p| p.name);
let name = language_name(locale, own.as_deref());
let message = match app.run("proof.removePack", json!({ "locale": locale })) {
Ok(_) => crate::i18n::fmt(tl!("The {language} Language pack is removed."), &[("language", &name)]),
Err(e) => {
let error = shown_error(&e);
app.language_packs.fail(locale.to_string(), error.clone());
crate::i18n::fmt(tl!("Couldn't remove the {language} Language pack: {error}"), &[("language", &name), ("error", &error)])
}
};
app.status(message);
app.language_packs.missing = None;
}
/// `proof.packs {refresh: true}` (fetching runs on the engine's thread); a refusal is kept under `key` → whether
/// the fetch started.
fn refresh(app: &mut VectorcraftApp, key: &str) -> bool {
app.language_packs.index = None;
match app.run("proof.packs", json!({ "refresh": true })) {
Ok(_) => true,
Err(e) => {
app.language_packs.fail(key.to_string(), shown_error(&e));
false
}
}
}
/// The index fetched last, read again only when a fetch starts or ends or the installed packs change.
fn index(app: &mut VectorcraftApp) -> Vec<Pack> {
let key = (packs::status().refreshing, packs::index_generation(), packs::generation());
if let Some((k, list)) = &app.language_packs.index
&& *k == key
{
return list.clone();
}
let list = packs::available();
app.language_packs.index = Some((key, list.clone()));
list
}
/// The failure to show for `locale` (`""`: the list): the window's own, else the engine's last.
fn error_of(app: &VectorcraftApp, errors: &BTreeMap<String, String>, locale: &str) -> Option<String> {
app.language_packs.errors.get(locale).cloned().or_else(|| errors.get(locale).map(|e| shown_error(e)))
}
/// The share of an install done, from its bytes (`total` 0: not known yet).
fn fraction(done: u64, total: u64) -> f32 {
if total == 0 { 0.0 } else { (done.min(total) as f64 / total as f64) as f32 }
}
/// "Installing… 40%" for an install's bytes.
fn installing_text(done: u64, total: u64) -> String {
let percent = (fraction(done, total) * 100.0).round().to_string();
crate::i18n::fmt(tl!("Installing… {percent}%"), &[("percent", &percent)])
}
/// The desktop part of Preferences › Language Packs ([`super::page`]).
pub(super) fn page(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(backend) = packs::backend() else {
Notice::new(Tone::Warn, tl!("Language packs aren't available: there is no font store folder for this user.")).show(ui);
return;
};
let injected = injected(ui.ctx());
let status = packs::status();
let list = index(app);
let installed = packs::installed();
if !backend.downloads_on() {
Text::new(tl!("Downloading is off. Install or Refresh List turns it on, for every Craft app.")).show(ui);
}
if let Some(test) = backend.index_override() {
Notice::new(Tone::Warn, crate::i18n::fmt(tl!("Packs come from a test list: {source}"), &[("source", &shown_error(&test))])).show(ui);
}
let mut refresh_clicked = false;
Row::new().wrap(true).show(ui, |ui, _| {
refresh_clicked |= Button::new(tl!("Refresh List")).enabled(!status.refreshing).show(ui).clicked();
if status.refreshing {
Text::new(tl!("Getting the list of languages…")).show(ui);
}
});
if let Some(e) = error_of(app, &status.errors, "") {
let message = crate::i18n::fmt(tl!("Couldn't get the list of Language packs: {error}"), &[("error", &e)]);
Notice::new(Tone::Bad, message).announce(Politeness::Assertive).show(ui);
}
// The installed packs, whether or not the list has them (another app may have installed one from a newer list).
Text::new(tl!("Installed")).show(ui);
if installed.is_empty() {
Text::new(tl!("No Language packs are installed.")).show(ui);
}
let mut remove_clicked: Option<String> = None;
for pack in &installed {
let name = language_name(&pack.locale, Some(&pack.name));
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(name.clone()).show(ui);
Text::new(shown(&pack.licence, MAX_NAME)).show(ui);
if Button::new(tl!("Remove")).show(ui).clicked() {
remove_clicked = Some(pack.locale.clone());
}
});
if let Some(e) = error_of(app, &status.errors, &pack.locale) {
Notice::new(Tone::Bad, e).announce(Politeness::Assertive).show(ui);
}
}
Text::new(tl!("Available")).show(ui);
if list.is_empty() && !status.refreshing {
Text::new(tl!("The list of Language packs hasn't been fetched yet: Refresh List gets it.")).show(ui);
}
let mut install_clicked: Option<String> = None;
for pack in list.iter().filter(|p| !installed.iter().any(|i| i.locale == p.locale)) {
let name = language_name(&pack.locale, Some(&pack.name));
let running = status.installing.iter().find(|(l, _, _)| *l == pack.locale).map(|(_, d, t)| (*d, *t));
let details: Vec<String> =
[size_text(ui, pack.size), provides(pack), shown(&pack.licence, MAX_NAME)].into_iter().filter(|s| !s.is_empty()).collect();
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(name.clone()).show(ui);
Text::new(details.join(" · ")).show(ui);
match running {
Some((done, total)) => {
Progress::new(fraction(done, total)).show(ui);
Text::new(installing_text(done, total)).show(ui);
}
None => {
if Button::new(tl!("Install")).show(ui).clicked() {
install_clicked = Some(pack.locale.clone());
}
}
}
});
if let Some(e) = error_of(app, &status.errors, &pack.locale) {
Notice::new(Tone::Bad, e).announce(Politeness::Assertive).show(ui);
}
}
if refresh_clicked && consent(app, ui, injected, "") {
refresh(app, "");
}
if let Some(locale) = remove_clicked {
remove(app, &locale);
}
if let Some(locale) = install_clicked
&& consent(app, ui, injected, &locale)
{
install(app, &locale);
}
}
/// What the bar offers for the front document, worked out again when the document, the installed packs or the
/// list change (at most once a [`MISSING_REFRESH_SECS`] while the document is being edited).
fn missing(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Missing> {
let now = ctx.input(|i| i.time);
let Some(st) = app.session.active() else { return Vec::new() };
let key = MissingKey {
document: st.uid,
revision: st.revision,
generation: packs::generation(),
refreshing: packs::status().refreshing,
index: packs::index_generation(),
};
if let Some((k, at, m)) = &app.language_packs.missing {
let only_edited = k.document == key.document && k.generation == key.generation && k.refreshing == key.refreshing && k.index == key.index;
if *k == key {
return m.clone();
}
let age = now - *at;
if only_edited && age < MISSING_REFRESH_SECS {
// Stale for an edit: a frame comes once it may be worked out again, even with no input by then.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((MISSING_REFRESH_SECS - age).max(0.0)));
return m.clone();
}
}
let m = vectorcraft_engine::cmd::packs::missing(&app.session);
app.language_packs.missing = Some((key, now, m.clone()));
m
}
/// The key a bar is closed under: its pack's locale, else (before the list) its language tag.
fn offer_key(m: &Missing) -> String {
m.pack.as_ref().map_or_else(|| m.tag.clone(), |p| p.locale.clone())
}
/// The offer the bar shows for the front document: the first language missing a pack whose bar wasn't closed.
fn shown_offer(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option<Missing> {
packs::backend()?;
let document = app.session.active()?.uid;
missing(app, ctx).into_iter().find(|m| {
let closed = |key: String| app.language_packs.dismissed.contains(&(document, key));
!closed(offer_key(m)) && !closed(m.tag.clone())
})
}
/// The missing-pack bar at the foot of the canvas `area`: "<Language> spelling and hyphenation need a Language
/// pack.", with Install (and the size) when the list has the pack, else Get Language Pack, which fetches the list
/// and then installs it. Closing it hides it for that language in this document.
pub(crate) fn bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
let Some(offer) = shown_offer(app, &ui.ctx().clone()) else { return };
let Some(document) = app.session.active().map(|st| st.uid) else { return };
let status = packs::status();
let name = language_name(&offer.tag, offer.pack.as_ref().map(|p| p.name.as_str()));
let message = crate::i18n::fmt(tl!("{language} spelling and hyphenation need a Language pack."), &[("language", &name)]);
let key = offer_key(&offer);
let running = status.installing.iter().find(|(l, _, _)| *l == key).map(|(_, d, t)| (*d, *t));
let fetching = offer.pack.is_none() && (status.refreshing || app.language_packs.wanted.is_some());
let error = error_of(app, &status.errors, &key);
let bar_offer = offer.pack.as_ref().map_or(BarOffer::Get, |pack| BarOffer::install(pack.size));
let state = match running {
Some((done, total)) => BarState::installing(done, total),
None if fetching => BarState::Fetching,
None => BarState::Idle,
};
// A child that allocates nothing in the canvas, at its foot and clear of the isolation bar.
let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area.shrink(8.0)).layout(egui::Layout::bottom_up(egui::Align::Center)));
let response = MissingPackBar::new(message, bar_offer).state(state).error(error).show(&mut bar_ui);
if response.dismissed {
app.language_packs.dismissed.insert((document, key.clone()));
}
if response.clicked && consent(app, &bar_ui, response.injected, &key) {
match &offer.pack {
Some(p) => install(app, &p.locale),
None => {
if refresh(app, &key) {
app.language_packs.wanted = Some(offer.tag.clone());
}
}
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,406 @@
//! Preferences › Language Packs and the missing-pack bar, over a stand-in for the font store. The packs backend is
//! the whole process's, and with one set the bar shows over any document in a language without a dictionary, so
//! each test that sets it runs in a process of its own ([`crate::testing::in_own_process`]).
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use egui::accesskit::TreeUpdate;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect};
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_engine::packs::{self, Backend, Cancel, Pack};
use super::*;
use crate::Services;
/// A stand-in for the font store: it lists a Konkani pack once the list was fetched (or from the start), and installs
/// it by writing its files. Konkani: no system has a Hunspell dictionary for it, so what the bar offers doesn't
/// depend on the machine.
struct Fake {
dir: PathBuf,
network: AtomicBool,
fetched: AtomicBool,
install_gate: Mutex<Option<mpsc::Receiver<()>>>,
}
impl Fake {
fn new(name: &str, fetched: bool) -> Arc<Fake> {
let dir = std::env::temp_dir().join(format!("vc-ui-packs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let fake = Arc::new(Fake { dir, network: AtomicBool::new(false), fetched: AtomicBool::new(fetched), install_gate: Mutex::default() });
packs::set_backend(Some(fake.clone()));
fake
}
fn downloads(&self) -> bool {
self.network.load(Ordering::Relaxed)
}
}
impl Drop for Fake {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn konkani() -> Pack {
Pack {
locale: "kok".into(),
name: "कोंकणी".into(),
size: 2_400_000,
licence: "MIT".into(),
class: "Embeddable".into(),
spelling: true,
hyphenation: true,
}
}
/// Writes a small Konkani pack into `packs/kok`, laid out as the font store unpacks one.
fn write_konkani_pack(packs: &Path) {
let dir = packs.join("kok");
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
std::fs::write(dir.join("pack.toml"), "locale = \"kok\"\nname = \"कोंकणी\"\nlicence = \"MIT\"\n").unwrap();
std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap();
std::fs::write(dir.join("spelling.aff"), "SET UTF-8\n").unwrap();
std::fs::write(dir.join("spelling.dic"), "1\nघर\n").unwrap();
}
impl Backend for Fake {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
self.downloads()
}
fn cached_index(&self) -> Vec<Pack> {
if self.fetched.load(Ordering::Relaxed) { vec![konkani()] } else { Vec::new() }
}
fn fetch_index(&self, _: &Cancel) -> Result<Vec<Pack>, String> {
assert!(self.downloads(), "a fetch only once downloading is on");
self.fetched.store(true, Ordering::Relaxed);
Ok(self.cached_index())
}
fn install(&self, locale: &str, _: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
assert!(self.downloads(), "an install only once downloading is on");
assert_eq!(locale, "kok");
let gate = self.install_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.recv_timeout(Duration::from_secs(10)).map_err(|e| e.to_string())?;
}
progress(1, 1);
write_konkani_pack(&self.dir);
Ok(())
}
fn remove(&self, locale: &str) -> Result<(), String> {
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
}
fn enable_downloads(&self) -> Result<(), String> {
self.network.store(true, Ordering::Relaxed);
Ok(())
}
}
/// Takes the backend away when the test ends, also when it failed.
struct NoBackend;
impl Drop for NoBackend {
fn drop(&mut self) {
packs::run_in_background(false);
packs::set_backend(None);
}
}
fn app() -> VectorcraftApp {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()))
}
/// One frame of the whole app, as the hosts run it → its accessibility tree.
fn frame(a: &mut VectorcraftApp, events: Vec<Event>) -> TreeUpdate {
let ctx = a.ui_ctx.clone().expect("a window context");
let time = ctx.input(|i| i.time) + 0.1;
let raw = RawInput {
events,
time: Some(time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(1400.0, 900.0))),
focused: true,
..Default::default()
};
crate::testing::app_frame(a, &ctx, raw).platform_output.accesskit_update.expect("an accessibility tree")
}
/// Frames until no install or fetch of the list runs and none waits to start (the bar's wanted pack), then one more,
/// whose tick announces what ended.
fn idle(a: &mut VectorcraftApp) {
let start = std::time::Instant::now();
loop {
frame(a, vec![]);
let status = packs::status();
if status.installing.is_empty() && !status.refreshing && a.language_packs.wanted.is_none() {
break;
}
assert!(start.elapsed() < std::time::Duration::from_secs(10), "the pack work never ended");
std::thread::sleep(std::time::Duration::from_millis(5));
}
frame(a, vec![]);
}
/// [`idle`], then frames until the layout holds still → the last one's tree.
fn settled(a: &mut VectorcraftApp) -> TreeUpdate {
idle(a);
for _ in 0..5 {
frame(a, vec![]);
}
frame(a, vec![])
}
fn labels(tree: &TreeUpdate) -> Vec<String> {
tree.nodes.iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect()
}
fn has(tree: &TreeUpdate, part: &str) -> bool {
labels(tree).iter().any(|l| l.contains(part))
}
/// The centre of the control named `label` exactly (Install, not the Installed heading).
fn spot(tree: &TreeUpdate, label: &str) -> Option<Pos2> {
spot_where(tree, |l| l == label)
}
/// The centre of the control whose name starts with `start` (`Install (` and the size).
fn spot_starting(tree: &TreeUpdate, start: &str) -> Option<Pos2> {
spot_where(tree, |l| l.starts_with(start))
}
fn spot_where(tree: &TreeUpdate, named: impl Fn(&str) -> bool) -> Option<Pos2> {
let (_, node) = tree.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| named(l.trim())) && n.bounds().is_some())?;
let b = node.bounds()?;
Some(Pos2::new((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5))
}
/// The person's own click at `at` (not the control channel's).
fn click(a: &mut VectorcraftApp, at: Pos2) {
frame(a, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(a, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
idle(a);
}
/// An agent's click on the control named `name`, through the control channel.
fn agent_click(a: &mut VectorcraftApp, name: &str) {
let ctx = a.ui_ctx.clone().expect("a window context");
let (request, _reply) = craft::automation::ControlRequest::new("ui.click", json!({"control": {"name": name}}));
let _ = crate::control::handle(a, &ctx, &request);
for _ in 0..3 {
frame(a, vec![]);
}
idle(a);
}
fn installed() -> Vec<String> {
packs::installed().into_iter().map(|p| p.locale).collect()
}
/// A document with type in Konkani.
fn konkani_document(a: &mut VectorcraftApp) {
a.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = a.run("text.create", json!({"x": 10, "y": 50, "text": "घर"})).unwrap()["id"].clone();
a.run("text.setFormat", json!({"ids": [id], "language": "Konkani"})).unwrap();
}
#[test]
fn the_page_installs_and_removes_a_pack_on_the_persons_click() {
if !crate::testing::in_own_process("language_packs::desktop::tests::the_page_installs_and_removes_a_pack_on_the_persons_click") {
return;
}
let _none = NoBackend;
let fake = Fake::new("page", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("language packs"));
let tree = settled(&mut a);
assert!(has(&tree, "Konkani (कोंकणी)"), "the pack is listed by name: {:?}", labels(&tree));
assert!(has(&tree, "Spelling and hyphenation"), "with what it provides");
assert!(has(&tree, "Downloading is off"), "and says downloading is off");
let install = spot(&tree, "Install").expect("an Install button");
click(&mut a, install);
assert!(fake.downloads(), "the person's click turned downloading on");
assert_eq!(installed(), ["kok"]);
assert!(a.ui.status.contains("installed"), "the end is announced: {}", a.ui.status);
let tree = settled(&mut a);
assert!(!has(&tree, "Downloading is off"));
let remove = spot(&tree, "Remove").expect("a Remove button for the installed pack");
click(&mut a, remove);
assert!(installed().is_empty(), "removed");
assert!(spot(&settled(&mut a), "Install").is_some(), "the pack can be installed again");
}
#[test]
fn a_faked_click_never_turns_on_downloading() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_faked_click_never_turns_on_downloading") {
return;
}
let _none = NoBackend;
let fake = Fake::new("agent", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("Language Packs"));
settled(&mut a);
agent_click(&mut a, "Install");
assert!(!fake.downloads(), "an injected click is no consent");
assert!(installed().is_empty(), "nothing installed");
assert!(has(&settled(&mut a), "Only you can turn on downloading"), "the row says why");
// Once the person turned it on, the refusal goes, and an agent installs.
fake.enable_downloads().unwrap();
assert!(!has(&settled(&mut a), "Only you can turn on downloading"), "the refusal no longer holds");
agent_click(&mut a, "Install");
assert_eq!(installed(), ["kok"]);
}
/// A failure that took a refusal's place is a failure: downloading coming on drops refusals only.
#[test]
fn a_failure_after_a_refusal_outlasts_downloading_coming_on() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_failure_after_a_refusal_outlasts_downloading_coming_on") {
return;
}
let _none = NoBackend;
let fake = Fake::new("refused-then-failed", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("Language Packs"));
settled(&mut a);
agent_click(&mut a, "Install");
assert!(has(&settled(&mut a), "Only you can turn on downloading"), "refused first");
// Removing a pack that isn't installed fails under the same locale.
remove(&mut a, "kok");
let failure = a.language_packs.errors.get("kok").cloned().expect("the removal's failure");
assert!(!failure.contains("Only you can turn on downloading"), "{failure}");
fake.enable_downloads().unwrap();
settled(&mut a);
assert_eq!(a.language_packs.errors.get("kok"), Some(&failure), "the failure stays once downloading is on");
}
#[test]
fn immediate_pack_errors_reach_the_status_bar() {
if !crate::testing::in_own_process("language_packs::desktop::tests::immediate_pack_errors_reach_the_status_bar") {
return;
}
let _none = NoBackend;
let _fake = Fake::new("immediate-errors", true);
let mut a = app();
// The engine rejects the install before starting a worker because downloading is off.
install(&mut a, "kok");
let install_error = &a.language_packs.errors["kok"];
assert!(a.ui.status.contains("Couldn't install") && a.ui.status.contains(install_error), "{}", a.ui.status);
assert!(packs::status().installing.is_empty());
// The backend rejects removal synchronously because the pack does not exist.
remove(&mut a, "kok");
let remove_error = &a.language_packs.errors["kok"];
assert!(a.ui.status.contains("Couldn't remove") && a.ui.status.contains(remove_error), "{}", a.ui.status);
}
#[test]
fn a_deferred_install_schedules_its_completion_frame() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_deferred_install_schedules_its_completion_frame") {
return;
}
let _none = NoBackend;
let fake = Fake::new("deferred-repaint", false);
fake.enable_downloads().unwrap();
packs::run_in_background(true);
let (finish, gate) = mpsc::channel();
*fake.install_gate.lock().unwrap() = Some(gate);
let mut a = app();
let ctx = a.ui_ctx.clone().expect("a window context");
// Tick the host without drawing widgets, which can independently ask for repaints.
let tick = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
out.textures_delta.clear();
out.viewport_output[&egui::ViewportId::ROOT].repaint_delay
};
for _ in 0..3 {
tick(&mut a);
}
assert_eq!(tick(&mut a), Duration::MAX, "the idle host does not request a frame");
// The bar's request is pending when the fetch finishes and the host next ticks.
assert!(refresh(&mut a, "kok"));
a.language_packs.wanted = Some("kok".into());
wait_for_pack_worker(|| !packs::status().refreshing);
let repaint_delay = tick(&mut a);
assert!(!packs::status().installing.is_empty(), "the deferred install started during the tick");
assert!(repaint_delay < Duration::MAX, "the host must wake with no further input");
finish.send(()).unwrap();
wait_for_pack_worker(|| packs::status().installing.is_empty());
frame(&mut a, vec![]);
assert_eq!(installed(), ["kok"]);
assert!(a.ui.status.contains("is installed"), "the scheduled frame announces completion: {}", a.ui.status);
}
fn wait_for_pack_worker(done: impl Fn() -> bool) {
let start = Instant::now();
while !done() {
assert!(start.elapsed() < Duration::from_secs(10), "the pack worker did not finish");
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn the_bar_gets_the_pack_for_the_documents_language() {
if !crate::testing::in_own_process("language_packs::desktop::tests::the_bar_gets_the_pack_for_the_documents_language") {
return;
}
let _none = NoBackend;
// No list yet: the bar offers the language alone, and its button gets the list, then the pack.
let fake = Fake::new("bar", false);
let mut a = app();
konkani_document(&mut a);
let tree = settled(&mut a);
assert!(has(&tree, "Konkani spelling and hyphenation need a Language pack."), "{:?}", labels(&tree));
let get = spot(&tree, "Get Language Pack").expect("the bar's button");
click(&mut a, get);
let tree = settled(&mut a);
assert!(fake.downloads(), "the person's click turned downloading on");
assert_eq!(installed(), ["kok"], "the list came, then the pack");
assert!(!has(&tree, "need a Language pack"), "the bar is gone once the language spells: {:?}", labels(&tree));
}
#[test]
fn closing_the_bar_hides_it_for_that_document() {
if !crate::testing::in_own_process("language_packs::desktop::tests::closing_the_bar_hides_it_for_that_document") {
return;
}
let _none = NoBackend;
let _fake = Fake::new("close", true);
let mut a = app();
konkani_document(&mut a);
let tree = settled(&mut a);
assert!(spot_starting(&tree, "Install (").is_some(), "the bar offers the pack with its size: {:?}", labels(&tree));
let close = ["Dismiss", "Close"].iter().find_map(|l| spot(&tree, l)).unwrap_or_else(|| panic!("the bar's close button: {:?}", labels(&tree)));
click(&mut a, close);
assert!(!has(&settled(&mut a), "need a Language pack"), "closed for this document");
konkani_document(&mut a);
assert!(has(&settled(&mut a), "need a Language pack"), "another document in the language offers it again");
assert!(installed().is_empty(), "nothing installed without a click");
}
/// Text from the index isn't ours to trust: control, bidi and tag characters are taken out and it is cut short.
#[test]
fn index_text_is_shown_without_hidden_characters() {
let hostile = "Nederlands\u{202E}lmth.exe\u{E0041}\u{200B}\n";
let shown = language_name("zz", Some(hostile));
assert!(!shown.chars().any(|c| c.is_control() || ('\u{202A}'..='\u{202E}').contains(&c) || ('\u{E0000}'..='\u{E007F}').contains(&c)));
assert!(shown.starts_with("Nederlands"));
assert!(language_name("zz", Some(&"x".repeat(100))).chars().count() <= 40, "cut short");
}
+4
View File
@@ -56,6 +56,7 @@ pub mod icon_data;
pub mod icons;
pub mod io;
pub mod keymap;
pub mod language_packs;
pub mod layout_migration;
pub mod menus;
pub mod opening;
@@ -270,6 +271,9 @@ pub struct VectorcraftApp {
pub concept_runs: panels::concept_vector::ConceptRuns,
/// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]).
pub retype_runs: retype_runs::RetypeRuns,
/// Language packs: the Preferences page's and the missing-pack bar's state ([`language_packs`]). The web has none.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) language_packs: language_packs::Runtime,
/// Data Recovery's timer and startup question ([`recovery`]).
pub recovery: recovery::Timer,
/// The Close, Close All or Quit in progress, which asks about each unsaved document in turn.
+54 -3
View File
@@ -310,14 +310,27 @@ fn role(title: &str) -> MenuRole {
/// The hash of what the catalog's rows depend on, which moves its generation: `plays` are the
/// actions' function keys, a row each, `type_keys` the chords the Type tool's commands take and `tools` the set the
/// tool rows' icons come from.
/// tool rows' icons come from. The rows the scripts and the fonts add are compared as rows ([`CatalogInputs`]) and
/// hashed into the catalog's generation as rows ([`rows_generation`]), so a new listing or font scan that leaves them
/// as they were keeps the catalog and the window's keymap.
fn generation(listed: &Listed, plays: &[(String, craft::keymap::Chord)], type_keys: &[(&str, Vec<Binding>)], tools: ToolIcons) -> u64 {
let mut h = DefaultHasher::new();
(crate::i18n::current().code(), plugin_revision(), crate::scripts_menu::revision(), vectorcraft_text::FontDb::global().generation()).hash(&mut h);
(crate::i18n::current().code(), plugin_revision()).hash(&mut h);
(listed, plays, type_keys, tools).hash(&mut h);
h.finish()
}
/// The catalog's generation: `base` ([`generation`]) with each row's key, label and kind, so it moves when a row comes,
/// goes or is renamed, and not when a menu shows or hides an item the rows already had.
fn rows_generation(base: u64, defs: &[CommandDef]) -> u64 {
let mut h = DefaultHasher::new();
base.hash(&mut h);
for def in defs {
(def.command.key(), &def.label, &def.kind).hash(&mut h);
}
h.finish()
}
/// Hashes the names of the saved workspaces and the custom toolbars, which the Window menu lists as rows.
fn hash_listed_names(ui: &UiState, h: &mut DefaultHasher) {
for w in &ui.workspaces.set.saved {
@@ -476,7 +489,8 @@ fn catalog_defs(inputs: &CatalogInputs) -> (Vec<CommandDef>, HashSet<String>) {
fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft::keymap::Chord)], defs: Vec<CommandDef>) -> Option<AppCatalog> {
let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides);
let (defs, linked_keys) = without_linked(defs);
match AppCatalog::new(defs, generation(listed, plays, &type_keys, ToolIcons::of(&app.session.prefs))) {
let generation = rows_generation(generation(listed, plays, &type_keys, ToolIcons::of(&app.session.prefs)), &defs);
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
// While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it,
// and the Type tool's commands run while it types.
@@ -805,6 +819,43 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
}
/// A new Scripts revision that leaves the menu's rows as they were (the note before the first listing, or a read
/// that finds the same scripts) lays the menus out again and keeps the catalog, so the window's keymap is not
/// built again. The fonts and plug-ins are held steady against tests running alongside, and the steps run again,
/// at most 20 times, until the shortcut editor's snapshot (which a test switching languages replaces) held still
/// through them, starting from the snapshot the app's catalog was built from.
#[test]
fn a_scripts_revision_with_the_same_rows_keeps_the_catalog() {
let fonts = vectorcraft_text::FontDb::global();
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
let snapshot = snapshot_addr;
for _ in 0..20 {
let (mut app, ctx) = app_with_document();
refresh(&mut app, &ctx);
// The snapshot the app's catalog was built from, not the shared one, which another thread may have
// replaced since.
let Some(before) = app.menus.rows.as_ref().map(|r| std::sync::Arc::as_ptr(&r.inputs.snapshot).addr()) else {
panic!("the first refresh made the catalog's rows");
};
let (rebuilds, builds, generation) = (app.menus.rebuilds, CATALOG_BUILDS.get(), app.menus.catalog_generation());
crate::scripts_menu::bump_revision();
refresh(&mut app, &ctx);
if snapshot() != before {
continue;
}
assert_eq!(app.menus.rebuilds, rebuilds + 1, "the new revision lays the menus out again");
assert_eq!(CATALOG_BUILDS.get(), builds, "the catalog's rows are not made again");
assert_eq!(app.menus.catalog_generation(), generation, "the catalog, which the keymap is built from, stays");
return;
}
panic!("the shortcut editor's snapshot changed during each of 20 tries");
}
/// The address of the shortcut editor's current snapshot.
fn snapshot_addr() -> usize {
std::sync::Arc::as_ptr(&crate::shortcut_editor::snapshot()).addr()
}
/// A new window keymap with nothing else changed (the framework builds the first one after the first frame's
/// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus
/// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held
+4 -2
View File
@@ -172,7 +172,7 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
/// How the menus show item `id` (params `p`) now: (enabled, checked: `Some` for an item that is on
/// or off), or `None` while they leave it out: an empty slot ([`hidden_when_disabled`]), an item
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
/// ([`east_asian_hidden`]).
/// ([`east_asian_hidden`]), or a disabled type conversion.
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
shown_state_with(app, id, p, &mut |id| why_off(app, id))
}
@@ -194,7 +194,9 @@ pub(crate) fn shown_state_with(
})
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
// Keep conversion labels in the catalog while leaving unavailable rows out of the Type menu.
let hide_disabled = hidden_when_disabled(id) || matches!(id, "type.convertToAreaType" | "type.convertToPointType");
if (!en && hide_disabled) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
return None;
}
Some((en, checked(app, id, p)))
+60
View File
@@ -164,6 +164,66 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() {
assert_eq!(menu.toggled("Pixel Snapping Options…"), None);
}
#[test]
fn type_menu_offers_only_conversions_that_apply_to_selected_text() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
model::refresh(app, ui.ctx());
craft::menu::MenuBarUi::new(&app.menus.laid).show(ui);
}
const TO_AREA: &str = "Convert To Area Type";
const TO_POINT: &str = "Convert To Point Type";
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
let point = app.run("text.create", json!({"x": 20, "y": 40, "text": "Point type"})).unwrap()["id"].clone();
let area = app.run("text.create", json!({"x": 20, "y": 100, "text": "Area type", "area": {"width": 120, "height": 60}})).unwrap()["id"].clone();
let rectangle = app.run("shape.rectangle", json!({"x": 160, "y": 40, "width": 40, "height": 40})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [point.clone()]})).unwrap();
let mut menu = Panel::new(app, draw);
menu.click("Type");
assert!(menu.menu_item_enabled(TO_AREA));
assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM));
menu.click_menu_item(TO_AREA);
menu.click("Type");
assert!(menu.menu_item_enabled(TO_POINT));
assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM));
menu.click_menu_item(TO_POINT);
menu.click("Type");
assert!(menu.menu_item_enabled(TO_AREA));
assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM));
menu.click("Type");
menu.app().run("select.set", json!({"ids": [point.clone(), area]})).unwrap();
menu.click("Type");
assert!(menu.menu_item_enabled(TO_AREA));
assert!(menu.menu_item_enabled(TO_POINT));
menu.click("Type");
menu.app().run("select.set", json!({"ids": []})).unwrap();
menu.click("Type");
assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM));
assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM));
menu.click("Type");
menu.app().run("select.set", json!({"ids": [rectangle.clone()]})).unwrap();
menu.click("Type");
assert!(!menu.shows_role(TO_AREA, Role::MENU_ITEM));
assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM));
menu.click("Type");
menu.app().run("select.set", json!({"ids": [rectangle, point]})).unwrap();
let group = menu.app().run("object.group", json!({})).unwrap()["id"].clone();
menu.app().run("select.set", json!({"ids": [group]})).unwrap();
menu.click("Type");
assert!(menu.menu_item_enabled(TO_AREA));
assert!(!menu.shows_role(TO_POINT, Role::MENU_ITEM));
}
/// The Window menu keeps one check column: the labels of checked and unchecked panels, of plain
/// commands and of submenus all start at the same x.
#[test]
+1
View File
@@ -798,6 +798,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec
panel("Separations Preview", "separations"),
panel("Stroke", "stroke"),
panel("SVG Interactivity", crate::panels::svg_interactivity::ID),
panel("Swatch Strip", crate::panels::swatch_strip::ID),
panel("Swatches", "swatches"),
panel("Symbols", "symbols"),
panel("Transform", "transform"),
+12 -9
View File
@@ -46,6 +46,7 @@ pub mod script_console;
pub mod separations;
pub mod stroke;
pub mod svg_interactivity;
pub mod swatch_strip;
pub mod swatches;
pub mod symbols;
pub mod tabs;
@@ -128,8 +129,8 @@ pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 {
}
/// What a corner field edits, as its edit target: the active document's uid, how many times
/// File › Revert and Undo or Redo replaced its content (after which a node id can name another
/// object), the selected objects in id order, and `corners`, the corners the field sets (a picked
/// File › Revert, Undo or Redo and other rollbacks (`DocState::rollbacks`) replaced its content
/// (after which a node id can name another object), the selected objects in id order, and `corners`, the corners the field sets (a picked
/// corner as its [`CornerPlace`]). A field drops a value typed and not yet committed when this
/// changes, even where the new corners have the same radius, and keeps it when the same objects
/// are selected in another order. Rounding a corner replaces its anchors without changing the
@@ -142,7 +143,7 @@ pub(crate) fn corner_target(app: &VectorcraftApp, corners: impl Hash) -> u64 {
.map(|st| {
let mut objects = st.selection.objects.to_vec();
objects.sort_unstable();
(st.uid, st.reverts, st.history_restores, objects)
(st.uid, st.reverts, st.history_restores, st.rollbacks, objects)
})
.hash(&mut hasher);
corners.hash(&mut hasher);
@@ -568,6 +569,7 @@ pub(crate) fn set_part_hidden(app: &mut VectorcraftApp, key: &'static str, on: b
pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
match id {
"swatches" => swatches::show(app, ui),
swatch_strip::ID => swatch_strip::show(app, ui),
"color" => color::show(app, ui),
"colorGuide" => color_guide::show(app, ui),
"stroke" => stroke::show(app, ui),
@@ -899,11 +901,12 @@ pub(crate) fn current_transparency(app: &VectorcraftApp) -> Option<(f32, BlendMo
Some(picked.unwrap_or((n.opacity, n.blend)))
}
/// The objects a selection field edits, as a field's edit target: the document with how many times File › Revert and
/// Undo or Redo replaced its content (after which a node id can name another object), the selected objects (or the
/// object targeted in the Layers panel) in id order, and the selected symbol part. A field with an unfinished value
/// drops it when these change, and keeps it when the same objects are selected in another order.
pub(crate) type SelectionTarget = (Option<(u64, u64, u64)>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>);
/// The objects a selection field edits, as a field's edit target: the document with how many times File › Revert,
/// Undo or Redo and other rollbacks (`DocState::rollbacks`) replaced its content (after which a node id can name
/// another object), the selected objects (or the object targeted in the Layers panel) in id order, and the selected
/// symbol part. A field with an unfinished value drops it when these change, and keeps it when the same objects are
/// selected in another order.
pub(crate) type SelectionTarget = (Option<(u64, u64, u64, u64)>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>);
/// The [`SelectionTarget`] of the active document.
pub(crate) fn selection_target(app: &VectorcraftApp) -> SelectionTarget {
@@ -911,7 +914,7 @@ pub(crate) fn selection_target(app: &VectorcraftApp) -> SelectionTarget {
let part = st.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone()));
let mut subjects = st.selection.subjects().to_vec();
subjects.sort_unstable();
(Some((st.uid, st.reverts, st.history_restores)), subjects, part)
(Some((st.uid, st.reverts, st.history_restores, st.rollbacks)), subjects, part)
}
/// What the Transparency panel's and the Control bar's Opacity fields edit, as their edit target: the
+17 -11
View File
@@ -143,17 +143,7 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
let key = (nodes, px);
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
let art: Vec<&Node> = ids().iter().filter_map(|id| doc.node(*id)).collect();
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
// the tile (Layers row thumbs stay cheap without it).
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
let img = RENDERER.with(|rr| match art.as_slice() {
[one] => rr.borrow_mut().render_node_thumbnail_with(doc, one, px, None, &opts),
many => {
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
rr.borrow_mut().render_node_thumbnail_with(doc, &group, px, None, &opts)
}
})?;
let color = crate::canvas::color_image(&img);
let color = RENDERER.with(|rr| thumb_image(&mut rr.borrow_mut(), doc, &art, px))?;
let tex = painter.ctx().load_texture(format!("asset-thumb-{}", a.id), color, egui::TextureOptions::LINEAR);
CACHE.with(|c| {
let mut c = c.borrow_mut();
@@ -169,6 +159,22 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
}
}
/// The objects `art` of `doc` (back to front) fitted into `px` pixels square, transparent: the
/// image of an asset's tile. `None` when they have no bounds.
pub(super) fn thumb_image(r: &mut vectorcraft_render::Renderer, doc: &Document, art: &[&Node], px: u32) -> Option<egui::ColorImage> {
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
// the tile (Layers row thumbs stay cheap without it).
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
let img = match art {
[one] => r.render_node_thumbnail_words_with(doc, one, px, None, &opts),
many => {
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
r.render_node_thumbnail_words_with(doc, &group, px, None, &opts)
}
}?;
Some(crate::canvas::color_image_owned(img))
}
/// The document's assets as the tile grid's items.
struct Assets {
ids: Vec<u64>,
+14
View File
@@ -180,6 +180,20 @@ pub(crate) fn gamut(_app: &VectorcraftApp) -> Gamut<'static> {
})
}
/// The printable test of [`gamut`] in the CMYK space of `inks` instead of the active one, for a
/// picker that edits a document other than the front one.
pub(crate) fn gamut_of(inks: std::sync::Arc<cms::Cms>) -> Gamut<'static> {
Gamut::new(move |c: Srgba| {
// The picker samples display sRGB: the same color in the document's RGB space.
let color = crate::screen_color::sampled(&inks, [c.r, c.g, c.b]);
if !inks.out_of_gamut(&color) {
return c;
}
let [r, g, b] = inks.display_rgb(&inks.convert(&color, cms::Model::Cmyk, inks.settings().intent));
Srgba::new(r, g, b, c.a)
})
}
/// Serde reader for [`crate::UiState::color_panel`]: junk gives the default, so an unknown value
/// doesn't lose the rest of the preferences.
pub fn deserialize_panel_state<'de, D: serde::Deserializer<'de>>(d: D) -> Result<ColorPanelState, D::Error> {
+6 -2
View File
@@ -384,8 +384,8 @@ fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyl
} else {
styled_node(n, g, app.session.prefs.override_char_color)
};
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?;
let mut img = crate::canvas::color_image(&img);
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, &styled, px, Some([255; 4])))?;
let mut img = crate::canvas::color_image_owned(img);
if empty {
slash(&mut img);
}
@@ -1321,13 +1321,17 @@ mod tests {
// The large preview on the selected rectangle.
let st = app.session.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
crate::canvas::clear_handed_over();
let img = render_object(&app, &st.doc, n, &empty, 60).unwrap();
crate::canvas::assert_handed_over(&img, "the large preview with the slash");
assert!(red(px(&img, 30, 30)));
assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30));
assert_eq!(px(&img, 10, 10), Color32::WHITE);
// A style that paints keeps its own look there, without the slash.
let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0));
crate::canvas::clear_handed_over();
let img = render_object(&app, &st.doc, n, &blue, 60).unwrap();
crate::canvas::assert_handed_over(&img, "the large preview");
assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255));
}
+19 -5
View File
@@ -128,7 +128,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
}
return match RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), &doc, &node, side)) {
Some(img) => ThumbRender::Ready(crate::canvas::color_image(&img)),
Some(img) => ThumbRender::Ready(crate::canvas::color_image_owned(img)),
None => ThumbRender::Blank,
};
}
@@ -141,7 +141,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
if cancel.is_cancelled() {
return Err(cancelled());
}
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image(&img))))
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image_owned(img))))
}))
}
@@ -309,8 +309,8 @@ fn light_row(n: &Node, quick: Option<bool>, doc: &Document) -> bool {
}
/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or a lane.
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered> {
r.render_node_thumbnail_with(doc, n, px, None, &thumb_options())
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
r.render_node_thumbnail_words_with(doc, n, px, None, &thumb_options())
}
#[cfg(test)]
@@ -598,7 +598,7 @@ mod tests {
let ThumbRender::Later(job) = rendered(doc, n, &request) else { panic!("a heavy node is made on a lane") };
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, request.side).expect("this thread draws the node");
let here = crate::canvas::color_image(&here);
let here = crate::canvas::color_image_owned(here);
assert!(here.pixels.iter().any(|p| p.a() > 0), "the thumbnail shows the art");
assert_eq!((there.size, &there.pixels), (here.size, &here.pixels), "the same pixels");
}
@@ -642,4 +642,18 @@ mod tests {
assert!(matches!(before.render(&key, &request), ThumbRender::Ready(_)));
assert!(matches!(after.render(&key, &request), ThumbRender::Later(_)), "and a long path is made on a lane");
}
#[test]
fn a_rows_thumbnail_is_handed_to_its_image_without_a_copy() {
let request = ThumbRequest::for_cell(24.0, 1.0);
let (doc, n) = doc_with(|id| rect(id.0));
crate::canvas::clear_handed_over();
let ThumbRender::Ready(here) = rendered(&doc, &n, &request) else { panic!("a small object's thumbnail is made at once") };
crate::canvas::assert_handed_over(&here, "a thumbnail made here");
let (doc, n) = doc_with(|id| path(id.0, 50_000));
let ThumbRender::Later(job) = rendered(&doc, &n, &request) else { panic!("a long path is made on a lane") };
crate::canvas::clear_handed_over();
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
crate::canvas::assert_handed_over(&there, "a thumbnail made on a lane");
}
}
+16 -2
View File
@@ -173,8 +173,8 @@ impl ThumbSource<NavKey> for NavThumbs {
ThumbRender::Later(Box::new(move |_cancel| {
let options = image_options(key);
let renderer = if key.solid_dashes { &SOLID_RENDERER } else { &NAV_RENDERER };
let image = renderer.with(|r| r.borrow_mut().render_region_with(&doc, region, scale, &options));
Ok(LoadedPicture::Image(crate::canvas::color_image(&image)))
let image = renderer.with(|r| r.borrow_mut().render_region_with_words(&doc, region, scale, &options));
Ok(LoadedPicture::Image(crate::canvas::color_image_owned(image)))
}))
}
}
@@ -293,6 +293,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
mod tests {
use super::*;
/// The navigator's picture, with and without solid dashes, holds the pixels it was rendered into.
#[test]
fn the_navigator_picture_is_handed_to_its_image_without_a_copy() {
let doc = Arc::new(vectorcraft_doc::Document::new(200.0, 100.0));
let source = NavThumbs::new(&doc, 1, DRect::new(-10.0, -10.0, 210.0, 110.0));
for solid_dashes in [false, true] {
let key = NavKey { uid: 1, artboard_only: false, solid_dashes };
let ThumbRender::Later(job) = source.render(&key, &ThumbRequest::for_cell(60.0, 1.0)) else { panic!("the picture is made on a lane") };
crate::canvas::clear_handed_over();
let Ok(LoadedPicture::Image(image)) = job(&craft::host::queue::Cancel::new()) else { panic!("the job draws the document") };
crate::canvas::assert_handed_over(&image, if solid_dashes { "with solid dashes" } else { "with dashes" });
}
}
#[test]
fn navigator_reports_a_malformed_zoom_entry() {
assert_malformed_zoom_entry_reported(show);
+67 -37
View File
@@ -5,12 +5,17 @@
use std::sync::LazyLock;
mod profile_picker;
use profile_picker::{ProfileAction, ProfileActions, ProfileOption, ProfileSample, ProfileSelect};
use craft::behavior::{ColumnWidth, EditEvent, GestureId, IconId, Mixed};
use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSections};
use craft::keymap::CommandRef;
use craft::ui::buttons::IconButton;
use craft::ui::choice::Segmented;
use craft::ui::contract::{Bind, EditResponse, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec};
use craft::ui::contract::{
Bind, EditResponse, Entry, FieldLabelRole, Inner, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec,
};
use craft::ui::display::Divider;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Grid, Row};
@@ -24,7 +29,7 @@ use craft::ui::runtime::env::{LengthUnits, UnitKind};
use craft::ui::style::DataColor;
use craft::ui::text::{LinkMode, LinkedFields};
use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows};
use egui::{Rect, Ui, pos2};
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};
@@ -56,8 +61,6 @@ pub(crate) struct StrokePanel {
pub scale_linked: bool,
/// The cache of [`brush_keeps_size`], keyed by (document uid, revision, active Appearance row).
pub brushed: Option<(BrushedKey, Option<bool>)>,
/// The Stroke popover of the weight's link label is open.
pub link_open: bool,
/// The running gesture of a Stroke panel select.
pub select_gesture: Option<SelectGesture>,
}
@@ -447,24 +450,26 @@ 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 output of the number field, none when
/// the row's body did not run.
fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: SideLabel, weight: Option<f64>) -> Option<NumberOutput> {
Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight).show(ui)).inner
/// 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))
}
/// The weight field whose link side label (`label`: the Control bar's "Stroke:", the Properties panel's "Stroke")
/// opens the Stroke panel in a popover under it, and whose drag scrubs the weight. The field keeps its name, Weight:
/// the label beside the Stroke chip says which paint it is the weight of.
/// opens the Stroke panel in a popover anchored to it, and whose drag scrubs the weight. The field keeps its name,
/// 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 mut open = app.ui.stroke_panel.link_open;
if let Some(out) = weight_row(app, ui, label, side, weight) {
let field = weight_row(app, ui, label, side, weight);
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 {
apply_weight(app, &out, WeightTarget::Shown);
open ^= out.link;
}
Popover::new(tl!("Stroke"), Bind::bound(&mut open)).show(ui, |ui, _| show(app, ui));
app.ui.stroke_panel.link_open = open;
Popover::new(tl!("Stroke"), Bind::bound(&mut open)).opened_by(&field.output).show(ui, |ui, _| show(app, ui));
ui.data_mut(|d| d.insert_temp(open_id, open));
}
/// The Stroke panel: the weight, the stroke editor (cap, corner, align, dashes), arrowheads, scale, align and the
@@ -492,7 +497,7 @@ 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) {
if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight).inner {
apply_weight(app, &out, WeightTarget::Shown);
}
if app.ui.stroke_panel.hide_options {
@@ -887,57 +892,82 @@ pub(crate) fn profile_select(app: &mut VectorcraftApp, ui: &mut Ui) {
brush_keeps_size(app, shown.as_ref())
};
let mut entries = vec![];
// Each entry's id and silhouette, as `WidthProfile::points`.
let mut shapes: Vec<(String, Option<Vec<_>>)> = vec![];
let mut picked = String::new();
let mut divide = true;
for e in app.session.profile_entries().filter(|e| brushed != Some(true) || e.matches(None)) {
if !e.built_in && std::mem::take(&mut divide) {
entries.push(Entry::separator());
}
if e.matches(cur) {
picked = e.id.to_string();
}
// A saved profile's name is the user's.
entries.push(Entry::new(e.id.to_string(), super::label_or_name(e.label, e.built_in).to_string()));
shapes.push((e.id.to_string(), silhouette(e.points).map(<[_]>::to_vec)));
entries.push(ProfileOption {
id: e.id.to_string(),
label: super::label_or_name(e.label, e.built_in).to_string(),
points: silhouette(e.points).map(<[ProfileSample]>::to_vec),
built_in: e.built_in,
});
}
let brush_tip = tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.");
// While a brush keeps the size of a profiled stroke the select stays on, to its Uniform row, and still says why.
let tip = TooltipSpec::new(if brushed == Some(true) { brush_tip } else { tl!("Variable Width Profile") }).disabled_text(brush_tip);
// A profile no row shows (an unsaved one, or a listed one the brushed list leaves out) is drawn and named on the
// face under the empty id, without a row of its own.
// face without a row of its own.
let unlisted = match cur {
Some(profile) if picked.is_empty() => {
shapes.push((String::new(), silhouette(&profile.points).map(<[_]>::to_vec)));
Some(app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned())
let label = app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned();
Some((label, silhouette(&profile.points).map(<[ProfileSample]>::to_vec)))
}
_ => None,
};
let select = Select::new(tl!("Profile"), Bind::given(picked), &entries);
let actions = ProfileActions {
can_add: cur.is_some() && brushed != Some(true) && crate::menus::enabled(app, "stroke.widthProfile.add"),
can_delete: cur.as_ref().and_then(|p| app.session.profile_entry(Some(p))).is_some_and(|e| !e.built_in)
&& brushed != Some(true)
&& crate::menus::enabled(app, "stroke.widthProfile.delete"),
can_reset: crate::menus::enabled(app, "stroke.widthProfile.reset"),
};
let select = ProfileSelect::new(tl!("Profile"), Bind::given(picked), entries, paint_profile, actions);
let select = match unlisted {
Some(label) => select.unlisted_label(label),
Some((label, points)) => select.unlisted(label, points),
None => select,
};
let out = select
.picture(|id: &String, cx, rect| {
if let Some((_, points)) = shapes.iter().find(|(i, _)| i == id) {
paint_profile(cx, rect, points.as_deref());
}
})
// Brushed strokes with a profile still open the list, to its Uniform row.
.enabled(brushed != Some(false))
.tooltip(tip)
.show(ui);
// A cancel puts back what the gesture changed instead of applying the empty id, which names no profile.
apply_select(app, "profile", &out, |app, id| set(app, json!({"profile": id})));
apply_select(app, "profile", &out.edit, |app, id| set(app, json!({"profile": id})));
if let Some(action) = out.action {
apply_profile_action(app, action);
}
}
fn apply_profile_action(app: &mut VectorcraftApp, action: ProfileAction) {
match action {
// Asks for the new profile's name, as the ≡ menu's Add to Profiles… does.
ProfileAction::Add => {
let params = add_profile_params(app);
crate::menus::invoke(app, "ui.paramDialog", params);
}
ProfileAction::Delete(Some(name)) => {
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({"name": name}));
}
ProfileAction::Delete(None) => {
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({}));
}
ProfileAction::Reset => {
crate::dialogs::confirm::ask(app, tl!("Do you want to reset profiles?"), "", "stroke.widthProfile.reset", json!({}));
}
}
}
/// The `ui.paramDialog` params that ask for the name of a new saved profile.
fn add_profile_params(app: &VectorcraftApp) -> Value {
json!({"command": "stroke.widthProfile.add", "label": "Variable Width Profile", "params": {"name": app.session.next_profile_name()}})
}
/// The command a ≡ menu row runs to ask for the name of a new saved profile.
fn add_profile(app: &VectorcraftApp) -> CommandRef {
let params =
json!({"command": "stroke.widthProfile.add", "label": "Variable Width Profile", "params": {"name": app.session.next_profile_name()}});
CommandRef::with_params("ui.paramDialog", params)
CommandRef::with_params("ui.paramDialog", add_profile_params(app))
}
/// The rows of the Stroke panel's ≡ menu; their titles and enabled flags come from [`menu_states`].
@@ -0,0 +1,657 @@
//! 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.
use std::borrow::Cow;
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,
};
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 _,
};
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::pickers::{SelectFace, toggle_on_key};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::{FocusMove, KeyUse};
use craft::ui::runtime::memory::Remember as _;
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::sections::{FooterAction, FooterBar};
use craft::ui::style::{ComponentStyle, StyleCx, SurfaceLook};
use egui::{Rect, Response, Vec2};
const PROFILE_COL: ColumnKey = ColumnKey::new("profile");
/// The narrowest the closed control and the open list get, in points: room for a built-in's thumbnail and its
/// longest label.
const DROPDOWN_MIN_WIDTH: f32 = 132.0;
/// The widest the closed control gets, in points, however long the picked profile's name.
const CLOSED_MAX_WIDTH: f32 = 145.0;
/// The rows Page Up and Page Down step the closed control by.
const PAGE_ROWS: isize = 12;
/// The size of a saved profile's thumbnail in the open list, in points.
const SAVED_THUMB: Vec2 = Vec2::new(80.0, 20.0);
/// The space left above and below a saved profile's thumbnail inside its row, in points.
const SAVED_THUMB_INSET: f32 = 2.0;
const FACE: PartKey = PartKey::new("face");
const POPUP: &str = "list";
const LIST_SALT: &str = "items";
/// Row identity in the profile list, keeping the non-interactive divider distinct from any
/// user-saved profile name (even a literal `"__profile_separator__"`).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ProfileRowKey {
Profile(String),
Separator,
}
impl ProfileRowKey {
fn profile(&self) -> Option<&str> {
match self {
ProfileRowKey::Profile(id) => Some(id.as_str()),
ProfileRowKey::Separator => None,
}
}
}
/// One silhouette sample `(t, left_offset, right_offset)` returned by `stroke::silhouette`.
pub(super) type ProfileSample = (f64, f64, f64);
fn profile_thumb_aspect() -> ThumbAspect {
ThumbAspect::new(14, 5)
}
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct ProfileGraphicStyle {
#[style(metrics)]
metrics: Metrics,
}
/// Passive width-profile graphic for captionless user-added rows (`Sense::empty()` lets clicks and
/// reorder drags go straight through to the list row).
#[derive(Component, Props)]
#[component(content_painter, sample = ProfileGraphic::sample)]
struct ProfileGraphic {
#[common]
common: Common,
points: Option<Vec<ProfileSample>>,
paint: ProfilePaint,
size: Vec2,
}
impl ProfileGraphic {
fn new(paint: ProfilePaint, points: Option<Vec<ProfileSample>>, size: Vec2) -> Self {
Self { common: Common::new(), points, paint, size }
}
fn sample() -> Self {
Self::new(|_, _, _| {}, None, SAVED_THUMB)
}
}
impl Component for ProfileGraphic {
const ROLE: Role = Role::None;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = ProfileGraphicStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: ProfileGraphicStyleKey) -> ProfileGraphicStyle {
ProfileGraphicStyle { metrics: Metrics::new() }
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
self.size
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let painter = ui.content_painter(cx);
(self.paint)(&painter, cx.rect.shrink2(Vec2::new(0.0, SAVED_THUMB_INSET)), self.points.as_deref());
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// One entry in the Variable Width Profile dropdown.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ProfileOption {
/// Engine preset id (`"uniform"`, `"lens"`, …) or saved profile name.
pub id: String,
/// Display label shown in the closed face, and in the dropdown row for built-in profiles.
pub label: String,
/// Profile silhouette samples (`None` for Uniform).
pub points: Option<Vec<ProfileSample>>,
/// Built-in profiles keep their text captions in the dropdown and cannot be deleted.
pub built_in: bool,
}
/// Enable state for the management controls inside the dropdown footer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ProfileActions {
pub can_add: bool,
pub can_delete: bool,
pub can_reset: bool,
}
/// A management action requested by the dropdown footer or a saved row's menu.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum ProfileAction {
Add,
Delete(Option<String>),
Reset,
}
/// Output of [`ProfileSelect`]: the underlying profile pick/preview edit and any management action.
#[derive(Debug)]
pub(super) struct ProfileSelectOutput {
pub edit: EditResponse<String>,
pub action: Option<ProfileAction>,
}
impl Outcome for ProfileSelectOutput {
type Value = String;
fn response(&self) -> &Response {
&self.edit.response
}
}
/// Paint callback shared between the closed face and list rows.
pub(super) type ProfilePaint = fn(&ContentPainterCx, Rect, Option<&[ProfileSample]>);
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
pub(super) struct ProfileSelectStyle {
#[style(surface)]
surface: SurfaceLook,
#[style(metrics)]
metrics: Metrics,
}
#[derive(Clone, Default)]
struct PickerMemory {
/// Target key of an open per-row context menu.
menu: Option<String>,
/// Pre-typed query buffered on focus while closed.
type_ahead: TypeAhead,
/// Pending lead override when opening from closed type-ahead.
reveal_on_open: Option<String>,
/// Whether a preview proposal was issued during this open popup session.
previewed: bool,
}
/// The Profile drop-down: the width profile list, with a footer that adds the stroke's profile, deletes a saved one
/// and resets the list.
#[derive(Component, Props)]
#[component(overlay, sample = ProfileSelect::sample)]
pub(super) struct ProfileSelect {
#[common]
common: Common,
value: Bind<'static, String>,
entries: Vec<ProfileOption>,
unlisted_label: Option<String>,
unlisted_points: Option<Vec<ProfileSample>>,
paint: ProfilePaint,
actions: ProfileActions,
action: Option<ProfileAction>,
}
impl ProfileSelect {
pub(super) fn new(
label: impl Into<craft::ui::runtime::env::Label>,
value: Bind<'static, String>,
entries: Vec<ProfileOption>,
paint: ProfilePaint,
actions: ProfileActions,
) -> Self {
Self { common: Common::new(), value, entries, unlisted_label: None, unlisted_points: None, paint, actions, action: None }.label(label)
}
pub(super) fn unlisted(mut self, label: String, points: Option<Vec<ProfileSample>>) -> Self {
self.unlisted_label = Some(label);
self.unlisted_points = points;
self
}
fn sample() -> Self {
Self::new(
"Profile",
Bind::given("uniform".to_owned()),
vec![ProfileOption { id: "uniform".to_owned(), label: "Uniform".to_owned(), points: None, built_in: true }],
|_, _, _| {},
ProfileActions::default(),
)
}
fn option(&self, id: &str) -> Option<&ProfileOption> {
self.entries.iter().find(|e| e.id == id)
}
fn display_for(&self, current: Option<&String>) -> (String, Option<Vec<ProfileSample>>, bool) {
let Some(id) = current else {
return (tl!("Mixed").to_owned(), None, true);
};
if let Some(opt) = self.option(id) {
return (opt.label.clone(), opt.points.clone(), false);
}
if let Some(label) = &self.unlisted_label {
return (label.clone(), self.unlisted_points.clone(), false);
}
(tl!("Mixed").to_owned(), None, true)
}
fn face(&self, current: Option<&String>) -> SelectFace<'static> {
let (text, points, placeholder) = self.display_for(current);
let paint = self.paint;
let face = SelectFace::new(text).fit(true).thumb(profile_thumb_aspect(), move |cx, rect| paint(cx, rect, points.as_deref()));
if placeholder { face.placeholder() } else { face }
}
fn has_separator(&self) -> bool {
self.entries.len() > 1
}
fn step_entry(&self, current: Option<&String>, steps: isize) -> Option<String> {
if self.entries.is_empty() {
return None;
}
let cur = current.and_then(|id| self.entries.iter().position(|e| &e.id == id));
let next = match cur {
Some(at) => (at as isize + steps).clamp(0, (self.entries.len() - 1) as isize) as usize,
None if steps >= 0 => 0,
None => self.entries.len() - 1,
};
self.entries.get(next).map(|e| e.id.clone())
}
fn nav_target(&self, current: Option<&String>, mv: NavMove) -> Option<String> {
match mv {
NavMove::Up | NavMove::Back => self.step_entry(current, -1),
NavMove::Down | NavMove::Forward => self.step_entry(current, 1),
NavMove::Start => self.entries.first().map(|e| e.id.clone()),
NavMove::End => self.entries.last().map(|e| e.id.clone()),
NavMove::PageUp => self.step_entry(current, -PAGE_ROWS),
NavMove::PageDown => self.step_entry(current, PAGE_ROWS),
_ => None,
}
}
}
struct ProfileRows<'a> {
entries: &'a [ProfileOption],
separator: bool,
}
impl<'a> ProfileRows<'a> {
fn entry_at(&self, at: usize) -> Option<&'a ProfileOption> {
if at == 0 {
return self.entries.first();
}
if self.separator { if at == 1 { None } else { self.entries.get(at - 1) } } else { self.entries.get(at) }
}
}
impl DisplayOrder<ProfileRowKey> for ProfileRows<'_> {
fn len(&self) -> usize {
self.entries.len() + usize::from(self.separator)
}
fn key(&self, at: usize) -> ProfileRowKey {
self.entry_at(at).map_or(ProfileRowKey::Separator, |e| ProfileRowKey::Profile(e.id.clone()))
}
fn is_section(&self, at: usize) -> bool {
self.separator && at == 1
}
fn enabled(&self, at: usize) -> bool {
!(self.separator && at == 1)
}
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
self.entry_at(at).map(|e| Cow::Borrowed(e.label.as_str()))
}
}
impl ItemSource<ProfileRowKey> for ProfileRows<'_> {}
impl Component for ProfileSelect {
const ROLE: Role = Role::COMBO_BOX;
const INPUT: Input = Input::Pointer;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_moves().with_type_ahead();
type Style = ProfileSelectStyle;
type Output = ProfileSelectOutput;
fn style(cx: &StyleCx<'_>, _: ProfileSelectStyleKey) -> ProfileSelectStyle {
ProfileSelectStyle { surface: cx.dropdown(), metrics: Metrics::new() }
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS | Sense::WHEEL_Y
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let mut size = cx.face(self.face(cx.value()));
let paint = self.paint;
let aspect = profile_thumb_aspect();
for entry in self.entries.iter().filter(|e| e.built_in) {
let points = entry.points.clone();
let mut face = SelectFace::new(entry.label.clone()).fit(true).thumb(aspect, move |painter, rect| paint(painter, rect, points.as_deref()));
let measured = cx.child("option", &mut face, Proposal::Ideal);
size.x = size.x.max(measured.x);
size.y = size.y.max(measured.y);
}
Vec2::new(size.x.clamp(DROPDOWN_MIN_WIDTH, CLOSED_MAX_WIDTH), size.y)
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
cx.part(FACE, rect)
.sense(Sense::CLICK | Sense::HOVER | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Body, 0))
.pointer_only("Enter, Space and Alt+Down open the list")
.toggles(POPUP);
}
fn bind(&mut self) -> Option<BindMut<'_, String>> {
Some(self.value.reborrow())
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let popup = cx.popup(POPUP);
toggle_on_key(cx, popup);
if !popup.is_open(cx) && !cx.in_wheel_run() && matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) {
cx.cancel(CancelReason::Dismissed);
}
if let Some(wheel) = cx.take_wheel() {
if matches!(wheel.phase, WheelPhase::End) {
cx.wheel_run(wheel.phase, None);
} else if let StepResult::Set(along) =
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, &wheel, cx.env.direction().is_rtl())
&& along != 0.0
{
let steps = along.round() as isize;
if let Some(target) = self.step_entry(cx.value().cloned().as_ref(), -steps) {
cx.wheel_run(wheel.phase, Some(target));
}
}
}
if popup.is_open(cx) {
return;
}
// A screen reader sets the pick by its place in the list, and steps it with Increment and Decrement (moves),
// without the keyboard focus, as the framework's `Select` takes them.
if let Some(at) = cx.intents().take_set_value() {
if cx.in_wheel_run() {
cx.commit();
}
let to = (at.round().max(0.0) as usize).min(self.entries.len().saturating_sub(1));
if let Some(entry) = self.entries.get(to) {
cx.propose(entry.id.clone());
cx.commit();
}
}
while let Some((mv, _)) = cx.intents().take_move() {
if cx.in_wheel_run() {
cx.commit();
}
if let Some(target) = self.nav_target(cx.value().cloned().as_ref(), mv) {
cx.propose(target);
cx.commit();
}
}
if !cx.is_focused() {
return;
}
if let Some(typed) = cx.intents().take_text() {
let folder = cx.env.folder();
let now = cx.ctx.input(|i| i.time);
let cur_idx = cx.value().and_then(|id| self.entries.iter().position(|e| &e.id == id));
let matched = {
let mem = cx.memory::<PickerMemory>();
let mut prefix = String::new();
for ch in typed.chars() {
prefix = mem.type_ahead.push(ch, now).to_owned();
}
TypeAhead::pick(&prefix, cur_idx, self.entries.len(), |at| Cow::Borrowed(self.entries[at].label.as_str()), |text| folder.key(text))
};
if let Some(at) = matched {
let id = self.entries[at].id.clone();
let mem = cx.memory::<PickerMemory>();
mem.reveal_on_open = Some(id.clone());
mem.previewed = true;
cx.propose(id);
popup.open(cx);
}
}
}
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
let popup = cx.popup(POPUP);
let list_id = cx.id.with(LIST_SALT);
let mut overlay = Overlay::dropdown()
.fit(OverlayFit::Content)
.min_width(MinWidth::None)
.min_size(Vec2::new(DROPDOWN_MIN_WIDTH, 0.0))
.body_scroll(false)
.list(list_id);
overlay.dismiss.on_activate = false;
let fresh = Popup::opening(popup, cx);
if fresh {
let mem = cx.memory::<PickerMemory>();
mem.menu = None;
if mem.reveal_on_open.is_none() {
mem.previewed = false;
}
}
let current = cx.value().cloned().filter(|id| !id.is_empty());
let reveal =
cx.memory::<PickerMemory>().reveal_on_open.take().or_else(|| fresh.then(|| current.clone()).flatten()).map(ProfileRowKey::Profile);
let selection = current.as_ref().map_or_else(Selection::default, |id| Selection::single(ProfileRowKey::Profile(id.clone())));
let saved: HashSet<String> = self.entries.iter().filter(|e| !e.built_in).map(|e| e.id.clone()).collect();
let view = PopupView { list_id, selection: &selection, reveal: reveal.as_ref(), saved: &saved };
let body_out = ui.show(popup, overlay, |ui, _| show_popup_body(ui, cx, self, view));
if let Some((events, footer_action, menu_action)) = body_out {
self.handle_list_events(cx, popup, &events);
if let Some(act) = footer_action.or(menu_action) {
if matches!(act, ProfileAction::Reset) {
popup.close(cx);
}
self.action = Some(act);
}
}
if let Some(reason) = ui.closing(popup) {
let mem = cx.memory::<PickerMemory>();
mem.menu = None;
if std::mem::take(&mut mem.previewed) && matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) {
match reason {
CloseReason::FocusLeft(FocusMove::Keys) => cx.commit(),
CloseReason::FocusLeft(_) => cx.cancel(CancelReason::Blur),
CloseReason::Escape => cx.cancel(CancelReason::Escape),
_ => cx.cancel(CancelReason::Dismissed),
}
}
}
}
/// The picked entry's place in the list, read as its label, so a screen reader steps and sets it. A value no
/// entry holds reads as the label the face shows.
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let (text, _, _) = self.display_for(cx.value());
let range = 0.0..=self.entries.len().saturating_sub(1) as f64;
let numeric = match cx.value().and_then(|id| self.entries.iter().position(|e| &e.id == id)) {
Some(at) => Numeric::new(at as f64, range),
None => Numeric::empty(range),
};
access.numeric(numeric.text(text).step(1.0));
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
ui.face(FACE, self.face(cx.value()));
}
fn finish(mut self, cx: Cx<'_, Self>) -> ProfileSelectOutput {
ProfileSelectOutput { edit: cx.edit_response(), action: self.action.take() }
}
}
impl ProfileSelect {
fn handle_list_events(&mut self, cx: &mut Cx<'_, Self>, popup: PopupHandle, events: &[CollectionEvent<ProfileRowKey, RowEvent>]) {
for event in events {
match event {
CollectionEvent::LeadMoved { key: ProfileRowKey::Profile(key), by: LeadSource::Keys } => {
cx.memory::<PickerMemory>().previewed = true;
cx.propose(key.clone());
}
CollectionEvent::Activate(ProfileRowKey::Profile(key))
| CollectionEvent::Item(ProfileRowKey::Profile(key), RowEvent::ThumbClicked { .. }) => {
cx.propose(key.clone());
cx.commit();
cx.memory::<PickerMemory>().previewed = false;
popup.close(cx);
}
_ => {}
}
}
}
}
#[derive(Clone, Copy)]
struct PopupView<'a> {
list_id: egui::Id,
selection: &'a Selection<ProfileRowKey>,
reveal: Option<&'a ProfileRowKey>,
saved: &'a HashSet<String>,
}
fn show_popup_body(
ui: &mut egui::Ui,
cx: &mut Cx<'_, ProfileSelect>,
picker: &ProfileSelect,
view: PopupView<'_>,
) -> (Vec<CollectionEvent<ProfileRowKey, RowEvent>>, Option<ProfileAction>, Option<ProfileAction>) {
let mut footer_action = None;
let mut events = Vec::new();
let mut list_resp = None;
let label = cx.label();
let rows = ProfileRows { entries: &picker.entries, separator: picker.has_separator() };
let paint = picker.paint;
let actions = picker.actions;
let builtin_aspect = profile_thumb_aspect();
Stack::new()
.fill_width()
.footer(|ui, _| {
footer_action = show_footer(ui, actions);
})
.show(ui, |ui, _| {
let mut list = List::<ProfileRowKey>::options(label.clone())
.id(view.list_id)
.header(false)
.columns(vec![ColumnSpec::new(PROFILE_COL, Label::Empty, ColumnWidth::fill(1.0))])
.hover_lead(HoverLead::Lead)
.activate(ActivateOn::Click)
.lead_on_open(LeadOnOpen::First)
.selection(Bind::given(view.selection.clone()));
if let Some(key) = view.reveal {
list = list.reveal(key.clone());
}
let out = list.show_items(ui, &rows, &mut |key, icx| {
let ProfileRowKey::Profile(id) = key else {
return ListRow::separator();
};
let Some(entry) = picker.option(id) else {
return ListRow::spacer();
};
let points = entry.points.clone();
if entry.built_in {
ListRow::new(entry.label.clone()).option().cells(icx.cells()).thumb_aspect(
ThumbSize::Small,
builtin_aspect,
move |painter, rect| paint(painter, rect, points.as_deref()),
)
} else {
ListRow::new("").accessible_name(entry.label.clone()).option().cells(icx.cells()).cell_field(
PROFILE_COL,
ProfileGraphic::new(paint, points, SAVED_THUMB),
|_| {},
)
}
});
events = out.events;
list_resp = Some(out.response);
});
let list_response = list_resp.unwrap_or_else(|| ui.response().clone());
for event in &events {
// Only a saved row has a menu: its one item deletes it, and a built-in can't be deleted.
if let CollectionEvent::ContextMenu(request) = event
&& let Some(id) = request.key.profile()
&& view.saved.contains(id)
{
cx.memory::<PickerMemory>().menu = Some(id.to_owned());
}
}
let menu_action = show_row_menu(ui, cx, picker, &list_response);
(events, footer_action, menu_action)
}
fn show_footer(ui: &mut egui::Ui, actions: ProfileActions) -> Option<ProfileAction> {
// End-edge placement lays out actions from the right edge inward, so index 0 (`Reset Profiles`)
// sits rightmost, with `Delete Profile` and `Add to Profiles` to its left.
let bar = FooterBar::actions([
FooterAction::new(IconId::new("rotate-ccw"), tl!("Reset Profiles")).enabled(actions.can_reset),
FooterAction::new(IconId::new("trash-2"), tl!("Delete Profile")).enabled(actions.can_delete),
FooterAction::new(IconId::new("dc-new-item"), tl!("Add to Profiles")).enabled(actions.can_add),
])
.show_footer(ui);
match bar.picked {
Some(0) => Some(ProfileAction::Reset),
Some(1) => Some(ProfileAction::Delete(None)),
Some(2) => Some(ProfileAction::Add),
_ => None,
}
}
fn show_row_menu(ui: &mut egui::Ui, cx: &mut Cx<'_, ProfileSelect>, picker: &ProfileSelect, anchor: &Response) -> Option<ProfileAction> {
let target = cx.memory::<PickerMemory>().menu.clone()?;
let Some(entry) = picker.option(&target).filter(|e| !e.built_in) else {
cx.memory::<PickerMemory>().menu = None;
return None;
};
let title = entry.label.clone();
let mut action = None;
let shown = Menu::context(title, anchor).show(ui, |ui, _| {
if MenuItem::new(tl!("Delete Profile")).show(ui).ran {
action = Some(ProfileAction::Delete(Some(target.clone())));
}
});
if action.is_some() || shown.closed.is_some() {
cx.memory::<PickerMemory>().menu = None;
}
action
}
+387
View File
@@ -0,0 +1,387 @@
//! Swatch Strip panel (Window › Swatch Strip): a None chip, then the document's color swatches, in a row of chips
//! that wraps to the room the panel has. Docked along the bottom of the window (`window.panel.dock {panel:
//! "swatchStrip", anchor: "canvas", placement: {"Edge": "Bottom"}}`, or a drop on the bottom edge) the chips run
//! across in one line; in a dock column or a narrow floating window they wrap down the column, and scroll when they
//! do not fit.
//!
//! A click on a chip sets the fill (`paint.setFill`); a right-click or an Alt-click sets the stroke
//! (`paint.setStroke`). Neither changes which of the Fill and Stroke proxies is active.
use craft::theme::Srgba;
use craft::ui::choice::Swatch;
use craft::ui::contract::{Props as _, Scroll, Show as _, ShowContainer as _};
use craft::ui::layout_components::{Row, Stack};
use egui::{Event, PointerButton, Rect, Ui};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use super::srgba;
use crate::VectorcraftApp;
/// The panel's id, as `window.panel` takes it.
pub const ID: &str = "swatchStrip";
/// One chip: its name, the color it shows (`None`: the None chip) and the paint params a pick sends.
struct Chip {
name: String,
color: Option<Srgba>,
params: Value,
}
/// The None chip, then each color swatch of the active document in the Swatches panel's order (the swatches outside
/// any color group, then each group's), shown in the color its art shows. Gradient and pattern swatches are left out.
fn chips(app: &VectorcraftApp) -> Vec<Chip> {
let Some(st) = app.session.active() else { return Vec::new() };
let d = &st.doc;
let index = super::swatches::index_of(app);
let none = Chip { name: tl!("None").to_owned(), color: None, params: json!({"none": true}) };
let swatches = d.swatches_iter().filter_map(|s| match super::swatches::shown(d, &index, s).0 {
Paint::Solid { color, .. } => Some(Chip { name: s.name.clone(), color: Some(srgba(&color)), params: json!({"swatch": s.name}) }),
_ => None,
});
std::iter::once(none).chain(swatches).collect()
}
/// Sets the fill (`stroke`: the stroke) to the chip's paint, leaving the active proxy as it is.
fn apply(app: &mut VectorcraftApp, chip: &Chip, stroke: bool) {
let mut params = chip.params.clone();
params["focus"] = json!(false);
app.run(if stroke { "paint.setStroke" } else { "paint.setFill" }, params).ok();
}
/// The panel's body.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.session.active().is_none() {
super::empty_state(ui, "swatch-book", tl!("No document"), tl!("Open a document to see its swatches."));
return;
}
let chips = chips(app);
let mut picked = None;
// Where each chip shows (clipped to the scroll area), for placing the frame's right-button events.
// A sizing pass draws the chips first; the drawing pass after it writes over its rects.
let mut hits: Vec<Option<Rect>> = vec![None; chips.len()];
Stack::new().id_salt(ID).fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
Row::new().fill_width().wrap(true).show(ui, |ui, _| {
for (at, chip) in chips.iter().enumerate() {
let swatch = match chip.color {
Some(color) => Swatch::new(chip.name.clone(), color),
None => Swatch::optional(chip.name.clone(), None::<Srgba>),
};
let out = swatch.id_salt(at).tooltip(chip.name.clone()).show(ui);
if let Some(hit) = hits.get_mut(at) {
*hit = Some(out.response.rect.intersect(ui.clip_rect()));
}
if out.clicked {
picked = Some((at, out.activation.is_some_and(|a| a.mods.alt)));
}
}
});
});
// A right-click sets the stroke when its press and its release both land on the same chip.
let press_id = ui.scope_id().with((ID, "secondary-press"));
// The chip is kept by its document and the paint it sends, so a swatch that moves in the list between press and
// release still counts, and a release in another document does not.
let uid = app.session.active().map_or(0, |st| st.uid);
let keys: Vec<String> = chips.iter().map(|c| format!("{uid}:{}", c.params)).collect();
let laid_out: Vec<(Rect, String)> = hits.iter().zip(&keys).filter_map(|(r, k)| r.map(|r| (r, k.clone()))).collect();
// A container's measuring run shows the strip in an invisible sizing pass with the same id and input before the
// frame's real run; it leaves the remembered press alone, so the real run's release still finds it.
if !ui.is_sizing_pass() {
let mut pressed_on = ui.ctx().data(|d| d.get_temp::<Option<String>>(press_id)).flatten();
for event in ui.input(|i| i.events.clone()) {
if let Event::PointerButton { pos, button: PointerButton::Secondary, pressed, .. } = event {
// A chip under another layer (a popup, a floating panel) does not take the event.
let on_layer = ui.ctx().layer_id_at(pos) == Some(ui.layer_id());
let key = if on_layer { laid_out.iter().find(|(r, _)| r.contains(pos)).map(|(_, k)| k.clone()) } else { None };
if pressed {
pressed_on = key;
} else if let Some(k) = pressed_on.take()
&& key.as_ref() == Some(&k)
{
picked = keys.iter().position(|x| *x == k).map(|at| (at, true));
}
}
}
ui.ctx().data_mut(|d| d.insert_temp(press_id, pressed_on));
}
if let Some((at, stroke)) = picked
&& let Some(chip) = chips.get(at)
{
apply(app, chip, stroke);
}
}
#[cfg(test)]
mod tests {
use craft::behavior::Axis;
use craft::behavior::dock::Node;
use egui::{Modifiers, vec2};
use serde_json::json;
use vectorcraft_color::Paint;
use vectorcraft_engine::Session;
use super::show;
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
/// A document with three global color swatches (art painted with one stays linked to it) and a gradient swatch,
/// and one selected rectangle.
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
for (name, color) in [("Strip Red", "#cc2222"), ("Strip Green", "#22aa44"), ("Strip Blue", "#2244cc")] {
app.run("swatch.new", json!({"name": name, "color": color, "global": true})).unwrap();
}
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
app.run("swatch.new", json!({"name": "Strip Ramp", "gradient": ramp})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
app
}
/// The fill and stroke the Fill and Stroke proxies show: the selected rectangle's.
fn paints(panel: &Panel) -> (Paint, Paint) {
crate::panels::current_paints(&panel.app())
}
/// The swatch a solid paint is linked to.
fn swatch_of(paint: &Paint) -> Option<String> {
match paint {
Paint::Solid { swatch, .. } => swatch.clone(),
_ => None,
}
}
#[test]
fn a_click_sets_the_fill_and_a_right_click_or_alt_click_the_stroke() {
let mut panel = Panel::new(app(), show);
let fill_active = panel.app().session.fill_active;
panel.click("Strip Red");
let (fill, stroke) = paints(&panel);
assert_eq!(swatch_of(&fill).as_deref(), Some("Strip Red"), "a click sets the fill");
assert_ne!(swatch_of(&stroke).as_deref(), Some("Strip Red"), "a click leaves the stroke");
panel.secondary_click("Strip Green");
let (fill, stroke) = paints(&panel);
assert_eq!(swatch_of(&stroke).as_deref(), Some("Strip Green"), "a right-click sets the stroke");
assert_eq!(swatch_of(&fill).as_deref(), Some("Strip Red"), "a right-click leaves the fill");
panel.click_with("Strip Blue", Modifiers::ALT);
let (fill, stroke) = paints(&panel);
assert_eq!(swatch_of(&stroke).as_deref(), Some("Strip Blue"), "an Alt-click sets the stroke");
assert_eq!(swatch_of(&fill).as_deref(), Some("Strip Red"), "an Alt-click leaves the fill");
assert_eq!(panel.app().session.fill_active, fill_active, "the active proxy stays as it was");
}
#[test]
fn a_right_drag_from_outside_onto_a_chip_leaves_the_stroke() {
let mut panel = Panel::new(app(), show);
let before = paints(&panel).1;
let chip = panel.rect("Strip Green");
let outside = egui::pos2(chip.center().x, chip.bottom() + chip.height() * 3.0);
let button =
|at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(outside)]);
panel.frame_with(vec![button(outside, true)]);
panel.frame_with(vec![egui::Event::PointerMoved(chip.center())]);
panel.frame_with(vec![button(chip.center(), false)]);
panel.frame();
assert_eq!(paints(&panel).1, before, "a right-button release on a chip whose press began elsewhere sets nothing");
panel.frame_with(vec![
egui::Event::PointerMoved(outside),
button(outside, true),
egui::Event::PointerMoved(chip.center()),
button(chip.center(), false),
]);
panel.frame();
assert_eq!(paints(&panel).1, before, "the same gesture within one frame sets nothing either");
panel.secondary_click("Strip Green");
assert_eq!(swatch_of(&paints(&panel).1).as_deref(), Some("Strip Green"), "a right-click on the chip still sets the stroke");
}
#[test]
fn a_right_click_counts_for_the_swatch_pressed_when_the_list_reorders_under_it() {
let mut panel = Panel::new(app(), show);
let from = panel.rect("Strip Red").center();
let button =
|at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(from)]);
panel.frame_with(vec![button(from, true)]);
panel.app().run("swatch.move", json!({"names": ["Strip Blue"], "to": 0})).unwrap();
panel.frame();
let to = panel.rect("Strip Red").center();
assert_ne!(from, to, "the move shifts the pressed chip: {from:?}");
panel.frame_with(vec![egui::Event::PointerMoved(to), button(to, false)]);
panel.frame();
assert_eq!(swatch_of(&paints(&panel).1).as_deref(), Some("Strip Red"), "the release on the same swatch sets the stroke");
}
#[test]
fn a_right_click_in_the_frame_the_strip_remeasures_still_sets_the_stroke() {
let mut panel = Panel::new(app(), show);
panel.room(vec2(4000.0, 200.0)).frame();
panel.frame();
let at = panel.rect("Strip Green").center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(at)]);
// A new width makes the strip measure itself again in the frame that carries the press.
panel.room(vec2(3000.0, 200.0));
panel.frame_with(vec![button(true)]);
panel.frame_with(vec![button(false)]);
panel.frame();
assert_eq!(swatch_of(&paints(&panel).1).as_deref(), Some("Strip Green"), "the right-click sets the stroke");
}
#[test]
fn a_right_release_in_another_document_leaves_its_stroke() {
let mut app = app();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": "Strip Green", "color": "#22aa44", "global": true})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let mut panel = Panel::new(app, show);
let from = panel.rect("Strip Green").center();
let button =
|at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(from)]);
panel.frame_with(vec![button(from, true)]);
assert!(panel.app().session.set_active(0), "the first document becomes active");
panel.frame();
let before = paints(&panel).1;
let to = panel.rect("Strip Green").center();
panel.frame_with(vec![egui::Event::PointerMoved(to), button(to, false)]);
panel.frame();
assert_eq!(paints(&panel).1, before, "a press in one document and a release in another set nothing");
}
/// The strip measured first in an invisible sizing pass elsewhere on the screen, with the same scope id, then shown.
fn measured(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
let away = ui.max_rect().translate(vec2(5000.0, 5000.0));
let mut sizing = ui.new_child(egui::UiBuilder::new().scope_id(ui.scope_id()).max_rect(away).sizing_pass().invisible());
show(app, &mut sizing);
show(app, ui);
}
#[test]
fn a_sizing_pass_leaves_the_right_click_to_the_shown_strip() {
let mut panel = Panel::new(app(), measured);
let at = panel.rect("Strip Green").center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(at)]);
panel.frame_with(vec![button(true)]);
panel.frame_with(vec![button(false)]);
panel.frame();
assert_eq!(swatch_of(&paints(&panel).1).as_deref(), Some("Strip Green"), "the shown strip's right-click sets the stroke");
}
thread_local! {
/// Whether [`covered`] draws its cover.
static COVER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
}
/// The strip with a foreground area covering the first 400 by 400 points while [`COVER`] is set.
fn covered(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
show(app, ui);
if COVER.with(|c| c.get()) {
egui::Area::new(egui::Id::unique("strip-cover")).order(egui::Order::Foreground).fixed_pos(egui::pos2(0.0, 0.0)).show(ui.ctx(), |ui| {
ui.allocate_exact_size(vec2(400.0, 400.0), egui::Sense::click());
});
}
}
#[test]
fn a_right_press_on_a_layer_covering_a_chip_leaves_the_stroke() {
COVER.with(|c| c.set(true));
let mut panel = Panel::new(app(), covered);
let before = paints(&panel).1;
let at = panel.rect("Strip Green").center();
assert!(at.x < 400.0 && at.y < 400.0, "the cover lies over the chip: {at:?}");
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE };
panel.frame_with(vec![egui::Event::PointerMoved(at)]);
panel.frame_with(vec![button(true)]);
// The cover goes away while the button is down, so the release lands on the chip itself.
COVER.with(|c| c.set(false));
panel.frame();
panel.frame();
panel.frame_with(vec![button(false)]);
panel.frame();
assert_eq!(paints(&panel).1, before, "a press on the covering layer does not count as a press on the chip");
panel.secondary_click("Strip Green");
assert_eq!(swatch_of(&paints(&panel).1).as_deref(), Some("Strip Green"), "with the cover gone a right-click reaches the chip");
}
#[test]
fn the_none_chip_comes_first_and_takes_the_paint_off() {
let mut panel = Panel::new(app(), show);
let none = panel.rect("None");
let red = panel.rect("Strip Red");
assert!(none.left() < red.left() || none.top() < red.top(), "the None chip comes before the swatches: {none:?} {red:?}");
panel.click("Strip Red");
panel.click("None");
assert!(paints(&panel).0.is_none(), "a click on None takes the fill off");
panel.secondary_click("None");
assert!(paints(&panel).1.is_none(), "a right-click on None takes the stroke off");
}
#[test]
fn only_color_swatches_get_chips() {
let panel = Panel::new(app(), show);
assert!(panel.shows("Strip Red"), "a color swatch has a chip");
assert!(!panel.shows("Strip Ramp"), "a gradient swatch has none");
}
#[test]
fn the_chips_run_along_a_wide_strip_and_wrap_down_a_narrow_one() {
let mut panel = Panel::new(app(), show);
let names = ["None", "Strip Red", "Strip Green", "Strip Blue"];
panel.room(vec2(4000.0, 200.0)).frame();
panel.frame();
let rects: Vec<_> = names.iter().map(|n| panel.rect(n)).collect();
for pair in rects.windows(2) {
assert!((pair[0].center().y - pair[1].center().y).abs() < 1.0, "the chips share one line: {pair:?}");
assert!(pair[0].right() <= pair[1].left(), "each chip lies after the one before it without overlapping: {pair:?}");
}
let one_chip = rects[0].width();
panel.room(vec2(one_chip * 2.5, 2000.0)).frame();
panel.frame();
let first = panel.rect("None");
let last = panel.rect("Strip Blue");
assert!(last.top() >= first.bottom(), "in a narrow column a later chip wraps below the first: {first:?} {last:?}");
assert!(last.right() <= one_chip * 2.5 + 0.5, "the chips stay inside the column: {last:?}");
}
/// Whether `node` holds panel `panel`.
fn holds(node: &Node<String>, panel: &str) -> bool {
match node {
Node::Split { first, second, .. } => holds(first, panel) || holds(second, panel),
Node::Tabs { panels, .. } => panels.iter().any(|p| p == panel),
Node::Stack { entries, .. } => entries.iter().any(|e| e.panel == panel),
Node::Dock { columns, .. } => columns.iter().any(|c| c.panels().any(|p| p == panel)),
_ => false,
}
}
/// Whether `node` has a split of rows with `upper` in its top part and `lower` in its bottom part.
fn above(node: &Node<String>, upper: &str, lower: &str) -> bool {
match node {
Node::Split { axis: Axis::Y, first, second, .. } if holds(first, upper) && holds(second, lower) => true,
Node::Split { first, second, .. } => above(first, upper, lower) || above(second, upper, lower),
_ => false,
}
}
#[test]
fn the_strip_docks_along_the_bottom_edge_below_the_canvas() {
let mut app = app();
app.run("window.panel.dock", json!({"panel": super::ID, "anchor": "canvas", "placement": {"Edge": "Bottom"}})).unwrap();
let layout = crate::panel_docking::layout_of(&app.ui);
let root = layout.root.as_ref().expect("a docked layout");
assert!(above(root, crate::panel_docking::CANVAS, super::ID), "the strip lies in a row below the canvas: {root:?}");
}
}
+9 -6
View File
@@ -278,7 +278,7 @@ pub(crate) fn selected(app: &VectorcraftApp) -> Vec<String> {
}
/// The names of the active document ([`Model::index`]); an empty index without a document.
fn index_of(app: &VectorcraftApp) -> Arc<SwatchIndex> {
pub(crate) fn index_of(app: &VectorcraftApp) -> Arc<SwatchIndex> {
app.session.active().map_or_else(Default::default, |st| app.ui.swatches_panel.index(&st.doc))
}
@@ -310,7 +310,7 @@ fn highlighted(d: &Document, index: &SwatchIndex, sel: &[String]) -> BTreeSet<St
/// The `swatch`'s paint as the panel shows it, and whether it is global and spot. A tint swatch shows its base's kind;
/// a spot colour shows the colour its art shows (a Lab one's CMYK equivalent when the Spot Colors options use those).
/// `index` holds the names of `d`.
fn shown(d: &Document, index: &SwatchIndex, s: &Swatch) -> (Paint, bool, bool) {
pub(crate) fn shown(d: &Document, index: &SwatchIndex, s: &Swatch) -> (Paint, bool, bool) {
let (global, spot) = s.tint_of().and_then(|(base, _)| index.swatch(d, base)).map_or((s.global, s.spot), |b| (b.global, b.spot));
let paint = match s.paint {
Paint::Solid { color, swatch: None, .. } if spot => Paint::solid(d.linked_color(color, true)),
@@ -682,10 +682,8 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
px,
);
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).unwrap_or_else(|| {
let tex = vectorcraft_render::render_pattern_swatch(doc, pattern, px).map(|img| {
let color = crate::canvas::color_image(&img);
ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR)
});
let tex = pattern_image(doc, pattern, px)
.map(|color| ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR));
CACHE.with(|c| {
let mut c = c.borrow_mut();
if c.len() > 256 {
@@ -701,6 +699,11 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
true
}
/// The swatch image of pattern `name` in `doc`, `px` pixels square; `None` when `doc` has no such pattern.
fn pattern_image(doc: &Document, name: &str, px: u32) -> Option<egui::ColorImage> {
vectorcraft_render::render_pattern_swatch_words(doc, name, px).map(crate::canvas::color_image_owned)
}
/// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or
/// black paper. It is the same in every theme.
pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20);
@@ -1716,3 +1716,18 @@ fn idle_frames_replay_the_swatch_rows() {
assert!(panel.shows(red), "and they show the swatch again");
idle(&mut panel, "after an undo");
}
/// A pattern swatch's image holds the pixels the swatch was rendered into; a pattern the document
/// lacks has no image.
#[test]
fn a_pattern_swatch_image_is_handed_over_without_a_copy() {
let mut app = app();
let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap();
let doc = doc(&app);
crate::canvas::clear_handed_over();
let image = pattern_image(&doc, "Dots", 24).expect("the pattern draws");
assert_eq!(image.size, [24, 24], "the swatch's size");
crate::canvas::assert_handed_over(&image, "the pattern swatch");
assert!(pattern_image(&doc, "Missing", 24).is_none(), "no image for a pattern the document lacks");
}
+5 -5
View File
@@ -100,7 +100,7 @@ impl ThumbSource<SymbolThumb> for SymbolPictures<'_> {
render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h))
}
};
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img)))
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img)))
}
}
@@ -198,7 +198,7 @@ pub(crate) mod counters {
/// Symbol `name` of `doc` rendered `px` pixels wide: an instance at its natural size, alone on a
/// copy of `doc` that keeps its resources (the symbols it nests, patterns, images, swatches,
/// brushes, graphic styles) but none of its art.
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered> {
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
let (w, h) = symbol_size(doc, name);
let mut d = doc.clone();
let layer = d.alloc_id();
@@ -206,7 +206,7 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::scale_non_uniform(w / 20.0, h / 20.0);
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })).ok()?;
r.render_thumbnail(&d, id, px)
r.render_thumbnail_words(&d, id, px)
}
/// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn
@@ -218,7 +218,7 @@ fn render_art(
name: &str,
art: vectorcraft_geom::Rect,
(w, h): (u32, u32),
) -> Option<vectorcraft_render::Rendered> {
) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
let (aw, ah) = (art.width(), art.height());
if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) {
return None;
@@ -232,7 +232,7 @@ fn render_art(
let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }));
let view =
vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0));
r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
r.render_node_words(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
}
/// The active document's current symbol (`symbol.list`'s `current`), read without running a
+23 -2
View File
@@ -13,8 +13,9 @@ fn symbols(app: &mut VectorcraftApp) -> Vec<String> {
}
/// Pixels of `img` that something paints opaquely, and those of them that are red.
fn painted(img: &vectorcraft_render::Rendered) -> (usize, usize) {
let painted: Vec<&[u8; 4]> = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
fn painted(img: &vectorcraft_render::Rendered<Vec<u32>>) -> (usize, usize) {
let bytes: &[u8] = bytemuck::cast_slice(&img.pixels);
let painted: Vec<&[u8; 4]> = bytes.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
let red = painted.iter().filter(|p| p[0] > 150 && p[1] < 80 && p[2] < 80).count();
(painted.len(), red)
}
@@ -1320,6 +1321,26 @@ fn an_imported_symbols_thumbnail_frames_its_whole_art() {
assert!(orange(inset_x, inset_y) && orange(w - 1 - inset_x, h - 1 - inset_y), "{w} × {h}");
}
/// Both pictures of a symbol become images in the pixels they were rendered into.
#[test]
fn a_symbols_pictures_are_handed_to_their_images_without_a_copy() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap();
s.execute("symbol.new", &json!({"name": "Wide"})).unwrap();
let doc = &*s.doc().unwrap().doc;
let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds");
let pictures = SymbolPictures { doc, name: "Wide" };
for (what, key) in [
("the symbol", SymbolThumb::Symbol { key: 1 }),
("its art", SymbolThumb::Art { key: 1, w: 40, h: 30, art: [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits) }),
] {
crate::canvas::clear_handed_over();
let ThumbRender::Ready(image) = pictures.render(&key, &ThumbRequest::for_cell(40.0, 1.0)) else { panic!("{what} renders at once") };
crate::canvas::assert_handed_over(&image, what);
}
}
/// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol
/// "Dot", which no instance uses; "Dot" is current.
fn leaf_and_dot() -> VectorcraftApp {
@@ -11,7 +11,7 @@ use craft::ui::runtime::commands::CommandStates;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use super::asset_export::{menu_rows, menu_states};
use super::asset_export::{menu_rows, menu_states, thumb_image};
use crate::dialogs::ExportForScreensDialog;
use crate::tests::panel_harness::Panel;
use crate::{Services, VectorcraftApp};
@@ -1158,3 +1158,19 @@ fn tile_menu_collects_canvas_art_as_one_or_multiple_assets_and_disables_empty_se
assert_eq!(picked(&p).len(), if single { 1 } else { 2 });
}
}
/// A tile's image is made in the words its objects were rendered into, for one object and for several.
#[test]
fn an_assets_tile_image_holds_the_rendered_words_without_a_copy() {
let (app, _, [a, b]) = app(false);
let doc = &app.session.active().unwrap().doc;
let node = |id: u64| doc.node(vectorcraft_doc::NodeId(id)).expect("the square");
let mut r = vectorcraft_render::Renderer::new();
for (what, art) in [("one object", vec![node(a)]), ("two objects", vec![node(a), node(b)])] {
crate::canvas::clear_handed_over();
let image = thumb_image(&mut r, doc, &art, 40).expect("the squares draw");
assert_eq!(image.size, [40, 40], "{what}: the tile's size");
assert!(image.pixels.iter().any(|p| p.a() > 0), "{what}: the tile shows the art");
crate::canvas::assert_handed_over(&image, what);
}
}
@@ -320,3 +320,218 @@ fn arrowhead_select_lists_the_notched_arrow_after_arrow() {
panel.click("Notched Arrow");
assert_eq!(current_stroke(&panel.app()).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::NotchedArrow));
}
#[test]
fn dropdown_footer_manages_profiles_and_confirms_reset() {
use craft::ui::contract::Role;
use craft::ui::dialog::StackDialog as _;
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, "profile": "taperStart"})).unwrap();
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown shrinks to compact width: {:?}", panel.rect("Profile"));
panel.click_role("Profile", Role::COMBO_BOX);
assert!(!panel.shows("Flip Along"), "Flip Along button is not shown inside the dropdown");
assert!(!panel.shows("Flip Across"), "Flip Across button is not shown inside the dropdown");
assert!(panel.shows("Add to Profiles"), "dropdown shows Add to Profiles footer button");
assert!(panel.shows("Delete Profile"), "dropdown shows Delete Profile footer button");
assert!(panel.shows("Reset Profiles"), "dropdown shows Reset Profiles footer button");
assert!(!panel.enabled("Delete Profile"), "a built-in profile can't be deleted");
assert!(
panel.rect("Reset Profiles").left() >= panel.rect("Delete Profile").right() - 0.5
&& panel.rect("Delete Profile").left() >= panel.rect("Add to Profiles").right() - 0.5,
"Reset Profiles sits rightmost in the footer"
);
assert!(panel.rect("Wave").width() <= 165.0, "dropdown shrinks to fit its items: {:?}", panel.rect("Wave"));
// Selecting Uniform disables Delete Profile; Uniform cannot be deleted.
panel.click("Uniform");
panel.click_role("Profile", Role::COMBO_BOX);
assert!(!panel.enabled("Delete Profile"), "Uniform profile cannot be deleted");
// Custom profile: Add to Profiles asks for a name and saves the profile under it, and user-added rows hide
// their text captions in the dropdown.
panel.app().session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
panel.frame();
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Custom"));
panel.click("Add to Profiles");
assert!(panel.app().session.prefs.width_profiles.is_empty(), "Add to Profiles saves nothing before the name is given");
{
let mut app = panel.app();
let dialog = crate::tests::picks::open_dialogs(&app).first().map(|d| d.id).expect("Add to Profiles asks for a name");
crate::tests::picks::answer_dialog(&mut app, dialog, &[("name", serde_json::json!("Ribbon"))], true);
}
panel.frame();
let saved_label = panel.app().session.profile_entries().find(|e| !e.built_in).map(|e| e.label.to_owned()).unwrap();
assert_eq!(saved_label, "Ribbon", "the profile is saved under the name given");
// The name dialog may have closed the list on taking focus; the checks below read the open list.
if !panel.shows("Reset Profiles") {
panel.click_role("Profile", Role::COMBO_BOX);
}
assert!(panel.enabled("Delete Profile"), "the saved profile the stroke uses can be deleted");
let face_rect = panel.rect("Profile");
let popup_captions: Vec<_> = panel.painted(&saved_label).into_iter().filter(|r| !face_rect.contains(r.center())).collect();
assert!(popup_captions.is_empty(), "user-added profile shows no caption text in the pulldown: {popup_captions:?}");
assert!(!panel.painted("Wave").is_empty(), "built-in profile still shows its caption text");
// No three-dot menu buttons appear next to any profile row.
assert!(!panel.shows("More (Uniform)"));
assert!(!panel.shows("More (Wave)"));
assert!(!panel.shows(&format!("More ({saved_label})")));
// Clicking Reset Profiles closes the dropdown and opens the confirmation prompt ("Do you want to reset profiles?").
panel.click("Reset Profiles");
assert!(!panel.shows("Add to Profiles"), "dropdown closes when confirmation prompt opens");
let ctx = panel.ctx().clone();
{
let mut app = panel.app();
let (message, _, command) = crate::dialogs::confirm::open_question(&app).expect("reset confirmation is open");
assert_eq!(message, "Do you want to reset profiles?");
assert_eq!(command, "stroke.widthProfile.reset");
app.dialogs().unwrap().with(|host| {
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
assert!(host.cancel_by_id(&ctx, qid));
});
crate::dialogs::confirm::pump(&mut app, &ctx);
assert!(app.session.profile_entries().any(|e| !e.built_in), "cancelling reset preserves profiles");
}
// Confirming OK executes the reset.
panel.click_role("Profile", Role::COMBO_BOX);
panel.click("Reset Profiles");
let mut app = panel.app();
app.dialogs().unwrap().with(|host| {
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
host.set_json_field(&ctx, qid, "choice", serde_json::json!("proceed")).unwrap();
assert!(host.confirm_by_id(&ctx, qid));
});
crate::dialogs::confirm::pump(&mut app, &ctx);
assert!(app.session.profile_entries().all(|e| e.built_in), "Reset Profiles clears saved presets");
}
#[test]
fn dropdown_row_menu_deletes_saved_profiles_only() {
use craft::ui::contract::Role;
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 app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
panel.click_role("Profile", Role::COMBO_BOX);
// A built-in row offers no Delete Profile.
for built_in in ["Uniform", "Wave"] {
panel.secondary_click(built_in);
assert!(!panel.shows_role("Delete Profile", Role::MENU_ITEM), "{built_in} can't be deleted");
}
// A saved row's menu deletes it.
panel.secondary_click("Mine");
assert!(panel.shows_role("Delete Profile", Role::MENU_ITEM), "a saved profile offers Delete Profile");
panel.click_menu_item("Delete Profile");
assert!(!panel.app().session.profile_entries().any(|e| e.id == "Mine"), "the saved profile is deleted");
assert!(panel.app().session.profile_entries().any(|e| e.id == "wave"), "the built-ins stay");
}
#[test]
fn dropdown_expands_into_available_vertical_space() {
use craft::ui::contract::Role;
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();
for i in 0..10 {
session
.execute(
"stroke.widthPoint.set",
&serde_json::json!({"id": id, "t": 0.25 + 0.05 * f64::from(i), "left": 8.0 + f64::from(i), "right": 4.0}),
)
.unwrap();
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": format!("Saved {i}")})).unwrap();
}
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown stays compact even with custom profiles: {:?}", panel.rect("Profile"));
panel.click_role("Profile", Role::COMBO_BOX);
assert!(panel.shows("Saved 9"), "dropdown expands past 12 rows when space is available");
assert!(
panel.rect("Saved 9").bottom() - panel.rect("Uniform").top() > 350.0,
"dropdown opens taller when vertical space allows: uniform={:?}, last={:?}",
panel.rect("Uniform"),
panel.rect("Saved 9")
);
assert!(panel.shows("Reset Profiles"), "footer remains visible with expanded list");
}
#[test]
fn dropdown_keeps_sentinel_named_profile_interactive_and_commits_tab_preview() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
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": "__profile_separator__"})).unwrap();
session.execute("stroke.set", &serde_json::json!({"profile": "uniform"})).unwrap();
let app = crate::VectorcraftApp::new(session, Default::default());
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
// A saved profile literally named "__profile_separator__" stays selectable and applies.
panel.click_role("Profile", Role::COMBO_BOX);
assert!(panel.shows("__profile_separator__"));
panel.click("__profile_separator__");
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("__profile_separator__"));
// Keyboard preview followed by Tab commits the previewed profile instead of cancelling it.
panel.click_role("Profile", Role::COMBO_BOX);
panel.click("Uniform");
panel.click_role("Profile", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
panel.key(Key::Tab, Modifiers::NONE);
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
// A fractional scroll-wheel delta steps the closed profile control cleanly.
let face_center = panel.rect("Profile").center();
panel.scroll_at(face_center, -0.5);
assert_ne!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
}
#[test]
fn a_screen_reader_sets_and_steps_the_profile() {
use craft::ui::contract::Role;
use craft::ui::testing::focus::AccessActionKind;
let mut panel = Panel::new(app_with_line(), stroke::profile_select);
let picked = |panel: &Panel| current_stroke(&panel.app()).and_then(|s| s.profile);
let preset = |id: &str| WidthProfile::PRESETS.iter().find(|p| p.id == id).map(|p| p.points.to_vec());
// The value is the row's place in the list: Uniform, Lens, Taper Start, ...
let numeric = panel.numeric_role("Profile", Role::COMBO_BOX).expect("the drop-down reports a numeric value");
assert_eq!(numeric.value, Some(0.0), "Uniform is the first row");
assert_eq!(*numeric.range.end(), (WidthProfile::PRESETS.len() - 1) as f64, "the range ends at the last row");
assert_eq!(numeric.text.as_deref(), Some("Uniform"), "the value reads as the row's label");
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::SetValue(2.0));
assert_eq!(picked(&panel).map(|p| p.points), preset("taperStart"), "SetValue picks the third row");
assert_eq!(panel.numeric_role("Profile", Role::COMBO_BOX).and_then(|n| n.value), Some(2.0), "the value follows the pick");
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::Decrement);
assert_eq!(picked(&panel).map(|p| p.points), preset("lens"), "Decrement picks the row above");
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::Increment);
assert_eq!(picked(&panel).map(|p| p.points), preset("taperStart"), "Increment picks the row below");
}
+79 -27
View File
@@ -11,7 +11,7 @@ use craft::ui::layout_components::{Row, Stack};
use craft::ui::pickers::Select;
use craft::ui::text::{NumberField, link_toggle};
use craft::ui::value_drag::Slider;
use egui::Ui;
use egui::{IdSalt, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
use vectorcraft_geom::shapes::CornerKind;
@@ -42,14 +42,22 @@ const SIDES_SLIDER: RangeInclusive<f64> = 3.0..=20.0;
pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, headed: bool) -> bool {
match live {
LiveShape::Rectangle { .. } => under_heading(ui, headed.then(|| tl!("Rectangle Properties:")), |ui| {
angle_row(app, ui, live, "rectangleAngle");
let target = shape_edit_target(app);
angle_row(app, ui, live, "rectangleAngle", target);
corner_radius_row(app, ui, n);
}),
LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| polygon_rows(app, ui, n, live)),
LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| star_rows(app, ui, live)),
LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| {
let target = shape_edit_target(app);
polygon_rows(app, ui, n, live, target);
}),
LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| {
let target = shape_edit_target(app);
star_rows(app, ui, live, target);
}),
LiveShape::Ellipse { pie, .. } => under_heading(ui, Some(tl!("Ellipse Properties:")), |ui| {
angle_row(app, ui, live, "ellipseAngle");
pie_rows(app, ui, *pie);
let target = shape_edit_target(app);
angle_row(app, ui, live, "ellipseAngle", target);
pie_rows(app, ui, *pie, target);
}),
LiveShape::Line { .. } => return line_rows(app, ui, live),
_ => return false,
@@ -57,6 +65,27 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l
true
}
/// The edit target of the live shape number fields: the active document, how many times File › Revert replaced its
/// content, how many times Undo or Redo restored an older snapshot, how many times another rollback put one back
/// (`DocState::rollbacks`; after either, the same node ID can name another object), and the selected objects in
/// selection order, which `object.setLiveShape` changes. The first selected object picks the rows, so the same objects
/// in another order can put another property's field in the same place. A field drops a value typed and not yet
/// committed when this changes, even where the newly selected shape shows the same value. Hashed once per (document
/// uid, revision): the panels read it every frame, and Select All can select hundreds of thousands of shapes. The
/// revision is not part of the target, so an edit that leaves the selection as it is keeps the value typed so far.
pub(crate) fn shape_edit_target(app: &mut VectorcraftApp) -> IdSalt {
let Some(st) = app.session.active() else { return IdSalt::new(None::<()>) };
let key = (st.uid, st.revision);
if let Some((k, target)) = app.canvas.shape_edit_target
&& k == key
{
return target;
}
let target = IdSalt::new(Some((st.uid, st.reverts, st.history_restores, st.rollbacks, st.selection.objects.as_slice())));
app.canvas.shape_edit_target = Some((key, target));
target
}
/// `rows` under a sub-heading, or bare when there is none.
fn under_heading(ui: &mut Ui, heading: Option<&'static str>, mut rows: impl FnMut(&mut Ui)) {
match heading {
@@ -75,7 +104,16 @@ fn set_live_shape(app: &mut VectorcraftApp, params: Value) {
}
/// One labelled number field whose edits send `params(number)` to `object.setLiveShape`; a scrub is one undo step.
fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: Option<f64>, quantity: Quantity, params: impl Fn(f64) -> Value) {
/// `target` is the field's [`shape_edit_target`].
fn number_row(
app: &mut VectorcraftApp,
ui: &mut Ui,
label: &'static str,
value: Option<f64>,
quantity: Quantity,
target: IdSalt,
params: impl Fn(f64) -> Value,
) {
let mut edit = None;
Field::new(label).show(ui, |ui, _| {
let bind = Bind::given(value);
@@ -84,7 +122,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value:
Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1),
Quantity::Ratio => NumberField::new(label, bind).range(0.001..=1.0).step(0.001).commit_decimals(3),
};
edit = Some(field.show(ui).edit);
edit = Some(field.edit_target(target).show(ui).edit);
});
if let Some(edit) = edit {
// `Scope`, not `Preview`: `Preview` names one command, and each field sends its own params.
@@ -99,9 +137,9 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value:
/// A live rectangle's, ellipse's or polygon's Angle row (counterclockwise): the angle the selected shapes of its
/// kind share, blank when they differ. `key` is the `object.setLiveShape` param an edit sets, which turns each of
/// them about its own center.
fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str) {
fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str, target: IdSalt) {
let angle = shared_shape_angle(app, live);
number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, |a| json!({ key: a }));
number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, target, |a| json!({ key: a }));
}
/// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None` when they
@@ -151,9 +189,11 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool {
if !only_lines_selected(app) {
return false;
}
let target = shape_edit_target(app);
under_heading(ui, Some(tl!("Line Properties:")), |ui| {
number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, |l| json!({ "lineLength": l }));
number_row(app, ui, tl!("Line Angle"), Some(live.line_angle().unwrap_or(0.0)), Quantity::Degrees, |a| json!({ "lineAngle": a }));
number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, target, |l| json!({ "lineLength": l }));
let angle = Some(live.line_angle().unwrap_or(0.0));
number_row(app, ui, tl!("Line Angle"), angle, Quantity::Degrees, target, |a| json!({ "lineAngle": a }));
});
true
}
@@ -161,13 +201,13 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool {
/// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the whole
/// ellipse), the Constrain Pie Angle link beside them, and Invert Pie, which shows the other part of it. With the
/// link on, a typed angle moves the other one by as much, so each selected ellipse keeps its span.
fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) {
fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), target: IdSalt) {
let constrain = app.ui.constrain_pie_angle;
// The link sits halfway between the two fields, with no bracket drawn to them.
Row::new().bracket(Bracket::Unlinked).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
for (label, key, v) in [(tl!("Pie Start Angle"), "pieStart", pie.0), (tl!("Pie End Angle"), "pieEnd", pie.1)] {
number_row(app, ui, label, Some(v), Quantity::Degrees, |a| {
number_row(app, ui, label, Some(v), Quantity::Degrees, target, |a| {
if constrain { json!({ key: a, "constrainPie": true }) } else { json!({ key: a }) }
});
}
@@ -181,16 +221,16 @@ fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) {
/// A live polygon's Polygon Properties: its side count (a field and a slider), angle (counterclockwise), corner
/// type and radius, radius (center to vertex) and side length, and Make Sides Equal, which an uneven scale enables.
fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape) {
fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, target: IdSalt) {
let LiveShape::Polygon { sides, .. } = live else { return };
let radius = live.polygon_radius();
let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin());
sides_row(app, ui, *sides);
angle_row(app, ui, live, "polygonAngle");
sides_row(app, ui, *sides, target);
angle_row(app, ui, live, "polygonAngle", target);
corner_kind_row(app, ui, corner_style(app, n).1);
Field::new(tl!("Corner Radius")).show(ui, |ui, _| corner_radius_field(app, ui, n));
number_row(app, ui, tl!("Radius"), radius, Quantity::Length, |r| json!({ "polygonRadius": r }));
number_row(app, ui, tl!("Side Length"), side, Quantity::Length, |l| json!({ "sideLength": l }));
number_row(app, ui, tl!("Radius"), radius, Quantity::Length, target, |r| json!({ "polygonRadius": r }));
number_row(app, ui, tl!("Side Length"), side, Quantity::Length, target, |l| json!({ "sideLength": l }));
if Button::new(tl!("Make Sides Equal")).enabled(!live.polygon_sides_equal()).show(ui).clicked() {
set_live_shape(app, json!({"makeSidesEqual": true}));
}
@@ -200,18 +240,27 @@ fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShap
/// over [`SIDES_SLIDER`]. A typed count is one undo step. A slider drag previews the count and its release records
/// one undo step; Escape during the drag puts the count back. A click on the rail or an arrow key sets the count in
/// one undo step. A count above 20 puts the thumb at the rail's right end, and screen readers read the real count.
fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) {
count_row(app, ui, tl!("Sides"), "sides", sides, 3.0);
fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32, target: IdSalt) {
count_row(app, ui, tl!("Sides"), "sides", sides, 3.0, target);
}
/// A count row (Polygon Properties' Sides, Star Properties' Points) whose edits set `key`: a field that takes `min`
/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes.
fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64) {
/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. The field drops an unfinished value when
/// `target` changes.
fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64, target: IdSalt) {
let count = f64::from(sides);
let (mut typed, mut slid) = (None, None);
Field::new(label).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
typed = Some(NumberField::new(label, Bind::given(Some(count))).range(min..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit);
typed = Some(
NumberField::new(label, Bind::given(Some(count)))
.range(min..=1000.0)
.fixed_decimals(0)
.id_salt("field")
.edit_target(target)
.show(ui)
.edit,
);
let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end());
slid = Some(
Slider::new(Bind::given(count.clamp(lo, hi)), SIDES_SLIDER)
@@ -241,10 +290,10 @@ fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'
/// A live star's Star Properties: its point count (a field that takes 2 to 1000 and a slider over 3 to 20) and its
/// ratio (inner radius over outer radius, 0.001 to 1). Its corners stay with Live Corners and Direct Selection, as any
/// path's do.
fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) {
fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, target: IdSalt) {
let Some(points) = live.star_points() else { return };
count_row(app, ui, tl!("Points"), "points", points, 2.0);
number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, |r| json!({ "ratio": r }));
count_row(app, ui, tl!("Points"), "points", points, 2.0, target);
number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, target, |r| json!({ "ratio": r }));
}
/// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the
@@ -259,3 +308,6 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option<CornerKin
apply_edits(app, &edit, EditPath::Scope, |app, k, _| set_live_shape(app, json!({ "kind": k })));
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,421 @@
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use vectorcraft_doc::Unit;
use super::*;
use crate::tests::panel_harness::Panel;
/// An app with a new document holding two shapes made by `cmd` with `a` and `b`, and their ids.
fn two(cmd: &str, a: Value, b: Value) -> (VectorcraftApp, Value, Value) {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let a = app.run(cmd, a).unwrap()["id"].clone();
let b = app.run(cmd, b).unwrap()["id"].clone();
(app, a, b)
}
/// Selects `a`, types "3+" into field `name` drawn by `draw`, selects `b`, then types "7" and Enter. Returns the
/// field's value just after `b` is selected, after the Enter, and with `a` selected again.
fn type_across_a_selection_change(
app: VectorcraftApp,
draw: fn(&mut VectorcraftApp, &mut Ui),
a: &Value,
b: &Value,
name: &str,
) -> (Option<String>, Option<String>, Option<String>) {
let mut app = app;
app.run("select.set", json!({"ids": [a]})).unwrap();
let mut p = Panel::new(app, draw);
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [b]})).unwrap();
p.frame();
let switched = p.value_role(name, Role::SPIN_BUTTON);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
let after = p.value_role(name, Role::SPIN_BUTTON);
p.app().run("select.set", json!({"ids": [a]})).unwrap();
p.frame();
(switched, after, p.value_role(name, Role::SPIN_BUTTON))
}
/// Checks that a value typed into field `name` for `a` and not finished is dropped when `b`, which shows `shown`
/// there as `a` does, is selected: the field shows `shown`, "7" and Enter then give `b` 7 (`seven`), not 3+7, and
/// `a` keeps `shown`.
fn check_field(app: VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), a: &Value, b: &Value, name: &str, shown: &str, seven: &str) {
let (switched, after, first) = type_across_a_selection_change(app, draw, a, b, name);
assert_eq!(switched.as_deref(), Some(shown), "{name}: the field shows the newly selected shape's value");
assert_eq!(after.as_deref(), Some(seven), "{name}: the newly selected shape takes 7, not the unfinished 3+ and 7");
assert_eq!(first.as_deref(), Some(shown), "{name}: the shape the value was first typed for keeps its value");
}
fn pt(v: f64) -> String {
Unit::Points.format(v)
}
fn rectangles() -> (VectorcraftApp, Value, Value) {
two("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}), json!({"x": 100, "y": 0, "width": 30, "height": 30}))
}
fn polygons() -> (VectorcraftApp, Value, Value) {
two("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5}), json!({"cx": 200, "cy": 60, "radius": 40, "sides": 5}))
}
fn ellipses() -> (VectorcraftApp, Value, Value) {
two("shape.ellipse", json!({"x": 0, "y": 0, "width": 40, "height": 30}), json!({"x": 100, "y": 0, "width": 40, "height": 30}))
}
fn lines() -> (VectorcraftApp, Value, Value) {
two("shape.line", json!({"x1": 20, "y1": 20, "x2": 120, "y2": 20}), json!({"x1": 20, "y1": 200, "x2": 120, "y2": 200}))
}
#[test]
fn an_unfinished_rectangle_angle_does_not_reach_another_rectangle() {
let (app, a, b) = rectangles();
check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°");
let (app, a, b) = rectangles();
check_field(app, crate::panels::properties::show, &a, &b, "Angle", "0°", "7°");
}
#[test]
fn an_unfinished_polygon_sides_count_does_not_reach_another_polygon() {
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Sides", "5", "7");
}
#[test]
fn an_unfinished_polygon_angle_radius_or_side_length_does_not_reach_another_polygon() {
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°");
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Radius", &pt(40.0), &pt(7.0));
let (app, a, b) = polygons();
let side = pt(2.0 * 40.0 * (std::f64::consts::PI / 5.0).sin());
check_field(app, crate::panels::transform::show, &a, &b, "Side Length", &side, &pt(7.0));
}
/// After Undo removes the shape a value was typed for, a new shape can take its node ID. The value is dropped when
/// that shape is selected, so it does not reach an object it was not typed for.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_undone_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [rect]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("edit.undo", json!({})).unwrap();
let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(ellipse, rect, "the ellipse takes the undone rectangle's node ID");
p.app().run("select.set", json!({"ids": [ellipse]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the ellipse's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7");
}
/// A canceled undo group removes the shape a value was typed for, and a new shape can take its node ID. The value is
/// dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_groups_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("edit.undoGroup.begin", json!({})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [rect]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("edit.undoGroup.end", json!({"cancel": true})).unwrap();
let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(ellipse, rect, "the ellipse takes the canceled group's rectangle's node ID");
p.app().run("select.set", json!({"ids": [ellipse]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new shape's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7");
}
/// A canceled interaction removes the shape its preview made and a Corner Radius value was typed for, and a new shape
/// made by `cmd` with `args` takes its node ID. The value is dropped when that shape is selected in the panel `draw`
/// draws.
fn check_corner_radius_after_a_canceled_preview(draw: fn(&mut VectorcraftApp, &mut Ui), cmd: &str, args: Value, panel: &str) {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Shape").unwrap();
let first = app.session.preview(cmd, &args).unwrap()["id"].clone();
let selected = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([first]), "{panel} {cmd}: the preview selects its shape");
let mut p = Panel::new(app, draw);
p.click_role("Corner Radius", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().session.cancel_interaction().unwrap();
let second = p.app().run(cmd, args).unwrap()["id"].clone();
assert_eq!(second, first, "{panel} {cmd}: the new shape takes the canceled preview's shape's node ID");
p.app().run("select.set", json!({"ids": [second]})).unwrap();
p.frame();
let shown = p.value_role("Corner Radius", Role::SPIN_BUTTON);
assert_eq!(shown.as_deref(), Some(pt(0.0).as_str()), "{panel} {cmd}: the field shows the new shape's corner radius");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
let after = p.value_role("Corner Radius", Role::SPIN_BUTTON);
assert_eq!(after.as_deref(), Some(pt(7.0).as_str()), "{panel} {cmd}: the new shape takes 7, not the unfinished 3+ and 7");
}
#[test]
fn an_unfinished_rectangle_corner_radius_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let rect = json!({"x": 0, "y": 0, "width": 30, "height": 30});
check_corner_radius_after_a_canceled_preview(crate::panels::transform::show, "shape.rectangle", rect, "Transform");
}
#[test]
fn an_unfinished_polygon_corner_radius_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let polygon = json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5});
check_corner_radius_after_a_canceled_preview(crate::panels::transform::show, "shape.polygon", polygon, "Transform");
}
#[test]
fn an_unfinished_rectangle_corner_radius_in_the_properties_panel_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let rect = json!({"x": 0, "y": 0, "width": 30, "height": 30});
check_corner_radius_after_a_canceled_preview(crate::panels::properties::show, "shape.rectangle", rect, "Properties");
}
#[test]
fn an_unfinished_polygon_corner_radius_in_the_properties_panel_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let polygon = json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5});
check_corner_radius_after_a_canceled_preview(crate::panels::properties::show, "shape.polygon", polygon, "Properties");
}
/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which removes the editing copy a value
/// was typed for, and a new shape can take the copy's node ID. The value is dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_unchanged_symbol_copys_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap();
app.run("symbol.new", json!({"name": "Box"})).unwrap();
app.run("symbol.edit", json!({})).unwrap();
let copy = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(copy.len(), 1, "symbol editing selects the editing copy");
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("symbol.exitEditing", json!({})).unwrap();
p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap();
let rect = p.app().run("shape.rectangle", json!({"x": 200, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(rect, json!(copy[0].0), "the second new rectangle takes the editing copy's node ID");
p.app().run("select.set", json!({"ids": [rect]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7");
}
/// A canceled interaction removes a shape its preview made and a value was typed for, and a new shape can take that
/// shape's node ID. The value is dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Rectangle").unwrap();
let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
let selected = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([previewed]), "the preview selects its rectangle");
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().session.cancel_interaction().unwrap();
let rect = p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(rect, previewed, "the new rectangle takes the canceled preview's rectangle's node ID");
p.app().run("select.set", json!({"ids": [rect]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7");
}
/// A replacement preview reuses the discarded rectangle's node ID and drops its unfinished angle.
/// The replacement rectangle takes the next angle typed into the field.
#[test]
fn an_unfinished_angle_does_not_reach_a_replacement_preview_that_reuses_a_discarded_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Rectangle").unwrap();
let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
let steps = json!({"commands": [
{"command": "shape.rectangle", "params": {"x": 100, "y": 10, "width": 40, "height": 30}}
]});
let replacement = p.app().session.preview("command.batch", &steps).unwrap();
let rect = replacement["results"][0]["id"].clone();
assert_eq!(rect, previewed, "the replacement rectangle reuses the discarded rectangle's node ID");
let selected = p.app().session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([rect]), "the preview selects the replacement rectangle");
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the replacement rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the replacement rectangle takes 7°, not the unfinished 3+ and 7");
}
#[test]
fn an_unfinished_ellipse_angle_or_pie_angle_does_not_reach_another_ellipse() {
for (name, shown) in [("Angle", "0°"), ("Pie Start Angle", "0°"), ("Pie End Angle", "360°")] {
let (app, a, b) = ellipses();
check_field(app, crate::panels::transform::show, &a, &b, name, shown, "7°");
}
}
#[test]
fn an_unfinished_star_points_or_ratio_does_not_reach_another_star() {
let stars = || {
two(
"shape.star",
json!({"cx": 60, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}),
json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}),
)
};
let (app, a, b) = stars();
check_field(app, crate::panels::transform::show, &a, &b, "Points", "5", "7");
let (app, a, b) = stars();
check_field(app, crate::panels::transform::show, &a, &b, "Ratio", "0.5", "1");
}
#[test]
fn an_unfinished_line_length_or_angle_does_not_reach_another_line() {
let (app, a, b) = lines();
check_field(app, crate::panels::transform::show, &a, &b, "Line Length", &pt(100.0), &pt(7.0));
let (app, a, b) = lines();
check_field(app, crate::panels::transform::show, &a, &b, "Line Angle", "0°", "7°");
}
/// A value typed for a rectangle and not finished is dropped when File Revert replaces the document's content or
/// another document becomes active, even where the selection has the same ids and the same angle.
#[test]
fn an_unfinished_angle_is_dropped_by_file_revert_or_another_document() {
type Change = fn(&mut VectorcraftApp);
let changes: [(&str, Change); 2] = [
("File Revert", |app| {
// The same content again, with the same rectangle selected after it.
let st = app.session.active().unwrap();
let (doc, ids) = ((*st.doc).clone(), st.selection.objects.clone());
assert!(app.session.replace_document(0, doc));
app.run("select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
}),
("another document became active", |app| {
app.run("document.activate", json!({"index": 1})).unwrap();
}),
];
// The angle of the rectangle in each open document, in whole degrees, and the index of the active document.
let angles = |p: &Panel| -> (Vec<Option<i64>>, Option<usize>) {
let app = p.app();
let docs = app.session.documents();
let angles = docs.iter().map(|st| st.doc.node(st.selection.objects[0]).and_then(|n| n.live_shape()?.shape_angle()).map(|a| a.round() as i64));
let active = app.session.active().map(|a| a.uid);
(angles.collect(), docs.iter().position(|st| Some(st.uid) == active))
};
for (change, apply) in changes {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
for _ in 0..2 {
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
}
app.run("document.activate", json!({"index": 0})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
apply(&mut p.app());
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "{change}: the field shows the rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let (got, active) = angles(&p);
let active = active.unwrap();
let mut want = vec![Some(0), Some(0)];
want[active] = Some(7);
assert_eq!(got, want, "{change}: the rectangle takes 7°, not the unfinished 3+ and 7");
}
}
/// While the selection stays the same, a value typed over several frames is kept and committed whole, also when an
/// edit to an unselected object changes the document in between.
#[test]
fn a_value_typed_with_the_same_selection_is_kept_across_frames() {
let (mut app, a, b) = rectangles();
app.run("select.set", json!({"ids": [a]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.frame();
let revision = p.app().session.active().unwrap().revision;
p.app().run("stroke.set", json!({"ids": [b], "weight": 4})).unwrap();
assert_ne!(p.app().session.active().unwrap().revision, revision, "the document changed");
p.frame();
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle");
}
/// An unfinished Sides value is dropped when selecting the star first replaces Sides with Points.
#[test]
fn an_unfinished_sides_count_does_not_reach_a_star_selected_first() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let polygon = app.run("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5})).unwrap()["id"].clone();
let star = app.run("shape.star", json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [polygon, star]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Sides", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [star, polygon]})).unwrap();
p.frame();
assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("5"), "the field shows the star's points");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("7"), "the star takes 7 points, not the unfinished 3+ and 7");
}
/// An Angle value typed across frames is kept when another corner of the same rectangle is Direct-Selected.
#[test]
fn a_value_typed_for_the_same_shape_is_kept_when_direct_selected_anchors_change() {
let (mut app, a, _) = rectangles();
let id = a.as_u64().unwrap();
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap();
p.frame();
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle");
}
+56 -2
View File
@@ -122,8 +122,8 @@ fn thumb_image(doc: &Arc<Document>, obj: &Node, own_mask: bool, px: u32, bg: Opt
} else {
obj
};
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
Some(crate::canvas::color_image(&img))
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
Some(crate::canvas::color_image_owned(img))
}
impl ThumbSource<MaskKey> for MaskThumbs<'_> {
@@ -744,6 +744,41 @@ mod tests {
assert_eq!(opacity_of(&panel, &b), 0.01, "Undo drops the unfinished value: 1%, not 20+1");
}
/// A canceled undo group drops an unfinished Opacity expression, though the object it takes away and the object
/// made and selected after it have the same id and opacity.
#[test]
fn unfinished_opacity_is_dropped_by_a_canceled_undo_group() {
let mut app = new_app();
run_cmd(&mut app, "edit.undoGroup.begin", json!({}));
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a]}));
let mut panel = Panel::new(app, show);
unfinished_opacity(&mut panel);
run_cmd(&mut panel.app(), "edit.undoGroup.end", json!({"cancel": true}));
let b = run_cmd(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone();
assert_eq!(b, a, "the new rectangle has the canceled group's rectangle's id");
run_cmd(&mut panel.app(), "select.set", json!({"ids": [b]}));
finish_opacity(&mut panel);
assert_eq!(opacity_of(&panel, &b), 0.01, "the canceled group drops the unfinished value: 1%, not 20+1");
}
/// Discard Empty Type drops an unfinished Opacity expression when it takes back the step that made the empty
/// text, though the object made and selected after it has the same id and opacity.
#[test]
fn unfinished_opacity_is_dropped_by_discard_empty_type() {
let mut app = new_app();
let a = run_cmd(&mut app, "text.create", json!({"x": 10, "y": 40, "text": ""}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a]}));
let mut panel = Panel::new(app, show);
unfinished_opacity(&mut panel);
run_cmd(&mut panel.app(), "text.discardEmpty", json!({"id": a}));
let b = run_cmd(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone();
assert_eq!(b, a, "the new rectangle has the discarded text's id");
run_cmd(&mut panel.app(), "select.set", json!({"ids": [b]}));
finish_opacity(&mut panel);
assert_eq!(opacity_of(&panel, &b), 0.01, "Discard Empty Type drops the unfinished value: 1%, not 20+1");
}
/// The same objects selected in another order keep an unfinished Opacity expression.
#[test]
fn unfinished_opacity_stays_when_the_same_objects_are_selected_in_another_order() {
@@ -879,6 +914,25 @@ mod tests {
assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back");
}
/// The object and mask thumbnails, on a background or none, hold the pixels they were rendered into.
#[test]
fn object_and_mask_thumbnails_are_handed_to_their_images_without_a_copy() {
let mut app = new_app();
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let b = run_cmd(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a, b]}));
run_cmd(&mut app, "transparency.makeOpacityMask", json!({}));
let n = state(&mut app).1.expect("the masked object");
let doc = app.session.active().unwrap().doc.clone();
for own_mask in [false, true] {
for bg in [None, Some([255; 4])] {
crate::canvas::clear_handed_over();
let image = thumb_image(&doc, &n, own_mask, 44, bg).expect("the thumbnail draws");
crate::canvas::assert_handed_over(&image, &format!("mask {own_mask}, background {bg:?}"));
}
}
}
#[test]
fn a_highlighted_blend_mode_applies_only_once_it_is_chosen() {
use egui::{Key, Modifiers};
+1 -1
View File
@@ -186,7 +186,7 @@ fn categories(app: &VectorcraftApp) -> impl Iterator<Item = &'static str> {
let _ = app;
None
};
PREF_CATEGORIES.iter().copied().chain(agents)
PREF_CATEGORIES.iter().copied().chain([crate::language_packs::PAGE]).chain(agents)
}
/// The agent settings as the AI Integrations page edits them; `None` where the window has no such page.
+16 -6
View File
@@ -380,15 +380,22 @@ impl Live<'_> {
impl PreferencesModel for Live<'_> {
fn pages(&self) -> Vec<PageSpec<'_>> {
let pages = PREF_CATEGORIES.iter().map(|&cat| self.page(cat));
let mut pages: Vec<PageSpec<'_>> = PREF_CATEGORIES.iter().map(|&cat| self.page(cat)).collect();
// Language Packs after Hyphenation: a page of its own, which installs and removes at once (nothing waits for
// OK, and there is nothing to reset).
let packs = PageSpec::custom(crate::language_packs::PAGE, tl!(crate::language_packs::PAGE))
.resettable(false)
.keywords(tl!("spelling dictionary hyphenation language download install remove"));
let at = pages.iter().position(|p| p.id == "Hyphenation").map_or(pages.len(), |i| i + 1);
pages.insert(at, packs);
// The agent settings, drawn whole by the framework's Agents page, on the desktop.
#[cfg(not(target_arch = "wasm32"))]
let pages = pages.chain(self.app.agents.is_some().then(|| {
if self.app.agents.is_some() {
use crate::agents::PAGE_TITLE;
let keywords = "agents AI MCP ArtCraft Launcher control port folders";
PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false)
}));
pages.collect()
pages.push(PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false));
}
pages
}
fn set(&mut self, key: &str, value: PrefValue) {
@@ -464,7 +471,10 @@ impl PreferencesModel for Live<'_> {
if page == crate::agents::PAGE_TITLE {
return agents_page(self, ui);
}
let _ = (ui, page);
if page == crate::language_packs::PAGE {
crate::language_packs::page(self.app, ui);
}
// Nothing of the draft changes: a pack installs or is removed at once.
false
}
+6
View File
@@ -155,6 +155,12 @@ pub fn revision() -> u64 {
state.revision * 2 + u64::from(state.note_at(now()) == Some(SLOW))
}
/// Moves [`revision`] on this test's thread with the listing left as it was, as a read that finds the same scripts does.
#[cfg(test)]
pub(crate) fn bump_revision() {
state().revision += 1;
}
/// Read the Scripts folder again, unless the session has no folder (the web, and a run without
/// preferences) or the context has no host. A read asked for while one runs waits for it (the
/// queue runs one job per folder). `ctx` is asked to draw when the read ends.
+6
View File
@@ -308,6 +308,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[
("color", "Color", "palette"),
("colorGuide", "Color Guide", "dc-color-guide"),
("swatches", "Swatches", "swatch-book"),
(crate::panels::swatch_strip::ID, "Swatch Strip", "swatch-book"),
("brushes", "Brushes", "paintbrush"),
("symbols", "Symbols", "spray-can"),
("patternOptions", "Pattern Options", "grid-3x3"),
@@ -997,6 +998,10 @@ pub struct UiState {
/// The Text Import Options confirmed last (`file.place`'s `text` options; null: never used).
#[serde(default, skip_serializing_if = "Value::is_null")]
pub text_import: Value,
/// The text files File › Open opened while Text Import Options was already open, each asked
/// about once it closes, the next one first.
#[serde(skip)]
pub(crate) text_opens: Vec<crate::dialogs::text_import::TextOpen>,
/// The documents (uids) whose Missing Fonts dialog waits until no dialog is open, the next one to
/// show first.
#[serde(skip)]
@@ -1635,6 +1640,7 @@ impl Default for UiState {
place_link: true,
place_import_options: true,
text_import: Value::Null,
text_opens: vec![],
pending_fonts: vec![],
stopped_plugin: None,
proof_setup: None,
+14
View File
@@ -298,6 +298,15 @@ impl Panel {
self.after();
}
/// A screen reader's action `kind` on the control of `role` named `name`.
pub(crate) fn access_role(&mut self, name: &str, role: Role, kind: craft::ui::testing::focus::AccessActionKind) {
self.frame();
let target = self.look_role(name, role);
self.take_input();
self.fixture.access(kind, &target);
self.after();
}
/// Turns the wheel by `dy` points over `at`.
pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) {
self.frame_with(vec![Event::PointerMoved(at)]);
@@ -486,6 +495,11 @@ impl Panel {
self.fixture.tree().value_of(self.look_role(name, role).node).map(str::to_owned)
}
/// The numeric value, range and step that the control of `role` named `name` reports to screen readers.
pub(crate) fn numeric_role(&self, name: &str, role: Role) -> Option<craft::ui::contract::Numeric> {
self.fixture.tree().numeric_of(self.look_role(name, role).node)
}
/// Whether a label named `name` has exactly `value`, where a field's static label may share its name and role.
pub(crate) fn label_has_value(&self, name: &str, value: &str) -> bool {
let tree = self.fixture.tree();
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more