mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge current main into Step and Repeat
This commit is contained in:
commit
da851068bf
315 files changed
+21210
-2032
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
|
||||
crates/cad/tests/data/*.dxf -text
|
||||
@@ -38,27 +38,32 @@
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 1/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 2/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 3/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 4/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 5/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 5/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 6/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
@@ -130,7 +135,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -39,11 +39,12 @@ jobs:
|
||||
dev-strip: true
|
||||
# The workspace crates also build without line tables. A panic still names its file and line.
|
||||
dev-debug: "0"
|
||||
# Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates,
|
||||
# and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)`
|
||||
# passes only when all five did. On pushes to main, a `cache warm` leg builds what every
|
||||
# shard builds and saves the dependency cache.
|
||||
test-shards: 5
|
||||
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
|
||||
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
|
||||
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
|
||||
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
|
||||
# saves the dependency cache.
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
|
||||
@@ -7,9 +7,26 @@ on:
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A push to main saves the Windows cache entry that pull requests restore.
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A weekly run on main saves a fresh entry after a new stable Rust changes the cache key.
|
||||
schedule:
|
||||
- cron: "23 6 * * 1"
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -18,15 +35,14 @@ concurrency:
|
||||
group: print-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
jobs:
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
|
||||
# but never save one; a manual run on main saves the cache they restore.
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pushes to main, the weekly run and
|
||||
# manual runs on main save the cache; pull requests restore it and never save one.
|
||||
windows:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-2022"]'
|
||||
# A change to Cargo.lock finds no cache (only main saves one) and builds everything cold:
|
||||
# about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests.
|
||||
# A run that finds no cache builds everything cold, which took 76 to 126 minutes.
|
||||
timeout-minutes: 150
|
||||
# As in ci.yml: test binaries without debug info or symbols, and workspace crates without
|
||||
# line tables. A panic still names its file and line.
|
||||
@@ -36,10 +52,14 @@ jobs:
|
||||
craft-fonts-ref: ""
|
||||
tools: ""
|
||||
targets: ""
|
||||
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
# Both test runs select the same two packages, so Cargo resolves features once and the
|
||||
# second run reuses the first run's dependencies. The first runs every test of the app
|
||||
# (`--bin vectorcraft --test it`), the second the UI crate's `tests::printps` tests. A filter
|
||||
# that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
command: |
|
||||
set -o pipefail
|
||||
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
|
||||
cargo test --locked -p vectorcraft
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --bin vectorcraft --test it
|
||||
log="$RUNNER_TEMP/printps.log"
|
||||
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
|
||||
@@ -42,6 +42,7 @@ jobs:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
macos-runner: macos-15
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
@@ -10,7 +11,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
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.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
Generated
+158
-172
File diff suppressed because it is too large.
Load diff
+50
-54
@@ -4,53 +4,55 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.24.1"
|
||||
version = "0.25.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# Language packs: the Craft apps' shared font store installs them (#4936).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] }
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -86,7 +88,6 @@ vectorcraft-apischema = { path = "crates/apischema" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
peniko = "0.6"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = { version = "1", features = ["float_roundtrip"] }
|
||||
@@ -156,10 +157,8 @@ egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
webbrowser = "1"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
@@ -193,25 +192,22 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -163,6 +163,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-29: Match Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the other selected objects take the width, the height or both, the bounding-box angle and the stacking place of the key object, or of the top or the bottom selected object, about a reference point, with Preview, as one undo step (`addon.arrange.match`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -211,6 +211,9 @@ fn main() -> ExitCode {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac_fonts::install();
|
||||
prefs_dir::install_fonts();
|
||||
// The Language packs installed in the shared font store; `proof.installPack` returns once
|
||||
// installed.
|
||||
prefs_dir::use_language_packs();
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// Before any subcommand attaches the plug-in folder.
|
||||
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
|
||||
|
||||
@@ -20,14 +20,15 @@ vectorcraft-format = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
craft = { workspace = true, features = ["ui", "keymap", "automation", "platform"] }
|
||||
egui = { workspace = true }
|
||||
egui_extras = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# Image loaders for `src/web.rs`, which builds only for wasm32.
|
||||
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 = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -5,6 +5,10 @@ dist = "../../dist/web"
|
||||
public_url = "./"
|
||||
filehash = true
|
||||
|
||||
[tools]
|
||||
# Binaryen 123 crashes while optimizing the release bundle; keep the optimizer explicit.
|
||||
wasm_opt = "version_133"
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8766
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The hand-off from the browser's input hook to the visible UI pass.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use egui::{DroppedFileHandle, Pos2, RawInput};
|
||||
|
||||
/// CSS pixels from the canvas origin, and whether Shift was held.
|
||||
pub(crate) type DragPosition = (f32, f32, bool);
|
||||
|
||||
pub(crate) struct DropBatch {
|
||||
pub(crate) files: Vec<DroppedFileHandle>,
|
||||
pub(crate) pos: Option<Pos2>,
|
||||
pub(crate) shift: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FileDrops(Vec<DroppedFileHandle>);
|
||||
|
||||
impl FileDrops {
|
||||
pub(crate) fn capture(&mut self, raw: &mut RawInput) {
|
||||
// The shared router reads dropped files at the start of the pass, before the web UI runs.
|
||||
self.0.append(&mut raw.dropped_files);
|
||||
}
|
||||
|
||||
pub(crate) fn take(&mut self, ctx: &egui::Context, position: &Cell<Option<DragPosition>>) -> Option<DropBatch> {
|
||||
let files = std::mem::take(&mut self.0);
|
||||
if files.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let at = position.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let pos = at.map(|(x, y, _)| egui::pos2(x / z, y / z));
|
||||
let shift = at.is_some_and(|(_, _, shift)| shift);
|
||||
Some(DropBatch { files, pos, shift })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Svg;
|
||||
|
||||
impl egui::DroppedFile for Svg {
|
||||
fn path(&self) -> &Path {
|
||||
Path::new("drawing.svg")
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
Err("test file has no contents".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn check_handoff(at: Option<DragPosition>, expected_pos: Option<Pos2>, expected_shift: bool) {
|
||||
let ctx = egui::Context::default();
|
||||
let shared_files = Arc::new(AtomicUsize::new(0));
|
||||
ctx.on_begin_pass("observe dropped files before the app UI", {
|
||||
let shared_files = shared_files.clone();
|
||||
Arc::new(move |ui| {
|
||||
shared_files.fetch_add(ui.ctx().input(|input| input.raw.dropped_files.len()), Ordering::Relaxed);
|
||||
})
|
||||
});
|
||||
let mut drops = FileDrops::default();
|
||||
let position = Cell::new(at);
|
||||
let svg = Arc::new(Svg) as DroppedFileHandle;
|
||||
let mut raw = RawInput { dropped_files: vec![svg.clone()], ..Default::default() };
|
||||
|
||||
drops.capture(&mut raw);
|
||||
let mut delivered = Vec::new();
|
||||
ctx.run_ui(raw, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
let mut next = RawInput::default();
|
||||
drops.capture(&mut next);
|
||||
ctx.run_ui(next, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
|
||||
assert_eq!(shared_files.load(Ordering::Relaxed), 0, "the shared router must not see browser-owned drops");
|
||||
assert_eq!(delivered.len(), 1, "the browser UI must receive exactly one batch");
|
||||
let batch = &delivered[0];
|
||||
assert_eq!(batch.files.len(), 1, "the browser UI must receive exactly one file");
|
||||
assert!(Arc::ptr_eq(&batch.files[0], &svg));
|
||||
assert_eq!((batch.pos, batch.shift), (expected_pos, expected_shift));
|
||||
assert!(position.get().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positioned_browser_drop_reaches_the_web_ui_once() {
|
||||
check_handoff(Some((53.0, 27.0, true)), Some(egui::pos2(53.0, 27.0)), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_browser_drop_without_a_position_reaches_the_web_ui_once() {
|
||||
check_handoff(None, None, false);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod file_drops;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -22,6 +22,7 @@ use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use crate::file_drops::{DragPosition, DropBatch, FileDrops};
|
||||
use crate::locks::WebLocks;
|
||||
use crate::pencil::SharedPointers;
|
||||
|
||||
@@ -39,7 +40,7 @@ struct OpenInboxes {
|
||||
|
||||
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
|
||||
/// whether Shift was held: where dropped files land.
|
||||
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
|
||||
type DragPos = Rc<Cell<Option<DragPosition>>>;
|
||||
|
||||
/// A picture or file pasted into the page, read and waiting for the next frame with the modifiers
|
||||
/// held at the paste, and the context to wake for it (the current runner's).
|
||||
@@ -176,7 +177,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
}
|
||||
};
|
||||
app.adopt_context(ctx);
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss }))
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss, dropped: FileDrops::default() }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -376,6 +377,7 @@ struct WebShell {
|
||||
host: Host,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
loss: GraphicsLoss,
|
||||
dropped: FileDrops,
|
||||
}
|
||||
|
||||
impl WebShell {
|
||||
@@ -410,9 +412,9 @@ impl eframe::App for WebShell {
|
||||
embed::logic(ctx, || app.close_decision());
|
||||
}
|
||||
|
||||
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
|
||||
/// shared input hook before egui runs.
|
||||
/// Gather browser drops and forward host pointer events before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.dropped.capture(raw);
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input(ctx, raw);
|
||||
@@ -425,18 +427,13 @@ impl eframe::App for WebShell {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if let Some(app) = &mut self.app {
|
||||
// DOM paste and drop are host input: read them in the UI phase, once per pass, not in
|
||||
// `logic` where a hidden tab replays the last shown frame's input.
|
||||
// Deliver host input in a visible UI pass. Hidden tabs only run `logic`.
|
||||
let pasted = self.host.pasted.borrow_mut().flavour.take();
|
||||
if let Some((f, held)) = pasted {
|
||||
app.paste_from_host(&ctx, f, held);
|
||||
}
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
if !dropped.is_empty() {
|
||||
let at = self.host.drag.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
|
||||
for f in dropped {
|
||||
if let Some(DropBatch { files, pos, shift }) = self.dropped.take(&ctx, &self.host.drag) {
|
||||
for f in files {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, app.drop_spot(pos), shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
|
||||
@@ -129,5 +129,3 @@ winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Bound socket buffers in real loopback transport deadline regressions.
|
||||
socket2 = { workspace = true }
|
||||
@@ -571,6 +571,10 @@ fn main() -> std::process::ExitCode {
|
||||
mac_fonts::install();
|
||||
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
|
||||
prefs_dir::install_fonts();
|
||||
// Language packs: installs and index fetches run on their own threads, so the window keeps
|
||||
// working while a pack downloads.
|
||||
prefs_dir::use_language_packs();
|
||||
vectorcraft_engine::packs::run_in_background(true);
|
||||
// The log file lives in the settings directory, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
// first. Runs without preferences (agents' test runs) log to standard error only, so they
|
||||
|
||||
@@ -24,6 +24,14 @@ pub fn install_fonts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have spelling and hyphenation read the Language packs installed in the Craft apps' shared font
|
||||
/// store (`proof.installPack`, or another Craft app), and install new ones there (#4936). Like the
|
||||
/// Fonts folder, whether or not `VECTORCRAFT_NO_PREFS` is set: the packs are the store's, not
|
||||
/// VectorCraft's preferences.
|
||||
pub fn use_language_packs() {
|
||||
vectorcraft_engine::packs::use_font_store();
|
||||
}
|
||||
|
||||
/// The folder `name` next to the settings, for what the user keeps: none in a run without
|
||||
/// preferences (`VECTORCRAFT_NO_PREFS`), which keeps nothing.
|
||||
fn store_dir(name: &str) -> Option<PathBuf> {
|
||||
|
||||
+159
-1
@@ -6,7 +6,7 @@
|
||||
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
|
||||
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
|
||||
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
|
||||
//! color may leave out its `#`.
|
||||
//! color may leave out its `#`. [`format`] writes a color in these forms.
|
||||
//!
|
||||
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
|
||||
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
|
||||
@@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// The forms [`format`] writes a color in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Notation {
|
||||
/// `#rrggbb`.
|
||||
Hex,
|
||||
/// `#rrggbbaa`, `ff` for a color without an alpha.
|
||||
HexAlpha,
|
||||
/// `rgb(51 102 153)`.
|
||||
Rgb,
|
||||
/// `hsl(210 50% 40%)`.
|
||||
Hsl,
|
||||
/// `oklch(49.93% 0.0987 250.43)`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation`
|
||||
/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of
|
||||
/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form
|
||||
/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and
|
||||
/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and
|
||||
/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a
|
||||
/// gray is 0. [`Notation::Hex`] leaves the alpha out.
|
||||
pub fn format(rgb: [f32; 3], alpha: Option<f32>, notation: Notation) -> String {
|
||||
// A NaN alpha reads as none.
|
||||
let alpha = alpha.filter(|a| !a.is_nan());
|
||||
let bytes = rgb.map(byte);
|
||||
let units = bytes.map(|v| f64::from(v) / 255.0);
|
||||
let [r, g, b] = bytes;
|
||||
match notation {
|
||||
Notation::Hex => hex_of(rgb),
|
||||
Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))),
|
||||
Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)),
|
||||
Notation::Hsl => {
|
||||
let [h, s, l] = rgb_to_hsl(units);
|
||||
format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha))
|
||||
}
|
||||
Notation::Oklch => {
|
||||
let lch = oklab::to_oklch(units.map(|v| v as f32));
|
||||
// The fewest places that read back to the same bytes, from two (four for chroma).
|
||||
let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes);
|
||||
let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch)));
|
||||
let places = |base: i32| usize::try_from(base + p).unwrap_or(2);
|
||||
let c = number(c, places(4));
|
||||
// A chroma that rounds to 0 is a gray, whose hue is 0.
|
||||
let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) };
|
||||
format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the
|
||||
/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under
|
||||
/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of
|
||||
/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at
|
||||
/// the rounded lightness and hue; the chroma is lowered a step at a time instead.
|
||||
fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> {
|
||||
let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra));
|
||||
let step = 10f64.powi(-(4 + extra));
|
||||
let mut c = rounded(c, 4 + extra);
|
||||
for _ in 0..OKLCH_CHROMA_STEPS {
|
||||
if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) {
|
||||
return Some([l, c.max(0.0), h]);
|
||||
}
|
||||
c = rounded(c - step, 4 + extra);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB.
|
||||
const OKLCH_CHROMA_STEPS: usize = 50;
|
||||
|
||||
/// `v` rounded to `places` decimal places.
|
||||
fn rounded(v: f64, places: i32) -> f64 {
|
||||
let f = 10f64.powi(places);
|
||||
(v * f).round() / f
|
||||
}
|
||||
|
||||
/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing.
|
||||
fn alpha_part(alpha: Option<f32>) -> String {
|
||||
let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2);
|
||||
if percent == "100" { String::new() } else { format!(" / {percent}%") }
|
||||
}
|
||||
|
||||
/// A hue in degrees to two places, 360 written as 0.
|
||||
fn hue_text(h: f64) -> String {
|
||||
hue_text_to(h, 2)
|
||||
}
|
||||
|
||||
/// A hue in degrees to `places` places, 360 written as 0.
|
||||
fn hue_text_to(h: f64, places: usize) -> String {
|
||||
let text = number(h, places);
|
||||
if text == "360" { "0".to_string() } else { text }
|
||||
}
|
||||
|
||||
/// `v` to `places` decimal places, without trailing zeros or a sign on zero.
|
||||
fn number(v: f64, places: usize) -> String {
|
||||
let text = format!("{v:.places$}");
|
||||
let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() };
|
||||
if text == "-0" { "0".to_string() } else { text.to_string() }
|
||||
}
|
||||
|
||||
/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's
|
||||
/// rgbToHsl (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>); the hue of a gray is 0.
|
||||
fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] {
|
||||
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
|
||||
let (d, l) = (max - min, (max + min) / 2.0);
|
||||
if d == 0.0 {
|
||||
return [0.0, 0.0, l];
|
||||
}
|
||||
let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) };
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
[h * 60.0, s, l]
|
||||
}
|
||||
|
||||
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
|
||||
fn hex(text: &str) -> Option<CssColor> {
|
||||
let digits = text.strip_prefix('#').unwrap_or(text);
|
||||
@@ -412,6 +532,26 @@ mod tests {
|
||||
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_writes_each_notation_with_the_alpha_where_it_belongs() {
|
||||
let rgb = [0.2, 0.4, 0.6];
|
||||
let half = Some(0.5);
|
||||
assert_eq!(format(rgb, half, Notation::Hex), "#336699");
|
||||
assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980");
|
||||
assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)");
|
||||
assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)");
|
||||
assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out");
|
||||
assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)");
|
||||
assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)");
|
||||
assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)");
|
||||
assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)");
|
||||
assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)");
|
||||
assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)");
|
||||
assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn random_text_never_panics(text in "\\PC{0,60}") {
|
||||
@@ -439,5 +579,23 @@ mod tests {
|
||||
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
|
||||
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) {
|
||||
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
|
||||
let alpha = f32::from(a) / 255.0;
|
||||
for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] {
|
||||
let text = format(rgb, Some(alpha), notation);
|
||||
let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text);
|
||||
let read = c.alpha.unwrap_or(1.0);
|
||||
match notation {
|
||||
Notation::Hex => prop_assert_eq!(c.alpha, None),
|
||||
Notation::HexAlpha => prop_assert_eq!(byte(read), a),
|
||||
// A percentage to two places, left out when it rounds to 100.
|
||||
_ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
|
||||
/// passes.
|
||||
const LIGHTNESS_SAMPLES: usize = 16;
|
||||
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
|
||||
const LIGHTNESS_STEPS: usize = 32;
|
||||
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
|
||||
/// which leave it within 1e-7 of the step.
|
||||
const PEAK_STEPS: usize = 32;
|
||||
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
|
||||
/// single peak between them. `f` is called 34 times.
|
||||
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
|
||||
let g = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
|
||||
let (mut fa, mut fb) = (f(a), f(b));
|
||||
for _ in 0..PEAK_STEPS {
|
||||
if fa < fb {
|
||||
(lo, a, fa) = (a, b, fb);
|
||||
b = lo + g * (hi - lo);
|
||||
fb = f(b);
|
||||
} else {
|
||||
(hi, b, fb) = (b, a, fa);
|
||||
a = hi - g * (hi - lo);
|
||||
fa = f(a);
|
||||
}
|
||||
}
|
||||
if fa > fb { a } else { b }
|
||||
}
|
||||
|
||||
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
|
||||
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
|
||||
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
|
||||
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
|
||||
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
|
||||
/// so a color that passes only in a narrow band between white and black (as under a Difference
|
||||
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
|
||||
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
|
||||
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
|
||||
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
|
||||
/// steps before the first passing one is missed, and a farther color can be returned.
|
||||
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
|
||||
let passes = |c: [f32; 3]| ratio(c) >= minimum;
|
||||
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
if passes(srgb) {
|
||||
return Some(srgb);
|
||||
}
|
||||
let [l, c, h] = crate::oklab::to_oklch(srgb);
|
||||
let mut best: Option<(f64, [f32; 3])> = None;
|
||||
for end in [1.0, 0.0] {
|
||||
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
|
||||
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
|
||||
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
|
||||
// `lo` fails and `hi` passes, the step before the first sample that passes.
|
||||
let found = match ratios.iter().position(|r| *r >= minimum) {
|
||||
Some(i) => Some((step(i), step(i + 1))),
|
||||
None => {
|
||||
// Every sample fails: look for a higher ratio around the highest one.
|
||||
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
|
||||
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
|
||||
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
|
||||
passes(at(peak)).then_some((lo, peak))
|
||||
}
|
||||
};
|
||||
let Some((mut lo, mut hi)) = found else { continue };
|
||||
for _ in 0..LIGHTNESS_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if passes(at(mid)) { hi = mid } else { lo = mid }
|
||||
}
|
||||
let step = (end - l).abs() * hi;
|
||||
if best.is_none_or(|(d, _)| step < d) {
|
||||
best = Some((step, at(hi)));
|
||||
}
|
||||
}
|
||||
best.map(|(_, c)| c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -137,6 +214,80 @@ mod tests {
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
|
||||
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
|
||||
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
|
||||
let r = contrast_ratio(fix, bg);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
|
||||
// A color lighter than the background gets lighter.
|
||||
assert!(relative_luminance(fix) > relative_luminance(fg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
|
||||
let white = [1.0; 3];
|
||||
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
|
||||
let r = contrast_ratio(fix, white);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_that_passes_only_between_white_and_black_is_found() {
|
||||
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
|
||||
// mid gray draws black, 5.3:1.
|
||||
let gray = [0.5; 3];
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
|
||||
let r = contrast_ratio(difference(fix), gray);
|
||||
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
|
||||
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_band_between_the_samples_is_found() {
|
||||
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
|
||||
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
|
||||
let gray = hex("5a5a5a");
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
|
||||
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
|
||||
let r = ratio(fix);
|
||||
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
|
||||
/// blue that needs a little more contrast keeps nearly all of its chroma.
|
||||
#[test]
|
||||
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
|
||||
let gray = hex("b8b8b8");
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
|
||||
let blue = [0.0, 0.0, 1.0];
|
||||
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
|
||||
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
|
||||
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
|
||||
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
|
||||
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
|
||||
let white = [1.0; 3];
|
||||
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
|
||||
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
|
||||
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
|
||||
let mid = hex("777777");
|
||||
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
|
||||
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
|
||||
+79
-8
@@ -446,6 +446,66 @@ impl Drop for InMask {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// While an [`InteriorProbe`] lives, whether a leaf tested without
|
||||
/// [`HitOptions::unfilled_interiors`] would have been hit inside an unfilled closed path with
|
||||
/// it; `None` outside a probe.
|
||||
static INTERIOR_SEEN: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// While a guard lives, the leaves tested without [`HitOptions::unfilled_interiors`] note whether
|
||||
/// they would be hit inside an unfilled closed path with it ([`unfilled_inside`]). A walk that hits
|
||||
/// nothing then looks inside the unfilled closed paths with a second walk only when one of them
|
||||
/// holds the point.
|
||||
struct InteriorProbe {
|
||||
was: Option<bool>,
|
||||
}
|
||||
|
||||
impl InteriorProbe {
|
||||
/// A probe when `wanted`, the walk that follows a miss looking inside unfilled closed paths.
|
||||
/// Otherwise the guard leaves things as they are, and no leaf measures an interior for it.
|
||||
fn open(wanted: bool) -> Self {
|
||||
Self { was: if wanted { INTERIOR_SEEN.replace(Some(false)) } else { INTERIOR_SEEN.get() } }
|
||||
}
|
||||
|
||||
/// Did a leaf tested since [`Self::open`] have an unfilled closed path holding the point?
|
||||
fn seen(&self) -> bool {
|
||||
INTERIOR_SEEN.get() == Some(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InteriorProbe {
|
||||
fn drop(&mut self) {
|
||||
// A probe opened inside another passes what it saw on to it.
|
||||
let seen = INTERIOR_SEEN.get() == Some(true);
|
||||
INTERIOR_SEEN.set(self.was.map(|was| was || seen));
|
||||
}
|
||||
}
|
||||
|
||||
/// The hit inside path or compound path `n`'s closed subpaths, which have no visible fill, when
|
||||
/// `n` takes one there ([`takes_interior`]) and `contains` says they hold the point. Without
|
||||
/// [`HitOptions::unfilled_interiors`], under an [`InteriorProbe`], notes whether `n` would take
|
||||
/// one with it, and hits nothing.
|
||||
fn unfilled_inside(n: &Node, opt: HitOptions, contains: impl FnOnce() -> bool) -> Option<HitKind> {
|
||||
if takes_interior(n, opt) {
|
||||
return contains().then_some(HitKind::Fill);
|
||||
}
|
||||
if INTERIOR_SEEN.get() == Some(false) && takes_interior(n, HitOptions { unfilled_interiors: true, ..opt }) {
|
||||
#[cfg(test)]
|
||||
INTERIORS_PROBED.with(|c| c.set(c.get() + 1));
|
||||
if contains() {
|
||||
INTERIOR_SEEN.set(Some(true));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many interiors [`unfilled_inside`] measured for an [`InteriorProbe`] on this thread.
|
||||
static INTERIORS_PROBED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
@@ -667,10 +727,15 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]), when the first pass passes one
|
||||
// holding `p` ([`InteriorProbe`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
let mut probe = Some(InteriorProbe::open(interiors));
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
if pass.unfilled_interiors && !probe.take().is_some_and(|probe| probe.seen()) {
|
||||
break;
|
||||
}
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
@@ -1017,12 +1082,15 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
/// only when the first, without it, hits nothing and passes an unfilled closed path holding `p`
|
||||
/// ([`InteriorProbe`]).
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !opt.outline);
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline || !probe.seen() {
|
||||
return painted;
|
||||
}
|
||||
drop(probe);
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
@@ -1672,8 +1740,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed);
|
||||
let inside = || interior.then(|| unfilled_inside(n, opt, || fill_contains(&closed_subpaths_at([path], p), *rule, p))).flatten();
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1740,7 +1808,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
unfilled_inside(n, opt, || fill_contains(&closed(), *rule, p))
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -2121,11 +2189,14 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit, and only
|
||||
// when the first walk passes one holding `p` ([`InteriorProbe`]).
|
||||
let probe = InteriorProbe::open(opt.unfilled_interiors && !opt.path_only && !outline);
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline || !probe.seen() {
|
||||
return None;
|
||||
}
|
||||
drop(probe);
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
|
||||
@@ -200,6 +200,88 @@ fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
/// An open path with a black stroke and no fill, from (`o`, 0) to (100, `o`) to (100, 100): its box
|
||||
/// holds (50, 50), and it is drawn nowhere near that point.
|
||||
fn open_corner(d: &mut Document, o: f64) -> Node {
|
||||
let pts = [Point::new(o, 0.0), Point::new(100.0, o), Point::new(100.0, 100.0)];
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false));
|
||||
Node::path(d.alloc_id(), path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
|
||||
}
|
||||
|
||||
/// How many leaves [`hit_leaf`] tested while `f` ran, with its result.
|
||||
fn leaves_tested<R>(f: impl FnOnce() -> R) -> (R, usize) {
|
||||
LEAVES_TESTED.with(|c| c.set(0));
|
||||
let r = f();
|
||||
(r, LEAVES_TESTED.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// A selection click that hits nothing, where no unfilled closed path holds the point, walks the
|
||||
/// document once: looking inside unfilled closed paths tests no more leaves than a click without
|
||||
/// it. An unfilled closed path that holds the point is still hit inside.
|
||||
#[test]
|
||||
fn a_selection_click_that_hits_nothing_walks_the_document_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..10 {
|
||||
let corner = open_corner(&mut d, f64::from(i));
|
||||
d.insert(Some(l), 99, corner).unwrap();
|
||||
}
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let (hit, without) = leaves_tested(|| hit_test(&d, p, SELECTING));
|
||||
assert_eq!(hit, None);
|
||||
assert_eq!(without, 10);
|
||||
let (hit, with) = leaves_tested(|| hit_test(&d, p, INTERIORS));
|
||||
assert_eq!(hit, None);
|
||||
assert_eq!(with, without, "hit_test");
|
||||
let (tops, with) = leaves_tested(|| objects_at(&d, p, INTERIORS, None));
|
||||
assert!(tops.is_empty());
|
||||
assert_eq!(with, without, "objects_at");
|
||||
// An unfilled frame below them that holds the point: the second walk finds it.
|
||||
let frame = d.alloc_id();
|
||||
let look = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
d.insert(Some(l), 0, Node::path(frame, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap();
|
||||
assert_eq!(hit_test(&d, p, INTERIORS).map(|h| h.leaf), Some(frame));
|
||||
assert_eq!(objects_at(&d, p, INTERIORS, None), vec![frame]);
|
||||
}
|
||||
|
||||
/// A hit test that does not look inside unfilled closed paths measures none of their interiors.
|
||||
#[test]
|
||||
fn a_hit_test_without_unfilled_interiors_measures_no_interior() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, true);
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let probed = |f: &dyn Fn()| {
|
||||
INTERIORS_PROBED.with(|c| c.set(0));
|
||||
f();
|
||||
INTERIORS_PROBED.with(std::cell::Cell::get)
|
||||
};
|
||||
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, SELECTING), None)), 0, "hit_test");
|
||||
assert_eq!(probed(&|| assert!(objects_at(&d, p, SELECTING, None).is_empty())), 0, "objects_at");
|
||||
assert_eq!(probed(&|| assert_eq!(hit_test(&d, p, HitOptions { path_only: true, ..INTERIORS }), None)), 0, "by path only");
|
||||
assert_eq!(probed(&|| assert!(hit_test(&d, p, INTERIORS).is_some())), 1, "looking inside");
|
||||
}
|
||||
|
||||
/// Direct Selection on a dynamic symbol's instance that picks no part of its art, where no
|
||||
/// unfilled closed path of the art holds the point, walks the art once.
|
||||
#[test]
|
||||
fn a_symbol_part_pick_that_hits_nothing_walks_the_art_once() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let corners: Vec<Arc<Node>> = (0..10).map(|i| Arc::new(open_corner(&mut d, f64::from(i)))).collect();
|
||||
let root = Node::group(d.alloc_id(), corners);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Corners".into(), art: Arc::new(root) });
|
||||
let l = d.layers[0].id;
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Corners".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let p = Point::new(50.0, 50.0);
|
||||
let (part, without) = leaves_tested(|| symbol_part_at(&d, n, p, SELECTING));
|
||||
assert_eq!(part, None);
|
||||
assert!(without >= 10, "{without} leaves tested");
|
||||
let (part, with) = leaves_tested(|| symbol_part_at(&d, n, p, INTERIORS));
|
||||
assert_eq!(part, None);
|
||||
assert_eq!(with, without);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -3569,3 +3651,26 @@ fn a_shaper_groups_original_shapes_in_symbol_art_are_not_picked() {
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(130.0, 50.0), opt), None, "over the erased original shape");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), Some(vec![0, 1]), "over the shown face");
|
||||
}
|
||||
|
||||
/// The pointer resting over empty canvas past many paths reads their anchors for their culling
|
||||
/// boxes on the first hover only: the next hovers use the boxes the paths keep.
|
||||
#[test]
|
||||
fn hovers_past_many_paths_read_their_anchors_once() {
|
||||
use vectorcraft_geom::anchors::measured_control_anchors;
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..100 {
|
||||
let n = square(&mut d, (i % 10) as f64 * 60.0, (i / 10) as f64 * 60.0);
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
}
|
||||
let empty = Point::new(900.0, 900.0);
|
||||
let before = measured_control_anchors();
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = measured_control_anchors() - before;
|
||||
assert!(first >= 400, "the first hover reads every square's anchors: {first}");
|
||||
for _ in 0..3 {
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
}
|
||||
assert_eq!(measured_control_anchors() - before, first, "later hovers read no anchor");
|
||||
assert!(hit_at(&d, 25.0, 25.0, HitOptions::default()).is_some(), "a square is still hit");
|
||||
}
|
||||
@@ -89,6 +89,10 @@ windows-native-keyring-store = "1.1"
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
# Language packs (packs.rs): the shared font store installs them and finds its folder. Already in
|
||||
# Cargo.lock (craft-font-manager), so this adds no new crate.
|
||||
craft-font-store = { workspace = true }
|
||||
craft-font-catalog = { workspace = true }
|
||||
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
|
||||
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
|
||||
# Linux. All MIT OR Apache-2.0.
|
||||
|
||||
@@ -65,6 +65,8 @@ pub(crate) mod objects_on_path;
|
||||
mod opacitymask;
|
||||
mod overprint;
|
||||
pub mod package;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod packs;
|
||||
mod paint;
|
||||
mod panelcmds;
|
||||
pub mod params;
|
||||
@@ -384,6 +386,9 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(tags::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
// Language packs need a font store, which the web build has none of.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
v.extend(packs::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
@@ -853,6 +858,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Arrange Tools (`addon.arrange.*`), a built-in add-on: Arrange in Grid lays the selected objects
|
||||
//! out in rows and columns, a row or a column; Swap Objects swaps the places (and sizes) of two;
|
||||
//! out in rows and columns, a row or a column; Offset Objects chains them one after another in a
|
||||
//! row or a column with a set gap, the first staying in place; Swap Objects swaps the places (and sizes) of two;
|
||||
//! Replace with Top Object puts a copy of the topmost selected object in place of each of the
|
||||
//! others; and Set Size of Each gives every selected object an exact width and height. Places and
|
||||
//! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the
|
||||
//! sizes are measured and set as `object.setBounds` does. Match Objects gives the other selected
|
||||
//! objects the size, bounding-box angle and stacking place of one of them. Group Overlapping Objects groups the
|
||||
//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random
|
||||
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
|
||||
//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection
|
||||
@@ -17,7 +19,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::Rng;
|
||||
use vectorcraft_doc::{Node, NodeId, OrientedBox};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::appearance::series_children_in_paint_order;
|
||||
@@ -52,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
grid
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.offset",
|
||||
"Offset Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{direction?: \"row\" (left to right) | \"column\" (top to bottom) (\"row\"), gap?: pt −1000000..1000000 (10; negative: the objects overlap), order?: \"stacking\" (stacking order, from the back) | \"position\" (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (\"stacking\"), reverse?: false (true: the order runs the other way)} chain the selected objects (the top-level ones) one after another in that order, as one undo step: the first stays where it is, and each later one moves only along the direction, so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. Everything is measured by visual bounds (strokes and effects as drawn; a clipping group by its mask). A run that moves nothing makes no step → {count}",
|
||||
has_multi,
|
||||
offset
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.swap",
|
||||
"Swap Objects",
|
||||
@@ -79,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.match",
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
cmd!(
|
||||
"addon.arrange.groupOverlapping",
|
||||
"Group Overlapping Objects",
|
||||
@@ -167,6 +187,14 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, cmd)?;
|
||||
s.note_journal("scaleStrokes", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -228,10 +256,46 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": n }))
|
||||
}
|
||||
|
||||
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.offset";
|
||||
let row = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row";
|
||||
let gap = number_in(p, "gap", 10.0, (-LIMIT, LIMIT), C)?;
|
||||
let by_position = choice(p, C, "order", &["stacking", "position"])?.unwrap_or("stacking") == "position";
|
||||
let reverse = switch_or(p, "reverse", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The objects in stacking order from the back, each with its leading and trailing edge along the direction.
|
||||
let mut items: Vec<(NodeId, f64, f64)> = roots
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let b = effects::preview::bounds_of(d, &[*id], true)?;
|
||||
Some(if row { (*id, b.x0, b.x1) } else { (*id, b.y0, b.y1) })
|
||||
})
|
||||
.collect();
|
||||
if by_position {
|
||||
items.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
}
|
||||
if reverse {
|
||||
items.reverse();
|
||||
}
|
||||
// The first stays; each later one starts `gap` past where the one before it now ends.
|
||||
let mut end: Option<f64> = None;
|
||||
let xfs: Vec<(NodeId, Affine)> = items
|
||||
.iter()
|
||||
.map(|&(id, start, finish)| {
|
||||
let shift = end.map_or(0.0, |e| e + gap - start);
|
||||
end = Some(finish + shift);
|
||||
(id, Affine::translate(if row { Vec2::new(shift, 0.0) } else { Vec2::new(0.0, shift) }))
|
||||
})
|
||||
.collect();
|
||||
transform_each(s, "Offset Objects", false, &xfs)?;
|
||||
Ok(json!({ "count": items.len() }))
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
@@ -244,7 +308,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -295,7 +359,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
@@ -313,6 +377,158 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
/// The source Match Objects matches `roots` (the selected roots, in stacking order) to, from its
|
||||
/// `source` param: the selected root that is the key object or holds it, the frontmost or the backmost.
|
||||
fn match_source(s: &Session, p: &Value, roots: &[NodeId], cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let key = st.selection.key.and_then(|k| st.doc.ancestry(k)).and_then(|up| roots.iter().copied().find(|id| up.contains(id)));
|
||||
let picked = match choice(p, cmd, "source", &["key", "top", "bottom"])? {
|
||||
Some("key") => Some(key.ok_or_else(|| bad(cmd, "no key object: set one with select.key"))?),
|
||||
Some("bottom") => roots.first().copied(),
|
||||
Some(_) => roots.last().copied(),
|
||||
None => key.or_else(|| roots.last().copied()),
|
||||
};
|
||||
picked.ok_or_else(|| bad(cmd, "select at least two objects"))
|
||||
}
|
||||
|
||||
/// Whether `targets` (in stacking order) are directly above `source` in its layer or group, in that order.
|
||||
fn stacked_above(d: &vectorcraft_doc::Document, source: NodeId, targets: &[NodeId]) -> bool {
|
||||
let paths = d.index_paths(targets.iter().copied().chain([source]));
|
||||
let Some((&at, up)) = paths.get(&source).and_then(|p| p.split_last()) else { return false };
|
||||
targets.iter().enumerate().all(|(i, id)| paths.get(id).and_then(|p| p.split_last()) == Some((&(at + 1 + i), up)))
|
||||
}
|
||||
|
||||
fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.match";
|
||||
let size = choice(p, C, "size", &["none", "width", "height", "both"])?.unwrap_or("none");
|
||||
let rotate = switch_or(p, "rotate", false, C)?;
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
}
|
||||
let source = match_source(s, p, &roots, C)?;
|
||||
let targets: Vec<NodeId> = roots.iter().copied().filter(|id| *id != source).collect();
|
||||
if targets.is_empty() {
|
||||
return Err(bad(C, "select at least two objects"));
|
||||
}
|
||||
// Only sizing measures the source; a stacking or rotate match doesn't need its bounds.
|
||||
let (w, h) = if size == "none" {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let sb = box_of(s, source)?;
|
||||
(sb.rect.width(), sb.rect.height())
|
||||
};
|
||||
let wanted = match size {
|
||||
"width" if w < LEAST => return Err(bad(C, "the source object has no width")),
|
||||
"height" if h < LEAST => return Err(bad(C, "the source object has no height")),
|
||||
"both" if w < LEAST || h < LEAST => return Err(bad(C, "the source object has no width or no height")),
|
||||
"width" => Some(json!({ "width": w, "proportional": true })),
|
||||
"height" => Some(json!({ "height": h, "proportional": true })),
|
||||
"both" => Some(json!({ "width": w, "height": h })),
|
||||
_ => None,
|
||||
};
|
||||
let angle = s.doc()?.doc.bbox_angle(&[source]);
|
||||
let mut xfs = Vec::with_capacity(targets.len());
|
||||
for &id in &targets {
|
||||
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
|
||||
let Some(b) = s.transform_box(&[id]) else {
|
||||
if wanted.is_some() {
|
||||
return Err(bad(C, format!("object {} has no bounds to size", id.0)));
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
return Err(bad(C, format!("object {} has no bounds to rotate", id.0)));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let mut xf = Affine::IDENTITY;
|
||||
if let Some(q) = &wanted {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
}
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
xfs.retain(|(_, xf)| !still(xf));
|
||||
let restack = stacking && !stacked_above(&s.doc()?.doc, source, &targets);
|
||||
let (mut placed, mut left) = (vec![], vec![]);
|
||||
if restack {
|
||||
let d = &s.doc()?.doc;
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: it stays there.
|
||||
let is_clip =
|
||||
|id: &NodeId| d.position(*id).is_some_and(|(_, idx, _)| idx == 0) && d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(Node::clips);
|
||||
if targets.iter().any(is_clip) {
|
||||
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
|
||||
}
|
||||
let parent = d.parent_of(source);
|
||||
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
placed = targets.iter().map(|i| (*i, d.parent_of(*i))).collect::<Vec<(NodeId, Option<NodeId>)>>();
|
||||
left = crate::cmd::intertwine::groups_of(d, &targets);
|
||||
}
|
||||
let count = json!({ "source": source.0, "count": targets.len() });
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
s.edit("Match Objects", |d, _| {
|
||||
for (id, xf) in &xfs {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
transform_node(n, *xf, sc, true);
|
||||
}
|
||||
}
|
||||
if restack {
|
||||
let moved = d.remove_many(&targets)?;
|
||||
d.insert_beside(vec![(source, moved.into_iter().map(Arc::unwrap_or_clone).collect())], false)?;
|
||||
// Targets moved out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -459,7 +675,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let order = choice(p, C, "order", &["ascending", "descending", "random"])?.unwrap_or("ascending");
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = switch_or(p, "scaleStrokes", s.prefs.scale_strokes, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
|
||||
@@ -106,6 +106,134 @@ fn grid_measures_visual_bounds() {
|
||||
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_chains_a_row_in_stacking_order_from_the_first_in_place() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 100.0, 50.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 0.0, 200.0, 40.0, 30.0);
|
||||
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[c, a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.offset", &json!({"gap": 5})).unwrap();
|
||||
assert_eq!(r["count"], json!(3));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// From the back: a stays, b starts 5 past a's right edge, c 5 past b's; each keeps its y.
|
||||
assert!(near(bounds(&s, a), (100.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (125.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (170.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, b), (0.0, 200.0, 40.0, 30.0)));
|
||||
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)));
|
||||
// Reversed: c stays, then b, then a. The gap defaults to 10.
|
||||
s.execute("addon.arrange.offset", &json!({"reverse": true})).unwrap();
|
||||
assert!(near(bounds(&s, c), (300.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (320.0, 200.0, 40.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, a), (370.0, 50.0, 20.0, 10.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_chains_a_column_by_position_either_way_and_overlaps_with_a_negative_gap() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 100.0, 10.0, 20.0);
|
||||
let b = rect(&mut s, 50.0, 0.0, 10.0, 10.0);
|
||||
let c = rect(&mut s, 100.0, 40.0, 10.0, 30.0);
|
||||
select(&mut s, &[a, b, c]);
|
||||
// Top to bottom: b, c, a; each 5 into the one before it, keeping its x.
|
||||
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "gap": -5})).unwrap();
|
||||
assert!(near(bounds(&s, b), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (100.0, 5.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, a), (0.0, 30.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Bottom to top: a stays, then c, then b.
|
||||
s.execute("addon.arrange.offset", &json!({"direction": "column", "order": "position", "reverse": true, "gap": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (100.0, 120.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (50.0, 150.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Left to right in a row: a, b, c.
|
||||
s.execute("addon.arrange.offset", &json!({"order": "position", "gap": 1})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 100.0, 10.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (11.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (22.0, 40.0, 10.0, 30.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_measures_visual_bounds_and_clipping_groups_by_their_mask() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
// Visual boxes 24 wide, touching.
|
||||
assert!(near(bounds(&s, b), (24.0, 0.0, 20.0, 20.0)), "{:?}", bounds(&s, b));
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
// A 200 wide object clipped to a 30 wide mask at x 100.
|
||||
let clipped = rect(&mut s, 50.0, 50.0, 200.0, 10.0);
|
||||
let mask = rect(&mut s, 100.0, 40.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0];
|
||||
let c = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, group, c]);
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
// The mask starts at a's right edge, and c at the mask's.
|
||||
assert!(near(bounds(&s, mask), (20.0, 40.0, 30.0, 30.0)), "{:?}", bounds(&s, mask));
|
||||
assert!(near(bounds(&s, clipped), (-30.0, 50.0, 200.0, 10.0)), "{:?}", bounds(&s, clipped));
|
||||
assert!(near(bounds(&s, c), (50.0, 0.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_makes_no_step_when_nothing_moves_and_skips_locked_objects() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 30.0, 50.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.offset"), "off with one object");
|
||||
select(&mut s, &[a, b]);
|
||||
assert!(enabled(&s, "addon.arrange.offset"));
|
||||
// Already 10 apart in a row.
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.offset", &json!({})).unwrap();
|
||||
assert_eq!(steps(&s), n, "no step when nothing moves");
|
||||
// Two objects in one group are one object: nothing to chain.
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert!(!enabled(&s, "addon.arrange.offset"), "off with one group");
|
||||
refuses(&mut s, "addon.arrange.offset", &[json!({"gap": 50})]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let c = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.offset", &json!({"gap": 0})).unwrap();
|
||||
assert!(near(bounds(&s, b), (30.0, 50.0, 20.0, 20.0)), "the locked object stays, {:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (20.0, 200.0, 10.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.offset",
|
||||
&[
|
||||
json!({"direction": "diagonal"}),
|
||||
json!({"direction": 1}),
|
||||
json!({"gap": 1e7}),
|
||||
json!({"gap": -1e7}),
|
||||
json!({"gap": "10"}),
|
||||
json!({"order": "size"}),
|
||||
json!({"reverse": "yes"}),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_trades_places_and_optionally_sizes() {
|
||||
let mut s = session();
|
||||
@@ -215,6 +343,394 @@ fn size_gives_each_object_a_width_and_height() {
|
||||
assert!(near(bounds(&s, a), (30.0, 8.0, 10.0, 12.0)), "both given: both set, {:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Three rectangles from the back, all selected: `a` 20 × 10 at the origin, `b` 40 × 40 at
|
||||
/// (100, 100) and `c` 10 × 30 at (200, 0).
|
||||
fn three(s: &mut Session) -> (NodeId, NodeId, NodeId) {
|
||||
let a = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(s, 100.0, 100.0, 40.0, 40.0);
|
||||
let c = rect(s, 200.0, 0.0, 10.0, 30.0);
|
||||
select(s, &[a, b, c]);
|
||||
(a, b, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_gives_the_others_the_key_objects_size() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r, json!({"source": b.0, "count": 2}));
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
// About each center; the key object stays.
|
||||
assert!(near(bounds(&s, a), (-10.0, -15.0, 40.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (185.0, -5.0, 40.0, 40.0)), "{:?}", bounds(&s, c));
|
||||
assert!(near(bounds(&s, b), (100.0, 100.0, 40.0, 40.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 20.0, 10.0)));
|
||||
// The width, with the height in proportion, about the top-left corner.
|
||||
s.execute("addon.arrange.match", &json!({"size": "width", "reference": 0})).unwrap();
|
||||
assert!(near(bounds(&s, a), (0.0, 0.0, 40.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 40.0, 120.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "height", "reference": 8})).unwrap();
|
||||
assert!(near(bounds(&s, a), (-60.0, -30.0, 80.0, 40.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
// No key object: the frontmost, c.
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
assert!(near(bounds(&s, a), (5.0, -10.0, 10.0, 30.0)), "{:?}", bounds(&s, a));
|
||||
assert!(near(bounds(&s, b), (115.0, 105.0, 10.0, 30.0)), "{:?}", bounds(&s, b));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "bottom", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(a.0));
|
||||
assert!(near(bounds(&s, b), (110.0, 115.0, 20.0, 10.0)), "{:?}", bounds(&s, b));
|
||||
assert!(near(bounds(&s, c), (195.0, 10.0, 20.0, 10.0)), "{:?}", bounds(&s, c));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// "top" names the frontmost even while a key object is set.
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let r = s.execute("addon.arrange.match", &json!({"source": "top", "size": "both"})).unwrap();
|
||||
assert_eq!(r["source"], json!(c.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_to_the_sources_angle() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "size": "both"})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
for (id, center) in [(a, (10.0, 5.0)), (c, (205.0, 15.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
assert!((o.rect.width() - 40.0).abs() < 1e-6 && (o.rect.height() - 40.0).abs() < 1e-6, "{id:?} sized {:?}", o.rect);
|
||||
let at = o.center();
|
||||
assert!((at.x - center.0).abs() < 1e-6 && (at.y - center.1).abs() < 1e-6, "{id:?} turned about its center: {at:?}");
|
||||
}
|
||||
// Turned back to the angle of an unturned source.
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, d]);
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "source": "top"})).unwrap();
|
||||
assert!(s.transform_box(&[a]).unwrap().angle.abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
|
||||
for size in ["width", "height", "both"] {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 10.5, 10.5);
|
||||
select(&mut s, &[source]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": size, "rotate": true})).unwrap();
|
||||
assert_eq!(r, json!({"source": source.0, "count": 1}));
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
|
||||
for angle in [0, 30] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.rotate", &json!({"angle": angle})).unwrap();
|
||||
select(&mut s, &[b]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[target]).is_none());
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert!((s.doc().unwrap().doc.bbox_angle(&[source]) - f64::from(angle)).abs() < 1e-6);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let result = s.execute("addon.arrange.match", &json!({"rotate": true}));
|
||||
if angle == 0 {
|
||||
assert_eq!(result.unwrap(), json!({"source": source.0, "count": 1}));
|
||||
} else {
|
||||
let error = result.unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("object {} has no bounds to rotate", target.0)), "{error}");
|
||||
}
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_puts_the_others_directly_above_the_source() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
let d = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[d, a, c]);
|
||||
s.execute("select.key", &json!({"id": a.0})).unwrap();
|
||||
let n = steps(&s);
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
assert_eq!(layer_order(&s), [a, c, d, b], "in the order they had, above the key object");
|
||||
assert!(near(bounds(&s, c), (200.0, 0.0, 10.0, 30.0)), "nothing else changes");
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(steps(&s), n + 1, "already above it: no step");
|
||||
// An object in another layer goes into the source's.
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let e = rect(&mut s, 0.0, 200.0, 10.0, 10.0);
|
||||
select(&mut s, &[b, e]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b, e]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(layer_order(&s), [a, c, d, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_makes_no_step_when_everything_matches() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 10.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let n = steps(&s);
|
||||
let r = s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true})).unwrap();
|
||||
assert_eq!(r["count"], json!(1));
|
||||
assert_eq!(steps(&s), n, "the same size and angle: no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_turns_the_others_about_their_reference_point() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = three(&mut s);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
select(&mut s, &[a, b, c]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"rotate": true, "reference": 0})).unwrap();
|
||||
// Each top-left corner stays where it was.
|
||||
for (id, corner) in [(a, (0.0, 0.0)), (c, (200.0, 0.0))] {
|
||||
let o = s.transform_box(&[id]).unwrap();
|
||||
assert!((o.angle - 30.0).abs() < 1e-6, "{id:?} turned to {}", o.angle);
|
||||
let at = o.to_doc() * vectorcraft_geom::reference_point(o.rect, 0);
|
||||
assert!((at.x - corner.0).abs() < 1e-6 && (at.y - corner.1).abs() < 1e-6, "{id:?} turned about its top-left corner: {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_scales_strokes_as_asked() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
assert_eq!(weight(&s, a), 2.0, "off by default (the preference)");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": true})).unwrap();
|
||||
assert!((weight(&s, a) - 4.0).abs() < 1e-9, "{}", weight(&s, a));
|
||||
assert!(near(bounds(&s, a), (-5.0, -5.0, 20.0, 20.0)), "{:?}", bounds(&s, a));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Strokes & Effects on doubles the 2 pt stroke of a 10 pt square, and
|
||||
/// replaying its journal entry after the preference is turned off scales the stroke the same way.
|
||||
fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2})).unwrap();
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", weight(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleStrokes", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let mask = rect(&mut s, 10.0, 10.0, 10.0, 10.0);
|
||||
select(&mut s, &[art, mask]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let x = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[mask, x]);
|
||||
s.execute("select.key", &json!({"id": x.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"stacking": true})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "width"}), json!({"size": "both"})]);
|
||||
// Its height can still take the source's.
|
||||
s.execute("addon.arrange.match", &json!({"size": "height"})).unwrap();
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[line]);
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "cap": "butt"})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 0.0, 2.0, 100.0);
|
||||
select(&mut s, &[b]);
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[line]).unwrap().rect;
|
||||
let wanted = s.transform_box(&[b]).unwrap().rect;
|
||||
assert!((measured.width() - wanted.width()).abs() < 1e-6, "{measured:?}");
|
||||
assert!((measured.height() - wanted.height()).abs() < 1e-6, "{measured:?}");
|
||||
select(&mut s, &[b]);
|
||||
s.execute("object.setBounds", &json!({"width": 4})).unwrap();
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_takes_a_member_out_of_its_intertwine_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[a, b]);
|
||||
let g = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.intertwine.arrange", &json!({"at": [30, 30], "order": "front", "member": a.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(a).unwrap().extras().intertwine.is_some(), "a is drawn over b in their overlap");
|
||||
let c = rect(&mut s, 200.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a, c]);
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(a), Some(g), "a left the Intertwine group");
|
||||
let e = d.node(a).unwrap().extras();
|
||||
assert!(e.intertwine.is_none() && e.intertwine_tiers.is_empty(), "a keeps no Intertwine areas");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "undo puts a back in its group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_needs_no_bounds_on_the_source() {
|
||||
let mut s = session();
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
select(&mut s, &[b, g]);
|
||||
s.execute("select.key", &json!({"id": g.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
|
||||
assert_eq!(layer_order(&s), [g, b], "b goes directly above the empty group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
|
||||
let source = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[source, b]);
|
||||
let parent = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[a]);
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(s.transform_box(&[source]).is_none());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(source), Some(parent));
|
||||
let c = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
|
||||
let d = rect(&mut s, 120.0, 20.0, 40.0, 40.0);
|
||||
select(&mut s, &[c, d]);
|
||||
let target = NodeId(s.execute("object.intertwine.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
select(&mut s, &[source, target]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let n = steps(&s);
|
||||
let error = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err().to_string();
|
||||
assert!(error.contains("can't be intertwined"), "{error}");
|
||||
assert_eq!(steps(&s), n);
|
||||
assert!(*s.doc().unwrap().doc == *before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
let (a, _, _) = three(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.arrange.match",
|
||||
&[
|
||||
json!({}),
|
||||
json!({"size": "none"}),
|
||||
json!({"size": "area"}),
|
||||
json!({"size": 1}),
|
||||
json!({"rotate": 1}),
|
||||
json!({"stacking": "yes"}),
|
||||
json!({"size": "both", "reference": 9}),
|
||||
json!({"size": "both", "reference": 1.5}),
|
||||
json!({"size": "both", "source": "left"}),
|
||||
json!({"size": "both", "scaleStrokes": "no"}),
|
||||
json!({"size": "both", "patterns": 0}),
|
||||
],
|
||||
);
|
||||
let e = s.execute("addon.arrange.match", &json!({"source": "key", "rotate": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no key object"), "{e}");
|
||||
select(&mut s, &[a]);
|
||||
assert!(!enabled(&s, "addon.arrange.match"), "one object selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -261,6 +777,7 @@ fn off_without_a_selection() {
|
||||
"addon.arrange.swap",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.sort",
|
||||
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Options…",
|
||||
[],
|
||||
None,
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); values the symbol already has, newName included, change nothing and add no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_doc,
|
||||
symbol_options
|
||||
),
|
||||
@@ -289,7 +289,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Symbol",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them) → {ids}",
|
||||
"{name, ids?|id?} swap the symbol of the selected instances (an instance given a different symbol drops its appearance changes; one given its own symbol keeps them; when every instance already shows the symbol, nothing changes and no undo step is recorded) → {ids}",
|
||||
has_selection,
|
||||
symbol_replace
|
||||
),
|
||||
|
||||
@@ -347,13 +347,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let dynamic = type_param(p, C)?;
|
||||
let pixel = pixel_grid_param(p, C)?;
|
||||
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
|
||||
match pixel {
|
||||
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
|
||||
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
|
||||
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
|
||||
Some(_) => {}
|
||||
}
|
||||
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() && pixel.is_none() {
|
||||
return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid"));
|
||||
}
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
@@ -362,7 +357,8 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("a symbol named `{n}` already exists")));
|
||||
}
|
||||
let final_name = new_name.clone().unwrap_or_else(|| name.clone());
|
||||
s.edit("Symbol Options", |d, _| {
|
||||
// Values the symbol already has leave the document as it is, and no undo step is added.
|
||||
crate::cmd::colorcmds::edit_if_changed(s, "Symbol Options", |before, d| {
|
||||
if let Some(ref n) = new_name
|
||||
&& n != &name
|
||||
{
|
||||
@@ -439,7 +435,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(on) = pixel {
|
||||
d.set_symbol_pixel_aligned(&final_name, on);
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), before != &*d))
|
||||
})?;
|
||||
Ok(options_json(&s.doc()?.doc, &final_name))
|
||||
}
|
||||
@@ -859,7 +855,8 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
s.edit("Replace Symbol", |d, _| {
|
||||
// Instances that already show the symbol leave the document as it is, and no undo step is added.
|
||||
crate::cmd::colorcmds::edit_if_changed(s, "Replace Symbol", |before, d| {
|
||||
let new = natural_size(d, &name);
|
||||
for id in &ids {
|
||||
let (old, other) = match d.node(*id).map(|n| &n.kind) {
|
||||
@@ -877,7 +874,7 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
fit_overrides(d, &ids);
|
||||
Ok(())
|
||||
Ok(((), ids.iter().any(|id| before.node(*id) != d.node(*id))))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
@@ -146,18 +146,52 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
parse_color
|
||||
),
|
||||
cmd!(
|
||||
query "color.format",
|
||||
"Format Color",
|
||||
[],
|
||||
None,
|
||||
"{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB",
|
||||
always,
|
||||
format_color
|
||||
),
|
||||
cmd!(
|
||||
query "color.contrast",
|
||||
"Contrast",
|
||||
[],
|
||||
None,
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn format_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.format";
|
||||
let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
|
||||
let opacity = super::paint::opacity_param(p, C)?;
|
||||
let notation = match text_param(p, "notation", C)? {
|
||||
Some("hex") => Some(css::Notation::Hex),
|
||||
Some("hexAlpha") => Some(css::Notation::HexAlpha),
|
||||
Some("rgb") => Some(css::Notation::Rgb),
|
||||
Some("hsl") => Some(css::Notation::Hsl),
|
||||
Some("oklch") => Some(css::Notation::Oklch),
|
||||
Some("cmyk") => None,
|
||||
_ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")),
|
||||
};
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let intent = cms.settings().intent;
|
||||
let text = match notation {
|
||||
None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)),
|
||||
Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")),
|
||||
// The working RGB numbers, as the Color panel's hex field and color.parse read them; for
|
||||
// oklch() the working RGB space is sRGB.
|
||||
Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n),
|
||||
};
|
||||
Ok(json!({ "text": text }))
|
||||
}
|
||||
|
||||
fn parse_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.parse";
|
||||
let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?;
|
||||
@@ -1032,7 +1066,229 @@ const BELOW_SIDE: f64 = 1.0;
|
||||
/// The pixels per point [`color_below`] renders at.
|
||||
const BELOW_SCALE: f64 = 4.0;
|
||||
|
||||
/// What `color.contrast` measures a color against: the background, and how the color is drawn over
|
||||
/// it (its row, object, groups and layer, each with its blend mode and opacity over the art below
|
||||
/// it). The Color Wheel panel's contrast lines measure many colors against one.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Backdrop {
|
||||
/// The background in display sRGB.
|
||||
against: [f32; 3],
|
||||
/// The background in working RGB, rounded to 8 bits, as the answer writes it.
|
||||
written: [u8; 3],
|
||||
/// The levels the color is drawn through, innermost first, without those that leave it as it is.
|
||||
passes: Vec<Pass>,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with.
|
||||
stain: Option<(Color, f32)>,
|
||||
/// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
|
||||
rich_black: bool,
|
||||
}
|
||||
|
||||
/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
|
||||
/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
|
||||
/// the art below it inside the level around it, while a blending level lies further out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Pass {
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
backdrop: ([f32; 3], f32),
|
||||
blends: bool,
|
||||
isolate: bool,
|
||||
inner: f32,
|
||||
}
|
||||
|
||||
/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
|
||||
/// level out holds drawn alone.
|
||||
type Through = ([f32; 3], f32, f32);
|
||||
|
||||
impl Pass {
|
||||
/// What the level draws for color and alpha `x`, drawn over the art below it: a level that
|
||||
/// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
|
||||
fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
|
||||
if !self.blends {
|
||||
return x;
|
||||
}
|
||||
if alone <= 0.0 {
|
||||
return (x.0, 0.0);
|
||||
}
|
||||
let b = self.backdrop;
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
}
|
||||
|
||||
/// `d` drawn through the level. The level's opacity applies to what it holds, a level that
|
||||
/// isolates its blending carries out the alpha of what it holds composited on its own, and the
|
||||
/// art beside it in the level around it adds to the alpha once.
|
||||
fn draw(&self, (color, alpha, alone): Through) -> Through {
|
||||
let source = self.source((color, alpha), alone);
|
||||
let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
|
||||
let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
|
||||
(color, alpha, drawn + self.inner * (1.0 - drawn))
|
||||
}
|
||||
|
||||
/// The level with its opacity, the art below it and its alphas passed through `q`.
|
||||
fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
|
||||
let (color, alpha) = self.backdrop;
|
||||
Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
|
||||
/// fill stains mixes its solid color towards the stain.
|
||||
pub fn drawn_color(&self, c: &Color) -> Color {
|
||||
match self.stain {
|
||||
Some((stain, amount)) => c.lerp(&stain, amount),
|
||||
None => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
|
||||
/// `cms` and the Appearance of Black the backdrop was read with.
|
||||
pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
|
||||
shown_rgb(cms, self.rich_black, &self.drawn_color(c))
|
||||
}
|
||||
|
||||
/// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
|
||||
pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
|
||||
let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
|
||||
if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
|
||||
}
|
||||
|
||||
/// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
|
||||
/// the background.
|
||||
pub fn ratio(&self, shown: [f32; 3]) -> f64 {
|
||||
wcag::contrast_ratio(self.front(shown), self.against)
|
||||
}
|
||||
|
||||
/// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
|
||||
/// below each level, the background, the opacities, and the color and alpha each level gives.
|
||||
fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let painted = |c: [f32; 3]| c.map(eight);
|
||||
let against = painted(self.against);
|
||||
let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
|
||||
let (color, alpha, alone) = p.with(eight).draw(d);
|
||||
(painted(color), eight(alpha), eight(alone))
|
||||
});
|
||||
let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
|
||||
wcag::contrast_ratio(painted(front), against)
|
||||
}
|
||||
|
||||
/// The background as `#rrggbb` in working RGB, the form a color param takes.
|
||||
pub fn against_hex(&self) -> String {
|
||||
let [r, g, b] = self.written;
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
|
||||
/// 100 % K alone shows as black.
|
||||
fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
|
||||
match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
|
||||
/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
|
||||
/// Gray color as gray.
|
||||
fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
|
||||
let [r, g, b] = cms.srgb_to_rgb(srgb);
|
||||
let rgb = Color::rgb(r, g, b);
|
||||
match like {
|
||||
Color::Rgb { .. } => rgb,
|
||||
Color::Cmyk { .. } => {
|
||||
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
|
||||
Color::cmyk(c, m, y, k)
|
||||
}
|
||||
Color::Lab { .. } => {
|
||||
let l = cms.lab(&rgb);
|
||||
Color::lab(l.l, l.a, l.b)
|
||||
}
|
||||
Color::Gray { .. } => keep_model(*like, rgb),
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
|
||||
/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
|
||||
/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
|
||||
/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
|
||||
/// [`Backdrop::ratio`], or when no lightness of its hue does.
|
||||
fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option<Color> {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let ratio = |srgb: [f32; 3]| {
|
||||
let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
|
||||
backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
|
||||
};
|
||||
if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
|
||||
return None;
|
||||
}
|
||||
let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
|
||||
Some(in_model_of(&cms, fix, color))
|
||||
}
|
||||
|
||||
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
contrast_measure(s, p).map(|(answer, _)| answer)
|
||||
}
|
||||
|
||||
/// `color.contrast`'s answer for params `p`, and what it measured the color against.
|
||||
pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
let category = match p.get("for") {
|
||||
None | Some(Value::Null) => Category::NormalText,
|
||||
Some(v) => {
|
||||
let key = "for";
|
||||
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
|
||||
v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
|
||||
}
|
||||
};
|
||||
let (color, backdrop) = contrast_backdrop(s, p)?;
|
||||
let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
}
|
||||
};
|
||||
let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
|
||||
Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
|
||||
None => Value::Null,
|
||||
};
|
||||
let fixes = match category.minimums() {
|
||||
(aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
|
||||
(aa, None) => json!({ "aa": fix(aa) }),
|
||||
};
|
||||
let answer = json!({
|
||||
"ratio": ratio,
|
||||
"against": backdrop.against_hex(),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
"for": category.id(),
|
||||
"fix": fixes,
|
||||
});
|
||||
Ok((answer, backdrop))
|
||||
}
|
||||
|
||||
/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
|
||||
/// what it measures it against.
|
||||
fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
|
||||
let (color, backdrop) = contrast_reading(s, p, true)?;
|
||||
let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
|
||||
Ok((color, backdrop))
|
||||
}
|
||||
|
||||
/// What a color picked for the active proxy would be measured against by `color.contrast` with
|
||||
/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
|
||||
/// Color Wheel's contrast lines show where a pick would pass.
|
||||
pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result<Backdrop> {
|
||||
contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
|
||||
}
|
||||
|
||||
/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
|
||||
/// `need_color`.
|
||||
fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option<Color>, Backdrop)> {
|
||||
const C: &str = "color.contrast";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity").and_then(Value::as_f64) {
|
||||
@@ -1044,23 +1300,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
};
|
||||
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
|
||||
let given = p.get("color").is_some_and(|v| !v.is_null());
|
||||
let (color, drawn) = match p.get("color") {
|
||||
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
|
||||
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
|
||||
Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
|
||||
};
|
||||
if need_color && color.is_none() {
|
||||
return Err(bad(C, no_color()));
|
||||
}
|
||||
let rich_black = s.prefs.black_on_screen == "rich";
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let shown = |c: &Color| match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
};
|
||||
let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
|
||||
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// Whether the background read is one color across its pixels.
|
||||
let mut uniform = true;
|
||||
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
|
||||
let (against, written) = match p.get("against").filter(|_| !below) {
|
||||
None => {
|
||||
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
|
||||
// one the ratio uses, and giving it back answers the same ratio.
|
||||
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
|
||||
let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
|
||||
uniform &= one;
|
||||
let working = to_8bit(cms.srgb_to_rgb(sample));
|
||||
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
|
||||
}
|
||||
Some(v) => {
|
||||
@@ -1096,60 +1357,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
|
||||
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
|
||||
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
|
||||
// The alphas, the art below each level and `alone` do not depend on the color, so each level
|
||||
// is read once here and [`Backdrop::front`] draws any color through the levels.
|
||||
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
|
||||
let mut x = (shown(&color), 1.0f32);
|
||||
let mut passes = vec![];
|
||||
let mut alpha = 1.0f32;
|
||||
let mut alone = 1.0f32;
|
||||
// Whether a level so far read art that is not one color.
|
||||
let mut mixed = false;
|
||||
for (k, step) in steps.iter().enumerate() {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let above = &steps[k + 1..];
|
||||
let scope = above.iter().find(|a| a.isolate);
|
||||
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
|
||||
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
|
||||
let backdrop = match scope {
|
||||
Some(_) if !sampled => ([0.0; 3], 0.0),
|
||||
None if !sampled => (against, 1.0),
|
||||
let (backdrop, one) = match scope {
|
||||
Some(_) if !sampled => (([0.0; 3], 0.0), true),
|
||||
None if !sampled => ((against, 1.0), uniform),
|
||||
// The background itself, as the answer writes it.
|
||||
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
|
||||
None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
|
||||
_ => read(scope.map(|a| &a.within))?,
|
||||
};
|
||||
// The alpha of the art below the level inside the level around it, while a blending level
|
||||
// lies further out (none for a given background).
|
||||
let inner = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
|
||||
_ => 0.0,
|
||||
let (inner, inner_one) = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
|
||||
let ((_, a), one) = read(Some(&around.within))?;
|
||||
(a, one)
|
||||
}
|
||||
_ => (0.0, true),
|
||||
};
|
||||
let source = if !blends(step) {
|
||||
x
|
||||
} else if alone <= 0.0 {
|
||||
(x.0, 0.0)
|
||||
} else {
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
};
|
||||
// A level that isolates its blending carries out the alpha of what it holds composited on
|
||||
// its own.
|
||||
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
|
||||
x = composite(step.blend, source, step.opacity, backdrop);
|
||||
alone = drawn + inner * (1.0 - drawn);
|
||||
}
|
||||
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
|
||||
let ratio = wcag::contrast_ratio(front, against);
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
// A blend mode mixes the color with the art below it pixel by pixel, which one color read for
|
||||
// art of several colors does not stand for, also when that art reaches it through the levels
|
||||
// inside it.
|
||||
mixed |= !one || !inner_one;
|
||||
if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
|
||||
return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
|
||||
}
|
||||
};
|
||||
let [r, g, b] = written;
|
||||
Ok(json!({
|
||||
"ratio": ratio,
|
||||
"against": format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
}))
|
||||
let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
|
||||
(_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
|
||||
passes.push(pass);
|
||||
}
|
||||
let stain = if given { None } else { stain_of(s, !need_color) };
|
||||
Ok((color, Backdrop { against, written, passes, stain, rich_black }))
|
||||
}
|
||||
|
||||
/// An object around the proxy's object: one in the document, or a group of the picked object's
|
||||
@@ -1232,7 +1484,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
|
||||
/// levels that change what they draw must be the same objects too, since the art below each one is
|
||||
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
|
||||
/// since the row draws over the object's rows below it and the object over the art behind it, and a
|
||||
/// row that blends or is translucent must lie over the same shown rows.
|
||||
/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
|
||||
/// blends, with the same isolation.
|
||||
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
|
||||
let level = |x: &Level, y: &Level| {
|
||||
@@ -1248,10 +1501,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
|
||||
// A row that blends or lets art through draws over the rows below it, read at one point.
|
||||
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
|
||||
// A lower row that blends reads the art behind the object unless the object isolates its
|
||||
// blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
|
||||
// row at no opacity does not show, nor does a fill row without effects under an opaque solid
|
||||
// Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
|
||||
let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
|
||||
let covers = |i: &vectorcraft_doc::AppearanceItem| {
|
||||
plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
|
||||
};
|
||||
let over_blended = |d: &Drawn| {
|
||||
over_rows(d)
|
||||
&& d.lower
|
||||
.iter()
|
||||
.enumerate()
|
||||
.any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
|
||||
};
|
||||
row(a) == row(b)
|
||||
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
|
||||
&& a.blend == b.blend
|
||||
&& (row(a).is_none() || a.isolate == b.isolate)
|
||||
&& (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
|
||||
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
|
||||
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
|
||||
&& la.len() == lb.len()
|
||||
@@ -1263,8 +1532,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
|
||||
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
|
||||
/// objects in different translucent or blending groups or layers differ, since the art below each
|
||||
/// such level is read with it hidden.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
|
||||
/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern),
|
||||
/// and the drawing is then the one a solid color in its place would have.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option<Color>, Drawn), String> {
|
||||
let stroke = !s.fill_active;
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
if if stroke { stroke_mixed } else { fill_mixed } {
|
||||
@@ -1320,20 +1590,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
|
||||
} else {
|
||||
drawing = source()?.unwrap_or_default();
|
||||
}
|
||||
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
|
||||
match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
|
||||
let found = match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Some((color, drawing.clone())),
|
||||
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
|
||||
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => Err(no_color()),
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => None,
|
||||
};
|
||||
Ok(match found {
|
||||
Some((color, drawn)) => (Some(color), drawn),
|
||||
None => (None, drawing),
|
||||
})
|
||||
}
|
||||
|
||||
/// The message for an active fill or stroke with no color to measure.
|
||||
fn no_color() -> String {
|
||||
"the active fill or stroke has no color: give `color`".to_string()
|
||||
}
|
||||
|
||||
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
|
||||
@@ -1398,19 +1676,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> s
|
||||
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
|
||||
}
|
||||
|
||||
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
|
||||
/// `color` itself otherwise.
|
||||
fn stained(s: &Session, color: Color) -> Color {
|
||||
let stain = s.active().and_then(|st| {
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
|
||||
});
|
||||
match stain {
|
||||
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
|
||||
None => color,
|
||||
/// The color and amount a fill stains the picked object of a dynamic symbol instance with
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
|
||||
/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
|
||||
/// or a pattern counts too, as the pick puts a solid color in its place.
|
||||
fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
|
||||
let (fill, stroke) = s.proxy_paints();
|
||||
match if s.fill_active { fill } else { stroke } {
|
||||
Paint::Solid { .. } => {}
|
||||
Paint::None | Paint::Pattern { .. } if pick => {}
|
||||
_ => return None,
|
||||
}
|
||||
let st = s.active()?;
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
|
||||
@@ -1455,14 +1735,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
|
||||
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
|
||||
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
|
||||
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
|
||||
/// without artboards.
|
||||
/// without artboards. Also whether the square's pixels are all one color.
|
||||
fn color_below(
|
||||
s: &Session,
|
||||
rich_black: bool,
|
||||
hide: Option<&Part>,
|
||||
full: &[&Part],
|
||||
scope: Option<&Part>,
|
||||
) -> std::result::Result<([f32; 3], f32), String> {
|
||||
) -> std::result::Result<(([f32; 3], f32), bool), String> {
|
||||
super::has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selection.objects.clone();
|
||||
@@ -1591,8 +1871,10 @@ fn color_below(
|
||||
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
|
||||
let px = img.pixels.as_chunks::<4>().0;
|
||||
if px.is_empty() {
|
||||
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
|
||||
return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
|
||||
}
|
||||
// Whether the pixels are one color, to within one step of 255 per channel.
|
||||
let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
|
||||
// The pixels are premultiplied: the average color is their sum over their alpha's.
|
||||
let mut sum = [0.0f64; 4];
|
||||
for p in px {
|
||||
@@ -1602,10 +1884,10 @@ fn color_below(
|
||||
}
|
||||
let alpha = sum[3] / (px.len() as f64 * 255.0);
|
||||
if alpha <= 0.0 {
|
||||
return Ok(([0.0; 3], 0.0));
|
||||
return Ok((([0.0; 3], 0.0), uniform));
|
||||
}
|
||||
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
|
||||
Ok((rgb, alpha as f32))
|
||||
Ok(((rgb, alpha as f32), uniform))
|
||||
}
|
||||
|
||||
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
|
||||
|
||||
@@ -920,7 +920,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result<Anchor> {
|
||||
};
|
||||
let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?);
|
||||
match v.get("smooth").filter(|b| !b.is_null()) {
|
||||
None | Some(Value::Bool(false)) => {}
|
||||
None => {}
|
||||
Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner,
|
||||
Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth,
|
||||
Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")),
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@
|
||||
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
|
||||
//! one out is not an undo step.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
|
||||
@@ -192,6 +194,51 @@ impl Options {
|
||||
/// Outlines with their layer colours ([`highlights`]).
|
||||
pub type Outlines = Vec<(BezPath, [u8; 3])>;
|
||||
|
||||
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
|
||||
/// allocation back until the outlines are found again.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Highlights {
|
||||
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
|
||||
/// it stroked for these outlines while the number stays the same.
|
||||
pub revision: u64,
|
||||
/// The outlines in each layer color, the colors in the order of their first outline.
|
||||
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
|
||||
}
|
||||
|
||||
/// The [`Highlights::revision`] the next set of outlines takes.
|
||||
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
|
||||
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
impl Highlights {
|
||||
/// `outlines` grouped by color, under a new revision.
|
||||
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
|
||||
if outlines.is_empty() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
|
||||
for (path, color) in outlines {
|
||||
match groups.iter_mut().find(|(c, _)| *c == color) {
|
||||
Some((_, paths)) => paths.push(path),
|
||||
None => groups.push((color, vec![path])),
|
||||
}
|
||||
}
|
||||
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
|
||||
}
|
||||
|
||||
/// How many outlines there are, in every color.
|
||||
pub fn len(&self) -> usize {
|
||||
self.groups.iter().map(|(_, paths)| paths.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether there is no outline.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.groups.iter().all(|(_, paths)| paths.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Global Edit in progress (per document; not saved, not an undo step).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlobalEdit {
|
||||
@@ -200,7 +247,7 @@ pub struct GlobalEdit {
|
||||
/// outline onto its own.
|
||||
pub members: Vec<(NodeId, Affine)>,
|
||||
/// [`highlights`] as of a document revision: the canvas asks every frame.
|
||||
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
|
||||
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
|
||||
}
|
||||
|
||||
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
|
||||
@@ -214,8 +261,18 @@ struct Form {
|
||||
frame: Affine,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`Form::of`] reduced an object to its form on this thread.
|
||||
pub(crate) static FORMS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread.
|
||||
pub(crate) static OUTLINES_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
#[cfg(test)]
|
||||
FORMS_MADE.with(|c| c.set(c.get() + 1));
|
||||
let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY };
|
||||
f.add(n, 0)?;
|
||||
let first = *f.points.first()?;
|
||||
@@ -450,8 +507,8 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
),
|
||||
};
|
||||
let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center());
|
||||
let in_scope = |n: &Node| {
|
||||
let Some(b) = n.geometric_bounds_with(&symbols) else { return false };
|
||||
let in_scope = |b: Option<Rect>| {
|
||||
let Some(b) = b else { return false };
|
||||
if !d.artboards.iter().any(|a| on(a.rect, b)) {
|
||||
return o.include_canvas;
|
||||
}
|
||||
@@ -459,14 +516,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
};
|
||||
// A copy that lies the same way has the size of the selected object when their boxes are as
|
||||
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
|
||||
let same_size = |n: &Node, xf: Affine, turned: bool| {
|
||||
let same_size = |b: Option<Rect>, xf: Affine, turned: bool| {
|
||||
if turned {
|
||||
close(xf.determinant().abs().sqrt(), 1.0)
|
||||
} else {
|
||||
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
|
||||
matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height()))
|
||||
}
|
||||
};
|
||||
let mut out = vec![(*id, Affine::IDENTITY)];
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.forms.pass();
|
||||
super::select::walk_selectable(d, st.isolation, |n| {
|
||||
if n.id == *id || out.len() >= MAX_MEMBERS {
|
||||
return false;
|
||||
@@ -482,21 +541,134 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
_ => false,
|
||||
};
|
||||
// The object count first: it turns most objects down before their form is made.
|
||||
if n.children().map(Vec::len) == count
|
||||
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
|
||||
&& (!o.size || same_size(n, xf, turned))
|
||||
&& (!o.appearance || same_look(key, n))
|
||||
&& in_scope(n)
|
||||
{
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
if n.children().map(Vec::len) != count {
|
||||
return look_in;
|
||||
}
|
||||
let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None });
|
||||
if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) {
|
||||
let b = seen.bounds(n, &symbols);
|
||||
if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) {
|
||||
out.push((n.id, xf));
|
||||
// A group taken is taken whole, as compound paths, symbol instances and the others are.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
look_in
|
||||
});
|
||||
cache.forms.end(pass, d);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to
|
||||
/// the next so that after an edit only the objects the edit replaced are measured again. A clone
|
||||
/// starts empty.
|
||||
#[derive(Default)]
|
||||
pub struct FormCache(std::cell::RefCell<FormCacheInner>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct FormCacheInner {
|
||||
forms: ByNode<Seen>,
|
||||
/// The outline of each highlighted object, or `None` when it has none and its box is shown.
|
||||
outlines: ByNode<Option<BezPath>>,
|
||||
}
|
||||
|
||||
/// An object as [`matches`] found it.
|
||||
struct Seen {
|
||||
/// Its form, or `None` when Global Edit doesn't support it.
|
||||
form: Option<Form>,
|
||||
/// Its geometric bounds, once measured; not kept for an object with symbol instances, whose
|
||||
/// bounds follow the symbols' art.
|
||||
bounds: Option<Option<Rect>>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option<Rect> {
|
||||
if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) {
|
||||
return n.geometric_bounds_with(symbols);
|
||||
}
|
||||
*self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols))
|
||||
}
|
||||
}
|
||||
|
||||
/// Values found for nodes of a document, by node address. The layers they were found in are held,
|
||||
/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so
|
||||
/// no other node can have that address while its entry is here.
|
||||
struct ByNode<T> {
|
||||
layers: Vec<Arc<Node>>,
|
||||
values: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Default for ByNode<T> {
|
||||
fn default() -> Self {
|
||||
Self { layers: vec![], values: ByAddress::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Values by node address.
|
||||
type ByAddress<T> = std::collections::HashMap<usize, T, std::hash::BuildHasherDefault<AddressHasher>>;
|
||||
|
||||
/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low
|
||||
/// half (addresses are aligned, so their low bits are always the same).
|
||||
#[derive(Default)]
|
||||
struct AddressHasher(u64);
|
||||
|
||||
impl std::hash::Hasher for AddressHasher {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_usize(&mut self, n: usize) {
|
||||
let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15);
|
||||
self.0 = x ^ (x >> 32);
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One walk of a document: the values it asks for, taken from the ones kept or found anew.
|
||||
struct Pass<T> {
|
||||
old: ByAddress<T>,
|
||||
new: ByAddress<T>,
|
||||
}
|
||||
|
||||
impl<T> Pass<T> {
|
||||
fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T {
|
||||
let at = std::ptr::from_ref(n) as usize;
|
||||
let old = &mut self.old;
|
||||
self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ByNode<T> {
|
||||
fn pass(&mut self) -> Pass<T> {
|
||||
let old = std::mem::take(&mut self.values);
|
||||
Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old }
|
||||
}
|
||||
|
||||
/// Keep the values `pass` asked for, found in `d`.
|
||||
fn end(&mut self, pass: Pass<T>, d: &Document) {
|
||||
self.values = pass.new;
|
||||
self.layers.clone_from(&d.layers);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for FormCache {
|
||||
fn clone(&self) -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FormCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let c = self.0.borrow();
|
||||
f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.global_edit.is_some() {
|
||||
@@ -890,31 +1062,31 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
|
||||
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
|
||||
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
|
||||
/// ([`similar`]).
|
||||
pub fn highlights(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
let Some(ge) = &st.global_edit else { return similar(s) };
|
||||
if let Some((rev, out)) = &*ge.outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = outlines(st, &ge.members);
|
||||
let out = Highlights::new(outlines(st, &ge.members));
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
pub fn similar(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
return vec![];
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
@@ -923,10 +1095,10 @@ pub fn similar(s: &Session) -> Outlines {
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = match matches(s, o) {
|
||||
let out = Highlights::new(match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
};
|
||||
});
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
out
|
||||
}
|
||||
@@ -935,20 +1107,45 @@ pub fn similar(s: &Session) -> Outlines {
|
||||
/// selected object, in their layer's color.
|
||||
fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines {
|
||||
let symbols = st.doc.symbol_boxes();
|
||||
members
|
||||
let mut cache = st.global_edit_forms.0.borrow_mut();
|
||||
let mut pass = cache.outlines.pass();
|
||||
let out = members
|
||||
.iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?;
|
||||
if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) {
|
||||
return None;
|
||||
// One look-up of the object's place, then down through its layers and groups: none of
|
||||
// them may be selected, and the innermost layer gives the color.
|
||||
let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None);
|
||||
for i in st.doc.index_path(*id)? {
|
||||
let c: &Node = nodes.get(i)?;
|
||||
if st.selection.objects.contains(&c.id) {
|
||||
return None;
|
||||
}
|
||||
if c.is_layer() {
|
||||
layer = Some(c);
|
||||
}
|
||||
if let Some(ch) = c.children() {
|
||||
nodes = ch;
|
||||
}
|
||||
found = Some(c);
|
||||
}
|
||||
let path = match n.stroke_path() {
|
||||
Some(p) => p,
|
||||
let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?;
|
||||
let color = match layer.map(|l| &l.kind) {
|
||||
Some(NodeKind::Layer { color, .. }) => color.rgb(),
|
||||
_ => vectorcraft_doc::LAYER_COLORS[0].1,
|
||||
};
|
||||
let path = match pass.get(n, || {
|
||||
#[cfg(test)]
|
||||
OUTLINES_MADE.with(|c| c.set(c.get() + 1));
|
||||
n.stroke_path()
|
||||
}) {
|
||||
Some(p) => p.clone(),
|
||||
None => n.geometric_bounds_with(&symbols)?.to_path(0.1),
|
||||
};
|
||||
Some((path, st.doc.layer_color(*id)))
|
||||
Some((path, color))
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
cache.outlines.end(pass, &st.doc);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it, and
|
||||
//! `appearance.setNewArt` sets its fill, stroke and stroke options whatever is selected.
|
||||
//!
|
||||
//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile
|
||||
//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new`
|
||||
@@ -34,7 +35,7 @@ pub(crate) struct NewArtSource {
|
||||
|
||||
use super::gradient::unplaced;
|
||||
use super::paint::SelectionPaints;
|
||||
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or};
|
||||
use crate::doc_state::{SelectionRecord, objects_only};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -57,9 +58,181 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
describe
|
||||
),
|
||||
cmd!(
|
||||
"appearance.setNewArt",
|
||||
"Set New Art Appearance",
|
||||
[],
|
||||
None,
|
||||
"{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}",
|
||||
always,
|
||||
set_new_art
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The most dash and gap lengths `appearance.setNewArt` takes.
|
||||
const MAX_DASHES: usize = 64;
|
||||
/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes.
|
||||
const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"];
|
||||
/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points.
|
||||
const MAX_DASH_LENGTH: f64 = 1_000_000.0;
|
||||
|
||||
/// What [`dash_fault`] finds wrong with a list of dash and gap lengths.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum DashFault {
|
||||
/// More than [`MAX_DASHES`] lengths.
|
||||
TooMany,
|
||||
/// A length that is not a number from 0 to [`MAX_DASH_LENGTH`].
|
||||
OutOfRange,
|
||||
/// Lengths that are all 0.
|
||||
AllZero,
|
||||
}
|
||||
|
||||
/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the
|
||||
/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good.
|
||||
/// An empty list (a solid line) is good.
|
||||
pub(crate) fn dash_fault(lengths: &[f64]) -> Option<DashFault> {
|
||||
if lengths.len() > MAX_DASHES {
|
||||
Some(DashFault::TooMany)
|
||||
} else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) {
|
||||
Some(DashFault::OutOfRange)
|
||||
} else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) {
|
||||
Some(DashFault::AllZero)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of
|
||||
/// the document in front.
|
||||
pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color {
|
||||
super::paint::new_color(s, &json!({}), c)
|
||||
}
|
||||
|
||||
/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before
|
||||
/// anything changes.
|
||||
fn set_new_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.setNewArt";
|
||||
let paint = |key: &str, fill: bool| -> Result<Option<Paint>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if !v.is_object() {
|
||||
return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}")));
|
||||
}
|
||||
if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) {
|
||||
return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", "))));
|
||||
}
|
||||
if v.get("swatch").is_some_and(|w| !w.is_string()) {
|
||||
return Err(bad(C, format!("{key}: `swatch` must be a swatch name")));
|
||||
}
|
||||
let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some());
|
||||
if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) {
|
||||
return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`")));
|
||||
}
|
||||
let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?;
|
||||
if !fill && matches!(&given, Paint::Gradient(g) if g.gradient.dither) && v.get("swatch").and_then(Value::as_str).is_none() {
|
||||
return Err(bad(C, "`dither` applies to gradient fills"));
|
||||
}
|
||||
Ok(Some(unplaced(&given)))
|
||||
};
|
||||
let (fill, stroke) = (paint("fill", true)?, paint("stroke", false)?);
|
||||
let number = |key: &str, min: f64, max: f64| -> Result<()> {
|
||||
match p.get(key) {
|
||||
None => Ok(()),
|
||||
Some(v) if v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n)) => Ok(()),
|
||||
Some(v) => Err(bad(C, format!("{key} must be a number from {min} to {max}, got {v}"))),
|
||||
}
|
||||
};
|
||||
number("weight", 0.0, 1000.0)?;
|
||||
number("miterLimit", 1.0, 500.0)?;
|
||||
number("dashOffset", -MAX_DASH_LENGTH, MAX_DASH_LENGTH)?;
|
||||
for key in ["cap", "join"] {
|
||||
if p.get(key).is_some_and(|v| !v.is_string()) {
|
||||
return Err(bad(C, format!("{key} must be a name")));
|
||||
}
|
||||
}
|
||||
match p.get("dash") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(Value::Array(a)) => {
|
||||
let lengths: Option<Vec<f64>> = a.iter().map(Value::as_f64).collect();
|
||||
match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) {
|
||||
None => {}
|
||||
Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))),
|
||||
Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))),
|
||||
Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")),
|
||||
}
|
||||
}
|
||||
Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))),
|
||||
}
|
||||
let flag = |key: &str| -> Result<Option<bool>> {
|
||||
p.get(key).map(|v| v.as_bool().ok_or_else(|| bad(C, format!("{key} must be true or false, got {v}")))).transpose()
|
||||
};
|
||||
let (fill_overprint, stroke_overprint) = (flag("fillOverprint")?, flag("strokeOverprint")?);
|
||||
let options: serde_json::Map<String, Value> =
|
||||
["weight", "cap", "join", "miterLimit", "dash", "dashOffset"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect();
|
||||
let change = super::stroke::StrokeChange::parse(&Value::Object(options), C)?;
|
||||
let dashed = match p.get("dash") {
|
||||
Some(Value::Array(a)) => !a.is_empty(),
|
||||
Some(_) => false,
|
||||
None => s.new_art().stroke().is_some_and(|st| st.dash.is_some()),
|
||||
};
|
||||
if p.get("dashOffset").and_then(Value::as_f64).is_some_and(|o| o != 0.0) && !dashed {
|
||||
return Err(bad(C, "dashOffset needs a dash pattern"));
|
||||
}
|
||||
let nothing = fill.is_none() && stroke.is_none() && change.is_empty() && fill_overprint.is_none() && stroke_overprint.is_none();
|
||||
if !nothing
|
||||
&& !s.prefs.new_art_basic
|
||||
&& !(s.tool_paints(false) && s.tool_paints(true))
|
||||
&& s.active().is_some_and(|st| !st.selection.subjects().is_empty())
|
||||
{
|
||||
return Err(bad(
|
||||
C,
|
||||
"with New Art Has Basic Appearance off, new art takes the selected object's appearance: deselect it or turn the option on",
|
||||
));
|
||||
}
|
||||
let look = |s: &Session| {
|
||||
let (opacity, blend, style) = s.new_art_transparency();
|
||||
(s.new_art(), opacity, blend, style.map(str::to_string))
|
||||
};
|
||||
let (before, was) = (s.paint.clone(), look(s));
|
||||
if let Some(f) = fill {
|
||||
s.paint.fill = f;
|
||||
}
|
||||
if let Some(st) = stroke {
|
||||
if !st.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = st;
|
||||
}
|
||||
if let Some(w) = change.weight {
|
||||
s.paint.stroke_width = w;
|
||||
}
|
||||
if !change.is_empty()
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
change.apply(st);
|
||||
}
|
||||
if let Some(on) = fill_overprint {
|
||||
let t = s.new_art_template_mut();
|
||||
if t.fill().is_none() {
|
||||
t.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
}
|
||||
if let Some(f) = t.fill_mut() {
|
||||
f.overprint = on;
|
||||
}
|
||||
}
|
||||
if let Some(on) = stroke_overprint
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.overprint = on;
|
||||
}
|
||||
let changed = look(s) != was;
|
||||
if !changed {
|
||||
s.paint = before;
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// `t` reduced to a basic appearance: an empty fill under its top stroke (options kept, without
|
||||
/// its own transparency or effects).
|
||||
fn basic_of(t: &Appearance) -> Appearance {
|
||||
|
||||
@@ -180,8 +180,9 @@ pub struct DocSettings {
|
||||
pub layout: ArtboardLayout,
|
||||
/// Columns of a grid layout.
|
||||
pub columns: u32,
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a
|
||||
/// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`).
|
||||
#[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")]
|
||||
pub rows: u32,
|
||||
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
|
||||
/// outside that range is read as the nearer end).
|
||||
@@ -380,12 +381,25 @@ impl DocSettings {
|
||||
return Ok(());
|
||||
}
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
|
||||
let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32);
|
||||
for (k, v) in o {
|
||||
match k.as_str() {
|
||||
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
|
||||
"columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?,
|
||||
"rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?,
|
||||
"columns" => {
|
||||
self.columns = v
|
||||
.as_f64()
|
||||
.filter(|c| c.is_finite() && *c >= 1.0)
|
||||
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
|
||||
.round()
|
||||
.min(MAX_ARTBOARDS as f64) as u32
|
||||
}
|
||||
"rows" => {
|
||||
self.rows = v
|
||||
.as_f64()
|
||||
.map(f64::round)
|
||||
.filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r))
|
||||
.map(|r| r as u32)
|
||||
.ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))?
|
||||
}
|
||||
"spacing" => {
|
||||
self.spacing = v
|
||||
.as_f64()
|
||||
@@ -590,6 +604,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
|
||||
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
|
||||
/// place) stays 0.
|
||||
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
|
||||
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points.
|
||||
fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D::Error> {
|
||||
Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING))
|
||||
|
||||
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency Info",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none); editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
|
||||
"{id?|ids?} → {ids, opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", knockoutShape, editingMask, pageIsolatedBlending, pageKnockoutGroup} the Transparency panel's values for `ids`, the selection, or the object whose mask is being edited. A value is null where those objects differ (or there are none). Without ids or id, with an object of a dynamic symbol instance selected by Direct Selection, opacity and blend are that object's for this instance, as transparency.set changes them; editingMask is the id of the object whose mask is being edited, or null; the page values are the document's",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -489,10 +489,16 @@ impl Session {
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = transparency_targets(s, p)?;
|
||||
// The points `transparency.set` with the same `ids` (or none) fades.
|
||||
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
|
||||
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
// Without `ids` or `id`, the values `transparency.set` without them edits: those of the panel,
|
||||
// whose picked mesh points and selected dynamic symbol part take the opacity (and the part the
|
||||
// blend mode).
|
||||
let i = if p.get("ids").is_none() && p.get("id").is_none() {
|
||||
s.transparency_info()
|
||||
} else {
|
||||
let ids = transparency_targets(s, p)?;
|
||||
let points = super::paint::picked_mesh_points_of(s, &ids);
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
};
|
||||
Ok(json!({
|
||||
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
|
||||
"opacity": i.opacity,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Language packs as commands (#4936): list, install and remove the packs that spell-check and
|
||||
//! hyphenate languages other than English ([`crate::packs`]). They open nothing and never turn
|
||||
//! downloading on: an install needs the Craft apps' shared download setting, which only the person
|
||||
//! using an app turns on.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
|
||||
use crate::packs::{self, Outcome};
|
||||
|
||||
/// The Language pack commands.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "proof.packs",
|
||||
"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)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
query "proof.installPack",
|
||||
"Install Language Pack",
|
||||
[],
|
||||
None,
|
||||
"{locale: language tag (a pack's locale from proof.packs, like nl or pt-br)} downloads the pack, checks its sha256 and installs it; spelling and hyphenation in that language use it at once, in every open document. Needs downloading on, which only the person using a Craft app can turn on. Refused under automation roots (the store is outside them). Opens nothing. In the desktop app it runs in the background → {locale, started: true}: follow it with proof.packs (installing, then installed or errors); elsewhere it returns once installed → {locale, installed: true}",
|
||||
always,
|
||||
install
|
||||
),
|
||||
cmd!(
|
||||
query "proof.removePack",
|
||||
"Remove Language Pack",
|
||||
[],
|
||||
None,
|
||||
"{locale} removes the installed pack (not while it installs; refused under automation roots); that language is no longer checked with it → {locale, installed: false}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn locale_param(p: &Value, command: &str) -> Result<String> {
|
||||
let raw = text_param(p, "locale", command)?.ok_or_else(|| bad(command, "`locale` (a language tag like nl) is required"))?;
|
||||
packs::parse_locale(raw).map_err(|e| bad(command, e))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "proof.packs";
|
||||
match p.get("refresh") {
|
||||
None | Some(Value::Null) | Some(Value::Bool(false)) => {}
|
||||
Some(Value::Bool(true)) => {
|
||||
not_confined(C)?;
|
||||
packs::refresh().map_err(EngineError::Other)?;
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`refresh` must be true or false")),
|
||||
}
|
||||
// The jobs before the installed packs: an install makes craft-proof read its pack before it
|
||||
// leaves the jobs, so one that ends between the two reads is in one list or the other.
|
||||
let packs::Status { installing, refreshing, errors } = packs::status();
|
||||
let installed = craft_proof::packs::installed();
|
||||
let backend = packs::backend();
|
||||
let rows: Vec<Value> = packs::available()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
json!({
|
||||
"locale": p.locale, "name": p.name, "size": p.size, "licence": p.licence, "class": p.class,
|
||||
"spelling": p.spelling, "hyphenation": p.hyphenation,
|
||||
"installed": installed.iter().any(|i| i.locale == p.locale),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// An install that ended since the last frame shows in every document's layout.
|
||||
s.poll_language_packs();
|
||||
Ok(json!({
|
||||
"packs": rows,
|
||||
"installed": installed.iter().map(|i| json!({"locale": i.locale, "name": i.name, "licence": i.licence})).collect::<Vec<_>>(),
|
||||
"installing": installing.iter().map(|(l, done, total)| json!({"locale": l, "done": done, "total": total})).collect::<Vec<_>>(),
|
||||
"refreshing": refreshing,
|
||||
"errors": errors,
|
||||
"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(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
if crate::file_access::current().is_some() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"automation path rejected: {command} writes the Language packs into the font store the Craft apps share, outside the automation roots"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let locale = locale_param(p, "proof.installPack")?;
|
||||
not_confined("proof.installPack")?;
|
||||
match packs::install(&locale).map_err(EngineError::Other)? {
|
||||
Outcome::Started => Ok(json!({"locale": locale, "started": true})),
|
||||
Outcome::Done => {
|
||||
s.poll_language_packs();
|
||||
Ok(json!({"locale": locale, "installed": true}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let locale = locale_param(p, "proof.removePack")?;
|
||||
not_confined("proof.removePack")?;
|
||||
packs::remove(&locale).map_err(EngineError::Other)?;
|
||||
s.poll_language_packs();
|
||||
Ok(json!({"locale": locale, "installed": false}))
|
||||
}
|
||||
@@ -913,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
apply_paint_opacity(s, p, paint, opacity, fill)
|
||||
}
|
||||
|
||||
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
|
||||
/// when it is left out or null.
|
||||
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as
|
||||
/// 0..1; `None` when it is left out or null.
|
||||
pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
|
||||
match p.get("opacity") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => match v.as_f64() {
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry",
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry",
|
||||
has_doc,
|
||||
set_anchors
|
||||
),
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject};
|
||||
use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clean Up…",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}",
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}",
|
||||
has_doc,
|
||||
clean_up
|
||||
),
|
||||
@@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value.
|
||||
pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4;
|
||||
/// The widths Hairline Slivers takes, in points.
|
||||
pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive<f64> = 0.001..=3.0;
|
||||
|
||||
/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string
|
||||
/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`].
|
||||
pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result<f64> {
|
||||
let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH);
|
||||
if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) {
|
||||
let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end());
|
||||
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths
|
||||
/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke),
|
||||
/// whose fill no circle `width` across fits inside? A compound path is measured as one fill.
|
||||
/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]).
|
||||
/// A hidden member of a compound path is measured too, since the compound path paints it.
|
||||
fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option<bool> {
|
||||
// A shape with no fill that paints is left to Unpainted Objects.
|
||||
if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) {
|
||||
return Some(false);
|
||||
}
|
||||
let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind {
|
||||
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut all = vec![];
|
||||
for c in children {
|
||||
let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) };
|
||||
all.extend(path.subpaths.iter());
|
||||
}
|
||||
(all, *rule)
|
||||
}
|
||||
_ => return Some(false),
|
||||
};
|
||||
// Paths of one anchor are stray points, and open paths are lines.
|
||||
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) {
|
||||
return Some(false);
|
||||
}
|
||||
po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget)
|
||||
}
|
||||
|
||||
/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an
|
||||
/// effect on the object or on one of its fills and strokes?
|
||||
fn draws_beyond_its_fill(a: &Appearance) -> bool {
|
||||
a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty())
|
||||
}
|
||||
|
||||
/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a
|
||||
/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping
|
||||
/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers
|
||||
/// leaves its members alone.
|
||||
fn holds_generated_art(n: &Node) -> bool {
|
||||
let e = n.extras();
|
||||
vectorcraft_tools::builder::is_live_paint(n)
|
||||
|| e.type_outlines
|
||||
|| e.clip_pieces
|
||||
|| e.graph.is_some()
|
||||
|| e.shaper.is_some()
|
||||
|| e.dimension.is_some()
|
||||
|| e.flare.is_some()
|
||||
|| e.trace.is_some()
|
||||
|| e.objects_on_path.is_some()
|
||||
|| e.live_paint_gaps.is_some()
|
||||
|| e.compound_shape
|
||||
}
|
||||
|
||||
/// The objects Hairline Slivers finds in `d` for `width`.
|
||||
pub(crate) struct Slivers {
|
||||
pub ids: Vec<NodeId>,
|
||||
/// Closed paths and compound paths whose fill couldn't be measured, which are left as they are.
|
||||
pub unmeasured: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any.
|
||||
pub(crate) fn unmeasured_warning(count: usize) -> Option<String> {
|
||||
(count > 0).then(|| {
|
||||
format!(
|
||||
"Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not
|
||||
/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and
|
||||
/// groups of the whole document. A compound path counts as one object. The clipping paths of groups
|
||||
/// and layers (and all of a clipping group used as one), the members of live and generated art,
|
||||
/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and
|
||||
/// layers whose own stroke or effect paints them are left out.
|
||||
pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers {
|
||||
struct Walk<'a> {
|
||||
width: f64,
|
||||
locks: LockedArtboards<'a>,
|
||||
within: &'a dyn Fn(NodeId) -> bool,
|
||||
// One budget for the whole document, so that thousands of shapes that need a search take
|
||||
// a bounded time; the shapes after it runs out count as unmeasured.
|
||||
budget: po::ThicknessBudget,
|
||||
out: Vec<(NodeId, Option<bool>)>,
|
||||
}
|
||||
fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) {
|
||||
// An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing.
|
||||
if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) {
|
||||
return;
|
||||
}
|
||||
let clips = n.clips();
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
visit(c, clips && i == 0, w);
|
||||
}
|
||||
}
|
||||
// Art on a locked artboard, or outside `within`, is left out before it is measured.
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => {
|
||||
match is_hairline_sliver(n, w.width, &mut w.budget) {
|
||||
Some(false) => {}
|
||||
found => w.out.push((n.id, found)),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] };
|
||||
for l in &d.layers {
|
||||
visit(l, false, &mut w);
|
||||
}
|
||||
let mut found = w.out;
|
||||
let editable = d.editable();
|
||||
found.retain(|(id, _)| editable(*id));
|
||||
let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some());
|
||||
Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() }
|
||||
}
|
||||
|
||||
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.path.cleanUp";
|
||||
let stray = switch_or(p, "strayPoints", true, C)?;
|
||||
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
|
||||
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
|
||||
let found = {
|
||||
let slivers = switch_or(p, "hairlineSlivers", false, C)?;
|
||||
let width = sliver_width(p, "sliverWidth", C)?;
|
||||
let (found, warning) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut v = vec![];
|
||||
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
|
||||
@@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
let mut warning = None;
|
||||
if slivers {
|
||||
let found = hairline_slivers(d, width, &|_| true);
|
||||
let listed: BTreeSet<NodeId> = v.iter().copied().collect();
|
||||
// A shape another option removes isn't left as it is.
|
||||
warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count());
|
||||
v.extend(found.ids.into_iter().filter(|id| !listed.contains(id)));
|
||||
}
|
||||
(v, warning)
|
||||
};
|
||||
let reply = |removed: usize| match &warning {
|
||||
Some(w) => json!({ "removed": removed, "warning": w }),
|
||||
None => json!({ "removed": removed }),
|
||||
};
|
||||
if found.is_empty() {
|
||||
return Ok(json!({ "removed": 0 }));
|
||||
return Ok(reply(0));
|
||||
}
|
||||
s.edit("Clean Up", |d, _| {
|
||||
let mut gone = Beside::replacing(d, &found);
|
||||
@@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
gone.finish(d)
|
||||
})?;
|
||||
Ok(json!({ "removed": found.len() }))
|
||||
Ok(reply(found.len()))
|
||||
}
|
||||
|
||||
// ---------- Divide Objects Below ----------
|
||||
|
||||
@@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
"“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
@@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !refused.is_empty() {
|
||||
v["refusedCommands"] = json!(refused);
|
||||
}
|
||||
let translations = &plugin.manifest().translations;
|
||||
if !translations.is_empty() {
|
||||
v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null);
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -1910,6 +1914,9 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
|
||||
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
|
||||
/// record one for another module → its report; saves the disabled list when loading changed it.
|
||||
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
|
||||
// Only native builds load modules, so only they save the disabled list.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (s, turn);
|
||||
let (report, retry) = match load.load.take() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(modules)) => {
|
||||
@@ -2447,7 +2454,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
|
||||
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
|
||||
@@ -70,6 +70,8 @@ const DENIED_PREFIXES: &[&str] = &[
|
||||
"text.rescanFonts",
|
||||
"text.fontList",
|
||||
"text.spelling.",
|
||||
// Language packs: downloads into, and removals from, the font store the Craft apps share.
|
||||
"proof.",
|
||||
"colorTheme.",
|
||||
"magicWand.",
|
||||
"eyedropper.",
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.arrange.grid",
|
||||
"addon.arrange.groupOverlapping",
|
||||
"addon.arrange.match",
|
||||
"addon.arrange.offset",
|
||||
"addon.arrange.randomizeOpacity",
|
||||
"addon.arrange.replace",
|
||||
"addon.arrange.size",
|
||||
@@ -104,6 +106,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"appearance.removeItem",
|
||||
"appearance.setActiveItem",
|
||||
"appearance.setItem",
|
||||
"appearance.setNewArt",
|
||||
"appearance.showAllHidden",
|
||||
"appearance.targetContents",
|
||||
"appearance.transfer",
|
||||
@@ -152,6 +155,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"charStyle.setAttrs",
|
||||
"charStyle.unused",
|
||||
"color.convert",
|
||||
"color.format",
|
||||
"color.gamutCheck",
|
||||
"color.harmony",
|
||||
"color.parse",
|
||||
@@ -542,6 +546,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.object.brushStrokes",
|
||||
"select.object.clippingMasks",
|
||||
"select.object.directionHandles",
|
||||
"select.object.hairlineSlivers",
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"select.object.pointText",
|
||||
"select.object.slices",
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::script;
|
||||
pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"];
|
||||
|
||||
/// The extensions of the scripts `script.run` takes as a file, in any case.
|
||||
pub const RUN_EXTS: &[&str] = &["js", "jsx"];
|
||||
pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"];
|
||||
|
||||
/// Does `path` name a file `script.run` takes?
|
||||
pub fn runs(path: &str) -> bool {
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handler
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Installed Scripts",
|
||||
[],
|
||||
None,
|
||||
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
"{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
@@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
|
||||
let fuel = max_fuel(p)?;
|
||||
let installed = switch_or(p, "installed", false, "script.run")?;
|
||||
let module = switch_or(p, "module", script::include::module_script(path), "script.run")?;
|
||||
let mut checked_real = None;
|
||||
let text = match (path, source) {
|
||||
(Some(""), None) => return Err(param("`path` is empty")),
|
||||
@@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
return Err(EngineError::Other(COMPILED.to_string()));
|
||||
}
|
||||
if !runs(path) {
|
||||
return Err(param("`path` must name a .js or .jsx file"));
|
||||
return Err(param("`path` must name a .js, .mjs or .jsx file"));
|
||||
}
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?;
|
||||
@@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
|
||||
fuel,
|
||||
locale,
|
||||
answers,
|
||||
module,
|
||||
actions,
|
||||
})
|
||||
}
|
||||
@@ -444,6 +446,7 @@ impl Session {
|
||||
fuel,
|
||||
locale,
|
||||
answers: vec![],
|
||||
module: script::include::module_script(path.to_str()),
|
||||
actions: vec![],
|
||||
};
|
||||
let runs = self.script_runs;
|
||||
|
||||
@@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::object::can_align;
|
||||
use super::panelcmds::artboard_at;
|
||||
use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning};
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
|
||||
@@ -205,6 +206,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| p.anchor_count() == 1))),
|
||||
cmd!(
|
||||
"select.object.hairlineSlivers",
|
||||
"Hairline Slivers…",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}",
|
||||
has_doc,
|
||||
select_hairline_slivers
|
||||
),
|
||||
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| !p.is_closed()))),
|
||||
@@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes
|
||||
/// ([`hairline_slivers`]), inside the isolated group while one is isolated.
|
||||
fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.object.hairlineSlivers";
|
||||
let width = sliver_width(p, "width", C)?;
|
||||
let st = s.doc()?;
|
||||
let (d, iso) = (&st.doc, st.isolation);
|
||||
let locks = d.locked_artboards();
|
||||
let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id));
|
||||
let warning = unmeasured_warning(found.unmeasured.len());
|
||||
s.select(|_, sel| sel.set(found.ids))?;
|
||||
let count = s.doc()?.selection.objects.len();
|
||||
Ok(match warning {
|
||||
Some(w) => json!({ "count": count, "warning": w }),
|
||||
None => json!({ "count": count }),
|
||||
})
|
||||
}
|
||||
|
||||
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
|
||||
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
|
||||
/// does not look at the paths inside it.
|
||||
|
||||
@@ -325,10 +325,11 @@ pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize
|
||||
/// not, since a save takes in the words another window saved), and a dictionary file attached.
|
||||
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
|
||||
/// out of date (Auto Spell Check checks the type again).
|
||||
/// The dictionaries' generation: what [`misspellings`] found before it last changed may be out of
|
||||
/// date (Auto Spell Check checks the type again). It moves on with the custom dictionary and with
|
||||
/// craft-proof's own dictionaries, which change when a Language pack is installed or removed.
|
||||
pub fn dictionary_generation() -> u64 {
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed)
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed).wrapping_add(craft_proof::dictionary_generation())
|
||||
}
|
||||
|
||||
fn dictionary_changed() {
|
||||
|
||||
@@ -86,6 +86,9 @@ pub struct DocState {
|
||||
/// Whether Start Global Edit supports the one selected object
|
||||
/// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable.
|
||||
pub(crate) global_edit_support: cmd::globaledit::SupportCache,
|
||||
/// The forms Start Global Edit compared the selected object with
|
||||
/// ([`cmd::globaledit::FormCache`]). Not saved, not undoable.
|
||||
pub(crate) global_edit_forms: cmd::globaledit::FormCache,
|
||||
/// What leaving symbol editing mode goes back to ([`cmd::symboledit`]).
|
||||
pub(crate) symbol_edit_return: cmd::symboledit::Return,
|
||||
pub interaction: Option<Interaction>,
|
||||
@@ -481,6 +484,7 @@ impl DocState {
|
||||
global_edit: None,
|
||||
similar_outlines: Default::default(),
|
||||
global_edit_support: Default::default(),
|
||||
global_edit_forms: Default::default(),
|
||||
symbol_edit_return: Default::default(),
|
||||
interaction: None,
|
||||
undo_group: None,
|
||||
|
||||
@@ -715,6 +715,15 @@ impl ScriptScope {
|
||||
|
||||
/// The real path of the file at `path` and its first `max` bytes, at most.
|
||||
pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec<u8>), ScriptRead> {
|
||||
match self.read_unless(path, max, |_| false)? {
|
||||
(real, Some(bytes)) => Ok((real, bytes)),
|
||||
(_, None) => Err(ScriptRead::Failed("the file was not read".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened:
|
||||
/// → its real path and no bytes.
|
||||
pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option<Vec<u8>>), ScriptRead> {
|
||||
use std::io::Read;
|
||||
if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() {
|
||||
return Err(ScriptRead::Refused);
|
||||
@@ -730,6 +739,9 @@ impl ScriptScope {
|
||||
if !self.allows(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
if known(&real) {
|
||||
return Ok((real, None));
|
||||
}
|
||||
let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?;
|
||||
if !meta.is_file() {
|
||||
@@ -747,7 +759,7 @@ impl ScriptScope {
|
||||
if std::fs::canonicalize(path).ok().as_ref() != Some(&real) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
Ok((real, bytes))
|
||||
Ok((real, Some(bytes)))
|
||||
}
|
||||
|
||||
/// The first granted folder, as people read it (`None` for a script given as text).
|
||||
@@ -966,6 +978,21 @@ mod tests {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// A file the caller already has is not opened: its size is not checked and no byte is read.
|
||||
#[test]
|
||||
fn a_known_script_file_is_not_read_again() {
|
||||
let (base, _) = folders("known");
|
||||
std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap();
|
||||
let scope = ScriptScope::of_folder(&base.join("in"));
|
||||
let path = base.join("in/big.js");
|
||||
assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge));
|
||||
let real = std::fs::canonicalize(&path).unwrap();
|
||||
assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None)));
|
||||
assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64)));
|
||||
assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind
|
||||
/// only one grants is not granted.
|
||||
#[test]
|
||||
|
||||
@@ -127,6 +127,12 @@ impl HistoryEntry {
|
||||
self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str()))
|
||||
}
|
||||
|
||||
/// A number no other step takes ([`History::step`]). Undo and Redo make the step they move
|
||||
/// with a new number, and so does an edit merged into the newest step.
|
||||
pub fn serial(&self) -> u64 {
|
||||
self.serial
|
||||
}
|
||||
|
||||
/// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the
|
||||
/// document before the undo, whose next state is now `now` (that step's document). Its figures
|
||||
/// are that step's the other way round when `doc` is still the document they were taken
|
||||
|
||||
@@ -12,6 +12,8 @@ pub mod guard;
|
||||
pub mod inspect;
|
||||
pub mod journal;
|
||||
pub mod link_watch;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod packs;
|
||||
pub mod schemas;
|
||||
pub mod steps;
|
||||
pub mod store;
|
||||
@@ -33,7 +35,7 @@ pub use cmd::flare::flare_settings;
|
||||
pub use cmd::gradient::{GradientEditPaints, StopOwner};
|
||||
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
|
||||
pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::{auto_simplify_level, can_outline_stroke};
|
||||
pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke};
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
|
||||
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
|
||||
@@ -220,6 +222,9 @@ pub struct Session {
|
||||
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
|
||||
/// that starts them ([`Session::load_plugins_in_background`]).
|
||||
plugin_loads_in_background: bool,
|
||||
/// The Language packs' generation the documents were last laid out for
|
||||
/// ([`Session::poll_language_packs`]).
|
||||
packs_seen: u64,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Language packs (#4936, RFC-0011): the spelling dictionary, hyphenation patterns and licence
|
||||
//! texts of a language other than English, published by storytold/craft-i18n and installed into the
|
||||
//! Craft apps' shared font store (craft-libs `craft-font-store`, item kind `language-pack`), where
|
||||
//! craft-proof reads them (`craft_proof::packs`). A pack installed by another Craft app is used
|
||||
//! here too, since the apps share the store.
|
||||
//!
|
||||
//! The store downloads only while its download setting is on, which only the person using an app
|
||||
//! turns on, with their own click. Nothing here turns it on: [`use_font_store`] opens the store as
|
||||
//! an agent's, so `proof.installPack` from the CLI, MCP or a script installs only after the person
|
||||
//! allowed downloads.
|
||||
//!
|
||||
//! The packs state is the process's, like craft-proof's: one backend ([`set_backend`]), one list of
|
||||
//! installs running and one error per locale. In the desktop app installs run on a thread of their
|
||||
//! own ([`run_in_background`]) and [`crate::Session::poll_language_packs`] lays out the documents
|
||||
//! again when one ends; elsewhere they return once installed.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
|
||||
|
||||
pub use craft_font_store::Cancel;
|
||||
|
||||
/// One pack the pack index lists.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Pack {
|
||||
/// Lowercase BCP 47 tag (`nl`, `pt-br`), also the installed pack's folder name.
|
||||
pub locale: String,
|
||||
/// The language's own name (`Nederlands`).
|
||||
pub name: String,
|
||||
/// The download's size in bytes.
|
||||
pub size: u64,
|
||||
/// SPDX licence expression of the pack's data.
|
||||
pub licence: String,
|
||||
/// The licence class: `Embeddable` or `Download-only`.
|
||||
pub class: String,
|
||||
/// Whether it has a spelling dictionary.
|
||||
pub spelling: bool,
|
||||
/// Whether it has hyphenation patterns.
|
||||
pub hyphenation: bool,
|
||||
}
|
||||
|
||||
/// Where packs come from and go to: the font store ([`use_font_store`]), or a stand-in in tests.
|
||||
pub trait Backend: Send + Sync {
|
||||
/// The installed-packs folder craft-proof reads.
|
||||
fn packs_dir(&self) -> PathBuf;
|
||||
/// Whether the person allowed downloads.
|
||||
fn downloads_on(&self) -> bool;
|
||||
/// The packs of the index fetched last, with no request; empty before the first fetch.
|
||||
fn cached_index(&self) -> Vec<Pack>;
|
||||
/// Fetches the pinned pack index (needs downloads on).
|
||||
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String>;
|
||||
/// Downloads, checks and installs the pack for `locale`, which the index lists (needs downloads
|
||||
/// on), calling `progress(done, total)` in bytes.
|
||||
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String>;
|
||||
/// Removes the installed pack for `locale`.
|
||||
fn remove(&self, locale: &str) -> Result<(), String>;
|
||||
/// The test index used instead of the pinned one (`CRAFT_LANGUAGE_PACK_INDEX`), if any.
|
||||
fn index_override(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// An install running.
|
||||
struct Job {
|
||||
done: u64,
|
||||
total: u64,
|
||||
cancel: Cancel,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jobs {
|
||||
installing: BTreeMap<String, Job>,
|
||||
/// A fetch of the index running.
|
||||
refreshing: Option<Cancel>,
|
||||
/// The last failure of each locale's install or removal, and of the index fetch (key `""`).
|
||||
errors: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
static BACKEND: RwLock<Option<Arc<dyn Backend>>> = RwLock::new(None);
|
||||
static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refreshing: None, errors: BTreeMap::new() });
|
||||
static BACKGROUND: AtomicBool = AtomicBool::new(false);
|
||||
/// Goes up each time the installed packs change.
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn jobs() -> MutexGuard<'static, Jobs> {
|
||||
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Use `backend` for packs (`None`: none), and have craft-proof read its installed packs.
|
||||
pub fn set_backend(backend: Option<Arc<dyn Backend>>) {
|
||||
let dir = backend.as_ref().map(|b| b.packs_dir());
|
||||
*BACKEND.write().unwrap_or_else(PoisonError::into_inner) = backend;
|
||||
craft_proof::packs::set_packs_dir(dir);
|
||||
changed();
|
||||
}
|
||||
|
||||
/// The backend [`set_backend`] set.
|
||||
pub fn backend() -> Option<Arc<dyn Backend>> {
|
||||
BACKEND.read().unwrap_or_else(PoisonError::into_inner).clone()
|
||||
}
|
||||
|
||||
/// Use the Craft apps' shared font store for packs, as an agent's store (it can't turn downloads
|
||||
/// on): the desktop app and `vectorcraft-cli` call it at startup. Without a per-user folder there
|
||||
/// are no packs.
|
||||
pub fn use_font_store() {
|
||||
let env = craft_font_catalog::FontEnv::from_process();
|
||||
set_backend(craft_font_store::FontStore::for_agent(&env).map(|store| Arc::new(FontStoreBackend::new(store)) as Arc<dyn Backend>));
|
||||
}
|
||||
|
||||
/// Run installs and index fetches on a thread of their own (the desktop app, so its window keeps
|
||||
/// working) instead of returning once they are done.
|
||||
pub fn run_in_background(on: bool) {
|
||||
BACKGROUND.store(on, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Goes up each time the installed packs change ([`crate::Session::poll_language_packs`]).
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Read the packs folder again: spelling and hyphenation in its languages change.
|
||||
fn changed() {
|
||||
craft_proof::packs::reload();
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether an install or an index fetch is running.
|
||||
pub fn busy() -> bool {
|
||||
let j = jobs();
|
||||
!j.installing.is_empty() || j.refreshing.is_some()
|
||||
}
|
||||
|
||||
/// `raw` as a pack locale: trimmed, lower case, `_` read as `-` (`pt_BR` is `pt-br`); a language
|
||||
/// tag of letters and digits, at most 35 bytes, in parts of at most 8.
|
||||
pub fn parse_locale(raw: &str) -> Result<String, String> {
|
||||
let l = raw.trim().to_ascii_lowercase().replace('_', "-");
|
||||
let ok = !l.is_empty()
|
||||
&& l.len() <= 35
|
||||
&& l.split('-').all(|p| !p.is_empty() && p.len() <= 8 && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()));
|
||||
if ok { Ok(l) } else { Err(format!("{:?} is not a language tag like nl or pt-br", raw.chars().take(40).collect::<String>())) }
|
||||
}
|
||||
|
||||
fn no_backend() -> String {
|
||||
"Language packs aren't available: there is no font store folder for this user".into()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// The packs the index fetched last lists.
|
||||
pub fn available() -> Vec<Pack> {
|
||||
backend().map(|b| b.cached_index()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What `proof.packs` reports about the jobs.
|
||||
pub struct Status {
|
||||
/// The installs running, as (locale, bytes done, bytes in all).
|
||||
pub installing: Vec<(String, u64, u64)>,
|
||||
/// Whether the index is being fetched.
|
||||
pub refreshing: bool,
|
||||
/// The last error of each locale (`""`: the index fetch).
|
||||
pub errors: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// The jobs running and the last errors.
|
||||
pub fn status() -> Status {
|
||||
let j = jobs();
|
||||
Status {
|
||||
installing: j.installing.iter().map(|(l, job)| (l.clone(), job.done, job.total)).collect(),
|
||||
refreshing: j.refreshing.is_some(),
|
||||
errors: j.errors.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What an install or a fetch did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// Done.
|
||||
Done,
|
||||
/// Running in the background ([`run_in_background`]).
|
||||
Started,
|
||||
}
|
||||
|
||||
/// Runs `job` on a thread of its own in the background, else here and gives its own result (never
|
||||
/// another call's, which the shared errors also hold). `undo` takes the job's entry back when its
|
||||
/// thread can't start.
|
||||
fn run(job: impl FnOnce() -> Result<(), String> + Send + 'static, undo: impl FnOnce()) -> Result<Outcome, String> {
|
||||
if !BACKGROUND.load(Ordering::Relaxed) {
|
||||
return job().map(|()| Outcome::Done);
|
||||
}
|
||||
match std::thread::Builder::new().name("language-pack".into()).spawn(move || {
|
||||
// The result is kept in the shared errors for `proof.packs`.
|
||||
let _ = job();
|
||||
}) {
|
||||
Ok(_) => Ok(Outcome::Started),
|
||||
Err(e) => {
|
||||
undo();
|
||||
Err(format!("couldn't start the download: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the pinned pack index again. Needs downloads on.
|
||||
pub fn refresh() -> Result<Outcome, String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if !b.downloads_on() {
|
||||
return Err(downloads_off());
|
||||
}
|
||||
let cancel = {
|
||||
let mut j = jobs();
|
||||
if j.refreshing.is_some() {
|
||||
return Ok(Outcome::Started);
|
||||
}
|
||||
let cancel = Cancel::new();
|
||||
j.refreshing = Some(cancel.clone());
|
||||
j.errors.remove("");
|
||||
cancel
|
||||
};
|
||||
run(
|
||||
move || {
|
||||
let r = b.fetch_index(&cancel).map(|_| ());
|
||||
let mut j = jobs();
|
||||
j.refreshing = None;
|
||||
if let Err(e) = &r {
|
||||
j.errors.insert(String::new(), e.clone());
|
||||
}
|
||||
r
|
||||
},
|
||||
|| jobs().refreshing = None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Installs the pack for `locale` (fetching the index first when it doesn't list it). Needs
|
||||
/// downloads on. Spelling and hyphenation in that language use it once it is installed.
|
||||
pub fn install(locale: &str) -> Result<Outcome, String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if !b.downloads_on() {
|
||||
return Err(downloads_off());
|
||||
}
|
||||
let locale = locale.to_string();
|
||||
let cancel = {
|
||||
let mut j = jobs();
|
||||
if j.installing.contains_key(&locale) {
|
||||
return Ok(Outcome::Started);
|
||||
}
|
||||
let cancel = Cancel::new();
|
||||
j.installing.insert(locale.clone(), Job { done: 0, total: 0, cancel: cancel.clone() });
|
||||
j.errors.remove(&locale);
|
||||
cancel
|
||||
};
|
||||
let l = locale.clone();
|
||||
run(
|
||||
move || {
|
||||
let r = install_now(&*b, &l, &cancel);
|
||||
// craft-proof reads the new pack before the job ends, so a caller that sees no
|
||||
// install running sees the pack installed (`proof.packs`, `busy`).
|
||||
if r.is_ok() {
|
||||
changed();
|
||||
}
|
||||
let mut j = jobs();
|
||||
j.installing.remove(&l);
|
||||
if let Err(e) = &r {
|
||||
j.errors.insert(l, e.clone());
|
||||
}
|
||||
r
|
||||
},
|
||||
|| {
|
||||
jobs().installing.remove(&locale);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
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)?) {
|
||||
return Err(format!("there is no Language pack for {locale}"));
|
||||
}
|
||||
b.install(locale, cancel, &mut |done, total| {
|
||||
if let Some(job) = jobs().installing.get_mut(locale) {
|
||||
(job.done, job.total) = (done, total);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Stops the install of `locale` (or the index fetch, for `""`) if one is running.
|
||||
pub fn cancel(locale: &str) {
|
||||
let j = jobs();
|
||||
let c = if locale.is_empty() { j.refreshing.as_ref() } else { j.installing.get(locale).map(|job| &job.cancel) };
|
||||
if let Some(c) = c {
|
||||
c.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the installed pack for `locale`; not while it is installing.
|
||||
pub fn remove(locale: &str) -> Result<(), String> {
|
||||
let b = backend().ok_or_else(no_backend)?;
|
||||
if jobs().installing.contains_key(locale) {
|
||||
return Err(format!("the {locale} pack is still installing"));
|
||||
}
|
||||
let r = b.remove(locale);
|
||||
changed();
|
||||
let mut j = jobs();
|
||||
match &r {
|
||||
Ok(()) => j.errors.remove(locale),
|
||||
Err(e) => j.errors.insert(locale.to_string(), e.clone()),
|
||||
};
|
||||
r
|
||||
}
|
||||
|
||||
/// 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).
|
||||
pub const PACK_INDEX: craft_font_store::PackIndexPin = craft_font_store::PackIndexPin {
|
||||
url: "https://github.com/storytold/craft-i18n/releases/download/language-packs-2/index.json",
|
||||
sha256: "b35c7aef0591177f18233b551da16035dcd615549ff874e169ffd19f16fea74b",
|
||||
};
|
||||
|
||||
/// The font store as the packs [`Backend`].
|
||||
struct FontStoreBackend {
|
||||
store: craft_font_store::FontStore,
|
||||
/// The index read or fetched last: an install takes its entry (URL, size, sha256) from it.
|
||||
index: Mutex<Option<craft_font_store::PackIndex>>,
|
||||
}
|
||||
|
||||
impl FontStoreBackend {
|
||||
fn new(store: craft_font_store::FontStore) -> Self {
|
||||
Self { store, index: Mutex::new(None) }
|
||||
}
|
||||
|
||||
fn keep(&self, index: craft_font_store::PackIndex) -> Vec<Pack> {
|
||||
let packs = index
|
||||
.packs
|
||||
.iter()
|
||||
.map(|e| Pack {
|
||||
locale: e.locale.clone(),
|
||||
name: e.name.clone(),
|
||||
size: e.size,
|
||||
licence: e.licence.clone(),
|
||||
class: e.class.clone(),
|
||||
spelling: e.spelling,
|
||||
hyphenation: e.hyphenation,
|
||||
})
|
||||
.collect();
|
||||
*self.index.lock().unwrap_or_else(PoisonError::into_inner) = Some(index);
|
||||
packs
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for FontStoreBackend {
|
||||
fn packs_dir(&self) -> PathBuf {
|
||||
self.store.language_packs_dir()
|
||||
}
|
||||
|
||||
fn downloads_on(&self) -> bool {
|
||||
self.store.network() == craft_font_store::Network::On
|
||||
}
|
||||
|
||||
fn cached_index(&self) -> Vec<Pack> {
|
||||
self.store.cached_language_pack_index(&PACK_INDEX).map(|i| self.keep(i)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn fetch_index(&self, cancel: &Cancel) -> Result<Vec<Pack>, String> {
|
||||
let index = self.store.fetch_language_pack_index(&PACK_INDEX, cancel).map_err(|e| e.to_string())?;
|
||||
Ok(self.keep(index))
|
||||
}
|
||||
|
||||
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
|
||||
let held = self.index.lock().unwrap_or_else(PoisonError::into_inner).clone();
|
||||
let index = held.or_else(|| self.store.cached_language_pack_index(&PACK_INDEX)).ok_or("the list of Language packs hasn't been fetched")?;
|
||||
let entry = index.pack(locale).ok_or_else(|| format!("there is no Language pack for {locale}"))?.clone();
|
||||
self.store.install_language_pack(&index, &entry, cancel, &mut |p| progress(p.done, p.total)).map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn remove(&self, locale: &str) -> Result<(), String> {
|
||||
self.store.remove_language_pack(locale).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn index_override(&self) -> Option<String> {
|
||||
craft_font_store::language_pack_index_overridden()
|
||||
}
|
||||
}
|
||||
|
||||
/// The font store backend in `dir`, for tests that need the real store without a request.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn font_store_in(dir: PathBuf) -> Arc<dyn Backend> {
|
||||
Arc::new(FontStoreBackend::new(craft_font_store::FontStore::new(dir, craft_font_store::Caller::Agent)))
|
||||
}
|
||||
+202
-27
@@ -44,6 +44,9 @@
|
||||
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
|
||||
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
//! - `app.activeDocument` with no document open throws `No active document`.
|
||||
//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run
|
||||
//! made; with no such step they change nothing, and with no document open they throw
|
||||
//! `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
@@ -108,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod paths;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
@@ -158,14 +168,38 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is
|
||||
/// open, the settings of each `DocumentPreset` the run made, with the size of the values they hold
|
||||
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
|
||||
/// gave out.
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
/// The last list of each document's paths ([`paths`]), kept while that document is unchanged.
|
||||
paths: RefCell<Vec<ItemList>>,
|
||||
/// A path and its subpaths with the point changes the run has made to it and not written yet
|
||||
/// ([`flush`]).
|
||||
pending: RefCell<Option<(Item, Vec<vectorcraft_geom::path::SubPath>)>>,
|
||||
/// The index of the first point of each subpath of the path whose points the run read last,
|
||||
/// and what they were counted from ([`paths`]).
|
||||
point_starts: RefCell<Option<(paths::Counted, Rc<Vec<usize>>)>>,
|
||||
/// How many times the points the run read of each path went stale, by document uid and path id
|
||||
/// ([`paths`]).
|
||||
point_cuts: RefCell<std::collections::HashMap<(u64, u64), u64>>,
|
||||
/// Each path whose points the run read, as the run last saw it, by document uid and then path
|
||||
/// id ([`paths`]).
|
||||
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
|
||||
/// The path whose points the object model is writing with `path.setAnchors`, the only path
|
||||
/// that command changes ([`paths`]).
|
||||
one_path: Cell<Option<Item>>,
|
||||
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
|
||||
/// points it read ([`paths`]).
|
||||
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
text: text::TextState,
|
||||
@@ -220,6 +254,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The most documents whose lists [`State`] keeps at once, the least recently listed going first.
|
||||
const KEPT_LISTS: usize = 8;
|
||||
|
||||
/// The list kept in `lists` for the document `st`, while that document is unchanged.
|
||||
fn kept_list(lists: &RefCell<Vec<ItemList>>, st: &DocState) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had.
|
||||
fn keep_list(lists: &RefCell<Vec<ItemList>>, st: &DocState, ids: &Rc<Vec<NodeId>>) {
|
||||
let mut l = lists.borrow_mut();
|
||||
l.retain(|(uid, ..)| *uid != st.uid);
|
||||
if l.len() >= KEPT_LISTS {
|
||||
l.remove(0);
|
||||
}
|
||||
l.push((st.uid, st.doc.clone(), ids.clone()));
|
||||
}
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
@@ -276,15 +328,40 @@ type Answer = std::result::Result<Data, HostError>;
|
||||
/// A member function: the run's host and the call's arguments, `this` first.
|
||||
type Member = fn(&Host, &[Data]) -> Answer;
|
||||
|
||||
/// A member function that first writes the point changes waiting in [`State`] ([`flush`]).
|
||||
fn function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, true)
|
||||
}
|
||||
|
||||
/// A member function of the points of a path, which reads and adds to the point changes waiting in
|
||||
/// [`State`] instead of writing them first.
|
||||
fn point_function(link: &Link, f: Member) -> HostFunction {
|
||||
call(link, f, false)
|
||||
}
|
||||
|
||||
fn call(link: &Link, f: Member, flushing: bool) -> HostFunction {
|
||||
let l = link.clone();
|
||||
Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(data_size).sum::<u64>())?;
|
||||
if flushing {
|
||||
flush(&h)?;
|
||||
}
|
||||
f(&h, &a)
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]).
|
||||
pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> {
|
||||
paths::flush(h)
|
||||
}
|
||||
|
||||
/// Notes the changes a command made to the points of the paths the run has read
|
||||
/// ([`paths::see_all_points`]).
|
||||
pub(super) fn see_points(h: &Host) {
|
||||
paths::see_all_points(h)
|
||||
}
|
||||
|
||||
fn get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(function(link, f))
|
||||
}
|
||||
@@ -297,6 +374,19 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(function(link, f))
|
||||
}
|
||||
|
||||
/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]).
|
||||
fn point_get(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Get(point_function(link, f))
|
||||
}
|
||||
|
||||
fn point_property(link: &Link, g: Member, s: Member) -> HostMember {
|
||||
HostMember::Property { get: point_function(link, g), set: point_function(link, s) }
|
||||
}
|
||||
|
||||
fn point_method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(point_function(link, f))
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
pub(super) type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
@@ -312,8 +402,9 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
|
||||
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
/// the check that a document, page item, path point or text range `this` is still there.
|
||||
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
|
||||
/// `reflect` leaves it out.
|
||||
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
@@ -324,9 +415,12 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
|
||||
"Document" => {
|
||||
doc_of(&h, arg(&a, 0), "Document")?;
|
||||
}
|
||||
"PageItem" | "TextFrame" => {
|
||||
"PageItem" | "PathItem" | "TextFrame" => {
|
||||
item_of(&h, arg(&a, 0))?;
|
||||
}
|
||||
"PathPoint" => {
|
||||
paths::this_point(&h, &a)?;
|
||||
}
|
||||
"TextRange" => {
|
||||
text::check_range(&h, arg(&a, 0))?;
|
||||
}
|
||||
@@ -653,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
return Ok(());
|
||||
}
|
||||
let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id);
|
||||
// Anchors and segments the change removed (a path opened or given fewer points) are left out.
|
||||
let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| {
|
||||
doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test))
|
||||
};
|
||||
let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len());
|
||||
let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true));
|
||||
let kept: Vec<NodeId> = before.objects.iter().copied().filter(keep).collect();
|
||||
if kept.is_empty() {
|
||||
command(h, "select.none", &json!({}))?;
|
||||
@@ -665,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(),
|
||||
// A path with only segments selected gets them back below, with no anchors.
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
@@ -676,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?;
|
||||
}
|
||||
for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) {
|
||||
let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect();
|
||||
let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect();
|
||||
if segments.is_empty() {
|
||||
continue;
|
||||
}
|
||||
command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?;
|
||||
}
|
||||
let guides: Vec<NodeId> = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect();
|
||||
@@ -796,9 +899,15 @@ pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
paths::see_all_points(h);
|
||||
let kept = h.dom.editing.replace(Some(item));
|
||||
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params)));
|
||||
h.dom.editing.set(kept);
|
||||
r
|
||||
}
|
||||
|
||||
/// Reads the document of `doc` with `f`.
|
||||
@@ -827,6 +936,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach
|
||||
/// only the steps the run made. With no step to undo or redo they change nothing.
|
||||
fn app_history(h: &Host, id: &str, redo: bool) -> Answer {
|
||||
let has_step = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
|
||||
if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() }
|
||||
};
|
||||
if has_step {
|
||||
command(h, id, &json!({}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn app_undo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.undo", false)
|
||||
}
|
||||
|
||||
fn app_redo(h: &Host, _: &[Data]) -> Answer {
|
||||
app_history(h, "edit.redo", true)
|
||||
}
|
||||
|
||||
fn app_selection(h: &Host, _: &[Data]) -> Answer {
|
||||
let uid = h.session.borrow().active().map(|st| st.uid);
|
||||
match uid {
|
||||
@@ -1183,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s
|
||||
})
|
||||
}
|
||||
|
||||
/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first
|
||||
/// built-in preset with `presetSettings` over them.
|
||||
const BUILT_IN_SETTINGS: &[&str] = &[
|
||||
"width",
|
||||
"height",
|
||||
"units",
|
||||
"artboards",
|
||||
"artboardLayout",
|
||||
"bleed",
|
||||
"backgroundContents",
|
||||
"colorMode",
|
||||
"rasterEffectsPpi",
|
||||
"previewMode",
|
||||
"alignNewObjectsToPixelGrid",
|
||||
];
|
||||
|
||||
/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from
|
||||
/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in
|
||||
/// place of the profile's.
|
||||
@@ -1229,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())),
|
||||
Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())),
|
||||
}
|
||||
// The document starts from the first preset of the profile's category (Print: Letter).
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
if let Some(m) = mode {
|
||||
p.entry("colorMode").or_insert_with(|| json!(m));
|
||||
}
|
||||
// The document starts from the first built-in preset of the profile's category (Print:
|
||||
// Letter) with `presetSettings` over it, given in full so that a saved preset of the same name
|
||||
// does not stand in for it. Settings the built-in preset refuses are an error.
|
||||
let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next());
|
||||
if let Some(first) = first {
|
||||
p.insert("preset".into(), json!(first.name));
|
||||
let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?;
|
||||
if let Value::Object(settings) = full.to_json() {
|
||||
for key in BUILT_IN_SETTINGS {
|
||||
if let Some(v) = settings.get(*key) {
|
||||
p.insert((*key).into(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n)));
|
||||
// A profile whose file could not be read throws, and the document `file.new` made with the
|
||||
// defaults is put back, with the Recent sizes as they were.
|
||||
atomically(h, |h| {
|
||||
@@ -1746,6 +1903,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
// The ids listed so far; `ids` keeps them in the order they were first listed.
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(list.len());
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
@@ -1982,6 +2140,7 @@ fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
|
||||
|
||||
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let name = &text_arg(arg(a, 1), "name")?;
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
@@ -2000,11 +2159,11 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
|
||||
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
|
||||
/// or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let note = &text_arg(arg(a, 1), "note")?;
|
||||
if note.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the note is too long".into()));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim()));
|
||||
if !same {
|
||||
edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?;
|
||||
@@ -2038,8 +2197,9 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let hidden = boolean(arg(a, 1), "hidden")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
|
||||
}
|
||||
|
||||
@@ -2048,8 +2208,9 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let locked = boolean(arg(a, 1), "locked")?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
@@ -2058,6 +2219,7 @@ fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let v = number(arg(a, 1), "opacity")?;
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
@@ -2067,7 +2229,6 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let item = this_item(h, a)?;
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
@@ -2113,12 +2274,12 @@ fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
|
||||
/// would still replace the blend mode a graph keeps for the item's series or kind.
|
||||
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
|
||||
let item = this_item(h, a)?;
|
||||
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
|
||||
@@ -2245,16 +2406,19 @@ fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
}
|
||||
|
||||
fn item_set_position(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let p = point(arg(a, 1), "position")?;
|
||||
move_to(h, a, Some(p[0]), Some(p[1]))
|
||||
}
|
||||
|
||||
fn item_set_left(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let x = coordinate(arg(a, 1), "left")?;
|
||||
move_to(h, a, Some(x), None)
|
||||
}
|
||||
|
||||
fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
this_item(h, a)?;
|
||||
let y = coordinate(arg(a, 1), "top")?;
|
||||
move_to(h, a, None, Some(y))
|
||||
}
|
||||
@@ -2263,12 +2427,12 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer {
|
||||
/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated
|
||||
/// objects included.
|
||||
fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let what = if width { "width" } else { "height" };
|
||||
let size = number(arg(a, 1), what)?;
|
||||
if size <= 0.0 || size > MAX_SIZE {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
@@ -2655,6 +2819,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::install_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
@@ -2677,6 +2842,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
("redo", method(l, app_redo), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
@@ -2750,17 +2917,17 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
@@ -2861,7 +3028,15 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.push(class(
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! The color classes of the script object model, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/RGBColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/LabColor/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/> describe them.
|
||||
//!
|
||||
//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components,
|
||||
//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time.
|
||||
//! Components are checked when a color is assigned to an object, and a value out of range throws a
|
||||
//! `RangeError` with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{Link, current, num, text};
|
||||
|
||||
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
const CLASSES: &[(&str, &[&str])] = &[
|
||||
("RGBColor", &["red", "green", "blue"]),
|
||||
("CMYKColor", &["cyan", "magenta", "yellow", "black"]),
|
||||
("GrayColor", &["gray"]),
|
||||
("LabColor", &["l", "a", "b"]),
|
||||
("NoColor", &[]),
|
||||
("GradientColor", &[]),
|
||||
("SpotColor", &["tint"]),
|
||||
("PatternColor", &[]),
|
||||
];
|
||||
|
||||
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
let mut items = vec![("typename".to_string(), text(class))];
|
||||
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that
|
||||
/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read
|
||||
/// from an object gives that object the same color.
|
||||
fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 {
|
||||
let mut scale = 1e4;
|
||||
for _ in 4..=9 {
|
||||
let r = (exact * scale).round() / scale;
|
||||
if back(r) == v {
|
||||
return r;
|
||||
}
|
||||
scale *= 10.0;
|
||||
}
|
||||
exact
|
||||
}
|
||||
|
||||
/// A component stored as `v`, from 0 to 1, that the script sees times `scale`.
|
||||
fn shown(v: f32, scale: f64) -> f64 {
|
||||
shown_as(f64::from(v) * scale, v, |r| unit(r, scale))
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
"CMYKColor",
|
||||
&[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))],
|
||||
),
|
||||
Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]),
|
||||
Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]),
|
||||
}
|
||||
}
|
||||
|
||||
/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor`
|
||||
/// with its `tint` for a color linked to a global or spot swatch.
|
||||
pub(super) fn of_paint(paint: &Paint) -> Data {
|
||||
match paint {
|
||||
Paint::None => color_object("NoColor", &[]),
|
||||
Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]),
|
||||
Paint::Solid { color, .. } => of_color(color),
|
||||
Paint::Gradient(_) => color_object("GradientColor", &[]),
|
||||
Paint::Pattern { .. } => color_object("PatternColor", &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a
|
||||
/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes
|
||||
/// it what the document stores, or the components reading `now` gives (a Gray value read back can
|
||||
/// stand for an ink amount that no Gray value names exactly).
|
||||
pub(super) fn unchanged(d: &Data, assigned: Option<Color>, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool {
|
||||
match (assigned, now) {
|
||||
(None, Paint::None) => true,
|
||||
(Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the color object `d` has the class and every component of `shown`.
|
||||
fn shows(d: &Data, shown: &Data) -> bool {
|
||||
let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false };
|
||||
b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v))
|
||||
}
|
||||
|
||||
/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out).
|
||||
fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result<f64, HostError> {
|
||||
match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) {
|
||||
None | Some(Data::Undefined) => Ok(0.0),
|
||||
Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n),
|
||||
Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))),
|
||||
Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property.
|
||||
pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color>, HostError> {
|
||||
let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) };
|
||||
let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) {
|
||||
Some(Data::String(s)) => s.as_str(),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
};
|
||||
let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max);
|
||||
Ok(Some(match class {
|
||||
"NoColor" => return Ok(None),
|
||||
"RGBColor" => {
|
||||
Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) }
|
||||
}
|
||||
"CMYKColor" => Color::Cmyk {
|
||||
c: unit(c("cyan", 0.0, 100.0)?, 100.0),
|
||||
m: unit(c("magenta", 0.0, 100.0)?, 100.0),
|
||||
y: unit(c("yellow", 0.0, 100.0)?, 100.0),
|
||||
k: unit(c("black", 0.0, 100.0)?, 100.0),
|
||||
},
|
||||
"GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) },
|
||||
"LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) },
|
||||
l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))),
|
||||
_ => return Err(HostError::Type(format!("{what} must be a color object"))),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The constructors of the color classes, and `cmykColor`.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let make = |name: &str, components: &'static [&'static str]| {
|
||||
let l = link.clone();
|
||||
let class = name.to_string();
|
||||
let f: HostFunction = Rc::new(move |_| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect();
|
||||
Ok(color_object(&class, &zeros))
|
||||
});
|
||||
f
|
||||
};
|
||||
let mut out: Vec<HostClass> = CLASSES
|
||||
.iter()
|
||||
.map(|(name, components)| HostClass {
|
||||
name: (*name).into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make(name, components)),
|
||||
})
|
||||
.collect();
|
||||
out.push(HostClass {
|
||||
name: "cmykColor".into(),
|
||||
parent: None,
|
||||
members: Vec::new(),
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: Some(make("CMYKColor", CLASSES[1].1)),
|
||||
});
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! A document's default fill and stroke in the script object model, the `Document` members whose
|
||||
//! names start with `default` that the help page
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/> describes, and `scaleFactor`.
|
||||
//!
|
||||
//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for
|
||||
//! every open document, as the help page says of these global settings. Reading one reads new
|
||||
//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the
|
||||
//! selection, its art, the active proxy and the recent colors as they were. A value that changes
|
||||
//! nothing runs no command, and a bad value throws an error with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or
|
||||
//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or
|
||||
//! `defaultStroked` set to true with no default fill or stroke gives black.
|
||||
//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores
|
||||
//! it.
|
||||
//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of
|
||||
//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a
|
||||
//! dash pattern unless it is 0.
|
||||
//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default
|
||||
//! throws an error, since new art then takes that object's appearance.
|
||||
//! - `scaleFactor` is 1: VectorCraft draws every document at its own size.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, LineCap, LineJoin};
|
||||
use vectorcraft_js::{Data, HostError, MemberInfo};
|
||||
|
||||
use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths};
|
||||
use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed};
|
||||
|
||||
/// New art's appearance, after the check that the document `this` names is still open.
|
||||
fn new_art(h: &Host, a: &[Data]) -> std::result::Result<Appearance, HostError> {
|
||||
this_doc(h, a)?;
|
||||
Ok(h.session.borrow().new_art())
|
||||
}
|
||||
|
||||
/// Runs `appearance.setNewArt` with `params`, unless `same`.
|
||||
fn set(h: &Host, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
command(h, "appearance.setNewArt", ¶ms)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn top_paint(ap: &Appearance, fill: bool) -> Paint {
|
||||
if fill { ap.fill_paint() } else { ap.stroke_paint() }
|
||||
}
|
||||
|
||||
fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill)))
|
||||
}
|
||||
|
||||
fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" };
|
||||
let color = colors::assigned(arg(a, 1), what)?;
|
||||
let now = top_paint(&new_art(h, a)?, fill);
|
||||
let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c));
|
||||
let paint = match color {
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, same, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none()))
|
||||
}
|
||||
|
||||
fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?;
|
||||
let now = !top_paint(&new_art(h, a)?, fill).is_none();
|
||||
let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) };
|
||||
let key = if fill { "fill" } else { "stroke" };
|
||||
set(h, now == on, json!({ key: paint }))
|
||||
}
|
||||
|
||||
fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let ap = new_art(h, a)?;
|
||||
Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) }))
|
||||
}
|
||||
|
||||
fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer {
|
||||
let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") };
|
||||
let on = boolean(arg(a, 1), what)?;
|
||||
let now = default_overprint(h, a, fill)? == Data::Bool(on);
|
||||
set(h, now, json!({ key: on }))
|
||||
}
|
||||
|
||||
/// New art's top stroke option `f` reads, or `none` when new art has no stroke.
|
||||
fn stroke_option<T>(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result<T, HostError> {
|
||||
Ok(new_art(h, a)?.stroke().map_or(none, f))
|
||||
}
|
||||
|
||||
fn default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(h.session.borrow().paint.stroke_width))
|
||||
}
|
||||
|
||||
fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer {
|
||||
let w = number(arg(a, 1), "defaultStrokeWidth")?;
|
||||
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
|
||||
return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into()));
|
||||
}
|
||||
this_doc(h, a)?;
|
||||
let now = h.session.borrow().paint.stroke_width;
|
||||
set(h, now == w, json!({"weight": w}))
|
||||
}
|
||||
|
||||
fn default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_cap(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("defaultStrokeCap must be a StrokeCap value".into())) };
|
||||
let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?;
|
||||
set(h, now == cap, json!({"cap": name}))
|
||||
}
|
||||
|
||||
fn default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
|
||||
}
|
||||
|
||||
fn set_default_join(h: &Host, a: &[Data]) -> Answer {
|
||||
let found = match arg(a, 1) {
|
||||
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(&(join, _, name)) = found else { return Err(HostError::Type("defaultStrokeJoin must be a StrokeJoin value".into())) };
|
||||
let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?;
|
||||
set(h, now == join, json!({"join": name}))
|
||||
}
|
||||
|
||||
fn default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?))
|
||||
}
|
||||
|
||||
fn set_default_miter(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeMiterLimit")?;
|
||||
if !(1.0..=500.0).contains(&v) {
|
||||
return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?;
|
||||
set(h, now == v, json!({"miterLimit": v}))
|
||||
}
|
||||
|
||||
fn dashes(h: &Host, a: &[Data]) -> std::result::Result<Vec<f64>, HostError> {
|
||||
stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone()))
|
||||
}
|
||||
|
||||
fn default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect()))
|
||||
}
|
||||
|
||||
fn set_default_dashes(h: &Host, a: &[Data]) -> Answer {
|
||||
let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?;
|
||||
let now = dashes(h, a)?;
|
||||
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
|
||||
set(h, now == lengths, json!({"dash": dash}))
|
||||
}
|
||||
|
||||
fn default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?))
|
||||
}
|
||||
|
||||
fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = number(arg(a, 1), "defaultStrokeDashOffset")?;
|
||||
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
|
||||
return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into()));
|
||||
}
|
||||
if dashes(h, a)?.is_empty() && v != 0.0 {
|
||||
return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into()));
|
||||
}
|
||||
let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?;
|
||||
set(h, now == v, json!({"dashOffset": v}))
|
||||
}
|
||||
|
||||
fn scale_factor(h: &Host, a: &[Data]) -> Answer {
|
||||
this_doc(h, a)?;
|
||||
Ok(num(1.0))
|
||||
}
|
||||
|
||||
/// The `Document` members of this module.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")),
|
||||
("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")),
|
||||
("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")),
|
||||
("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")),
|
||||
("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")),
|
||||
("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")),
|
||||
(
|
||||
"defaultStrokeWidth",
|
||||
property(l, default_stroke_width, set_default_stroke_width),
|
||||
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
|
||||
),
|
||||
("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")),
|
||||
("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")),
|
||||
("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")),
|
||||
("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")),
|
||||
("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")),
|
||||
("scaleFactor", get(l, scale_factor), typed("number")),
|
||||
])
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
|
||||
//!
|
||||
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
|
||||
@@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
|
||||
}
|
||||
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most
|
||||
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
|
||||
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
|
||||
pub fn holds(root: &Path, path: &Path) -> bool {
|
||||
|
||||
@@ -37,11 +37,21 @@
|
||||
//!
|
||||
//! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of
|
||||
//! the file it is in.
|
||||
//!
|
||||
//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules
|
||||
//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing
|
||||
//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL
|
||||
//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would
|
||||
//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`],
|
||||
//! so a link that leads out of the script's folder is refused as well. Module files count against
|
||||
//! the same limits as included files, and the paths of one file (two spellings, a link, or names
|
||||
//! that differ only in letter case on Windows) give one module.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_js::{DirectiveName, Options};
|
||||
use vectorcraft_js::{DirectiveName, LoadError, Options};
|
||||
|
||||
use crate::file_access::{ScriptRead, ScriptScope};
|
||||
|
||||
@@ -219,13 +229,65 @@ pub(crate) struct Files {
|
||||
frames: Vec<Frame>,
|
||||
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
|
||||
es2015: bool,
|
||||
/// The modules a module run has read, by key ([`module_key`]): the names of the folders each
|
||||
/// is in, below the script's folder.
|
||||
module_dirs: HashMap<String, Vec<String>>,
|
||||
/// The key of each module path read, below the script's folder.
|
||||
module_paths: HashMap<String, String>,
|
||||
/// The key [`Files::module_entry`] gave the script, in a module run.
|
||||
entry_key: Option<String>,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
|
||||
/// ECMAScript 5.1 with the ExtendScript extensions.
|
||||
/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text
|
||||
/// run as ECMAScript 5.1 with the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case).
|
||||
pub(crate) fn module_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs"))
|
||||
}
|
||||
|
||||
/// What names the file at the real path `real` among a run's modules: on Unix its device and file
|
||||
/// number, so two paths to one file give one module; elsewhere its real path, which on Windows
|
||||
/// spells each name in the letter case the folder stores it in, so two spellings of one file in a
|
||||
/// folder that ignores case give one module and two files in a folder that does not stay two.
|
||||
fn module_key(real: &Path) -> String {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if let Ok(m) = std::fs::metadata(real) {
|
||||
return format!("{}:{}", m.dev(), m.ino());
|
||||
}
|
||||
}
|
||||
display(real).to_string()
|
||||
}
|
||||
|
||||
/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is
|
||||
/// not `root` or below it, or has a name that is not Unicode.
|
||||
fn names_below(root: &Path, dir: &Path) -> Option<Vec<String>> {
|
||||
dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between
|
||||
/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error.
|
||||
fn specifier_names(specifier: &str) -> Result<Vec<&str>, LoadError> {
|
||||
let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}")));
|
||||
if !(specifier.starts_with("./") || specifier.starts_with("../")) {
|
||||
return wrong("must start with './' or '../'");
|
||||
}
|
||||
if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) {
|
||||
return wrong("must not contain \\, : or control characters");
|
||||
}
|
||||
let names: Vec<&str> = specifier.split('/').collect();
|
||||
let file = names.last().copied().unwrap_or_default();
|
||||
let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default();
|
||||
if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) {
|
||||
return wrong("must name a .mjs or .js file");
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
@@ -321,9 +383,91 @@ impl Files {
|
||||
levels: 0,
|
||||
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
|
||||
es2015: es2015_script(path),
|
||||
module_dirs: HashMap::new(),
|
||||
module_paths: HashMap::new(),
|
||||
entry_key: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the run's files read ECMAScript 2015, as a module run given as text does.
|
||||
pub(crate) fn read_es2015(&mut self) {
|
||||
self.es2015 = true;
|
||||
}
|
||||
|
||||
/// The module `text`, the script's own, as a source of one file. → its key and the source.
|
||||
pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> {
|
||||
self.bytes = self.bytes.saturating_add(text.len());
|
||||
let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default();
|
||||
self.module_dirs.insert(key.clone(), Vec::new());
|
||||
self.entry_key = Some(key.clone());
|
||||
let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None }))
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or
|
||||
/// this function gave). → the module's key, with its text and source map the first time the
|
||||
/// run reads it.
|
||||
pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> {
|
||||
let names = specifier_names(specifier)?;
|
||||
let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?;
|
||||
for name in names {
|
||||
match name {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
if path.pop().is_none() {
|
||||
return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'")));
|
||||
}
|
||||
}
|
||||
name => path.push(name.to_string()),
|
||||
}
|
||||
}
|
||||
let relative = path.join("/");
|
||||
if let Some(key) = self.module_paths.get(&relative) {
|
||||
return Ok((key.clone(), None));
|
||||
}
|
||||
let root =
|
||||
self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?;
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached")));
|
||||
}
|
||||
let candidate = path.iter().fold(root.clone(), |p, name| p.join(name));
|
||||
// Another path to a module already read gives that module: the file is not read again, and
|
||||
// its text is not counted again.
|
||||
let loaded = &self.module_dirs;
|
||||
let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real)));
|
||||
let (real, bytes) = match read {
|
||||
Ok(found) => found,
|
||||
Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))),
|
||||
Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))),
|
||||
Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))),
|
||||
Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))),
|
||||
};
|
||||
let key = module_key(&real);
|
||||
let Some(bytes) = bytes else {
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
return Ok((key, None));
|
||||
};
|
||||
if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES {
|
||||
return Err(LoadError::Range("script source limit reached (32 MiB)".to_string()));
|
||||
}
|
||||
if self.files >= MAX_FILES {
|
||||
return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached")));
|
||||
}
|
||||
let text = decode(&bytes, specifier).map_err(LoadError::Other)?;
|
||||
self.bytes += bytes.len();
|
||||
self.files += 1;
|
||||
self.module_paths.insert(relative, key.clone());
|
||||
// The module's relative imports start from the folder the file is in, whichever path to it
|
||||
// was read first; the path as written stands in when that folder is not below the script's.
|
||||
path.pop();
|
||||
let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path);
|
||||
self.module_dirs.insert(key.clone(), dir);
|
||||
let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] };
|
||||
Ok((key, Some((text, map))))
|
||||
}
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
|
||||
@@ -362,12 +506,26 @@ impl Files {
|
||||
self.expand(shown, dir, text, true)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its
|
||||
/// preprocessor lines read. It becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str) -> Result<Expanded, Failure> {
|
||||
/// The folder of the module `key` ([`Files::module`] gave it), from the script's folder.
|
||||
pub(crate) fn module_dir(&self, key: &str) -> Option<PathBuf> {
|
||||
let names = self.module_dirs.get(key)?;
|
||||
let root = self.frames.first().and_then(|f| f.dir.clone())?;
|
||||
Some(names.iter().fold(root, |p, name| p.join(name)))
|
||||
}
|
||||
|
||||
/// The script's folder when the run is a module run ([`Files::module_entry`] read the script),
|
||||
/// or `None` for a script run.
|
||||
pub(crate) fn entry_module_dir(&self) -> Option<PathBuf> {
|
||||
self.module_dir(self.entry_key.as_deref()?)
|
||||
}
|
||||
|
||||
/// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder
|
||||
/// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It
|
||||
/// becomes the file being run until [`Files::end_eval`].
|
||||
pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option<PathBuf>) -> Result<Expanded, Failure> {
|
||||
let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from(""));
|
||||
let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 };
|
||||
let dir = self.frames.last().and_then(|f| f.dir.clone());
|
||||
let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone()));
|
||||
let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?;
|
||||
let shown = display(&real);
|
||||
|
||||
+163
-28
@@ -66,7 +66,8 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind,
|
||||
Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress,
|
||||
Realm, RunError, RunErrorKind,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
@@ -162,6 +163,7 @@ pub fn refused_to_scripts(id: &str) -> bool {
|
||||
"edit.undoGroup.",
|
||||
"file.recovery.",
|
||||
"stroke.widthProfile.",
|
||||
"proof.",
|
||||
];
|
||||
const IDS: &[&str] = &[
|
||||
"text.addFontFiles",
|
||||
@@ -207,6 +209,8 @@ pub(crate) struct Request {
|
||||
pub locale: String,
|
||||
/// The answers to the dialogs of a run with nobody to ask, in order.
|
||||
pub answers: Vec<DialogAnswer>,
|
||||
/// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]).
|
||||
pub module: bool,
|
||||
/// The actions `app.doScript` can play.
|
||||
pub actions: Vec<actions::Playable>,
|
||||
}
|
||||
@@ -784,6 +788,9 @@ struct Host {
|
||||
script_map: RefCell<include::SourceMap>,
|
||||
/// The same for each source `$.evalFile` gave, in order.
|
||||
eval_maps: RefCell<Vec<include::SourceMap>>,
|
||||
/// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a
|
||||
/// module's, by its index there.
|
||||
module_maps: RefCell<HashMap<usize, String>>,
|
||||
/// The file, line and column of each error `$.evalFile` raised for a file it could not run, in
|
||||
/// order: the error's mark ([`HostError::Marked`]) is its index.
|
||||
eval_failures: RefCell<Vec<(Arc<str>, u32, u32)>>,
|
||||
@@ -979,6 +986,22 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the module whose source has `tag`, when it is a module of a module run: the
|
||||
/// script itself or a module it imported (not a file `$.evalFile` gave, or code from another
|
||||
/// run).
|
||||
fn module_dir_at(&self, tag: u32) -> Option<std::path::PathBuf> {
|
||||
let script = self.script_tag.get();
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return None;
|
||||
}
|
||||
let n = tag.checked_sub(script)?;
|
||||
if n == 0 {
|
||||
return self.files.borrow().entry_module_dir();
|
||||
}
|
||||
let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?;
|
||||
self.files.borrow().module_dir(&key)
|
||||
}
|
||||
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
@@ -1152,6 +1175,8 @@ struct Job {
|
||||
name: String,
|
||||
/// The file-access scope `script.run` came in, which every slice runs in.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
/// The script has ended, and the run waits for the person's growth answer before it is kept.
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
/// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in
|
||||
@@ -1380,6 +1405,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
// Point changes that wait in the object model are written before any command runs.
|
||||
dom::flush(host)?;
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let before = dom::before_command(host, id);
|
||||
@@ -1424,6 +1451,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
dom::after_command(host, before);
|
||||
// Style objects follow only a command that is kept.
|
||||
if crossed.is_ok() {
|
||||
dom::see_points(host);
|
||||
dom::after_kept_command(host);
|
||||
} else {
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
@@ -1495,6 +1523,7 @@ pub(crate) fn retained_style_lists(s: &Session) -> usize {
|
||||
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
|
||||
/// of a crossing throws a `RangeError`.
|
||||
fn vc_document(host: &Host) -> std::result::Result<Data, HostError> {
|
||||
dom::flush(host)?;
|
||||
let s = host.session.borrow();
|
||||
let Some(st) = s.active() else { return Ok(Data::Null) };
|
||||
let ids: Vec<u64> = st.selection.objects.iter().take(1_000).map(|i| i.0).collect();
|
||||
@@ -1596,6 +1625,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
}),
|
||||
strict_writes: Rc::new(move || current(&strict).ok().and_then(|h| h.eval_strict.get())),
|
||||
site: true,
|
||||
}
|
||||
};
|
||||
let mut items = vec![
|
||||
@@ -1610,9 +1640,17 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
}
|
||||
|
||||
/// `$.evalFile(path[, timeout])`: the source of the file `path` names, relative to the file being
|
||||
/// run, with its preprocessor lines read, which the interpreter then runs. `timeout`, in
|
||||
/// milliseconds, is taken and not waited on: the file is read at once.
|
||||
fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
/// run (for a call in a module the script imported, that module's file), with its preprocessor
|
||||
/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not
|
||||
/// waited on: the file is read at once. `args` starts with the call's place, as
|
||||
/// [`HostItem::Evaluator`] gives it with `site`.
|
||||
fn eval_file(host: &Host, mut args: Vec<Data>) -> std::result::Result<Data, HostError> {
|
||||
let tag = match args.first() {
|
||||
Some(Data::Number(n)) if args.len() >= 3 => *n as u32,
|
||||
_ => vectorcraft_js::UNKNOWN_SOURCE,
|
||||
};
|
||||
args.drain(..3.min(args.len()));
|
||||
let module_dir = host.module_dir_at(tag);
|
||||
let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else {
|
||||
return Err(HostError::Type(EVAL_NO_PATH.to_string()));
|
||||
};
|
||||
@@ -1626,7 +1664,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
return Err(HostError::Type(EVAL_ARGUMENTS.to_string()));
|
||||
}
|
||||
host.charge_call(path.len() as u64 + 2)?;
|
||||
let expanded = host.files.borrow_mut().eval_file(path).map_err(|f| {
|
||||
let expanded = host.files.borrow_mut().eval_file(path, module_dir).map_err(|f| {
|
||||
let message = if f.line > 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message };
|
||||
let error = match f.kind {
|
||||
include::FailKind::Limit => HostError::Abort(message),
|
||||
@@ -1736,6 +1774,22 @@ fn explained(e: &RunError) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The module `specifier` names for the module `referrer` of the run of `host`, read through the
|
||||
/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order
|
||||
/// the modules are read, which is the order of their sources' tags.
|
||||
fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result<LoadedModule, LoadError> {
|
||||
let (key, read) = host.files.borrow_mut().module(referrer, specifier)?;
|
||||
let source = read.map(|(text, map)| {
|
||||
let mut maps = host.eval_maps.borrow_mut();
|
||||
host.module_maps.borrow_mut().insert(maps.len(), key.clone());
|
||||
maps.push(map);
|
||||
drop(maps);
|
||||
host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::<Vec<u16>>());
|
||||
text
|
||||
});
|
||||
Ok(LoadedModule { key, source })
|
||||
}
|
||||
|
||||
/// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own.
|
||||
fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
|
||||
let (kind, message) = match f.kind {
|
||||
@@ -2056,7 +2110,7 @@ impl Session {
|
||||
if h.waiting.replace(false) {
|
||||
h.continues.set(h.continues.get() + 1);
|
||||
h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects()));
|
||||
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES));
|
||||
h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes()));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2153,7 +2207,19 @@ impl Session {
|
||||
self.script_stop.clear();
|
||||
self.script_report = None;
|
||||
let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env());
|
||||
let expanded = files.expand_script(&request.source);
|
||||
if request.module {
|
||||
files.read_es2015();
|
||||
}
|
||||
// A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines;
|
||||
// `module_key` names it among the modules it imports.
|
||||
let (expanded, module_key) = if request.module {
|
||||
match files.module_entry(&request.source) {
|
||||
Ok((key, expanded)) => (Ok(expanded), Some(key)),
|
||||
Err(f) => (Err(f), None),
|
||||
}
|
||||
} else {
|
||||
(files.expand_script(&request.source), None)
|
||||
};
|
||||
let name = match &expanded {
|
||||
Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(),
|
||||
_ => request.name,
|
||||
@@ -2184,9 +2250,8 @@ impl Session {
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
|
||||
// `.js` run that names it, and keeps it as it keeps its globals.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
// code the way the script does. Its realm has `Promise`; a kept realm retains it.
|
||||
let es2015 = request.module || include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
@@ -2224,7 +2289,7 @@ impl Session {
|
||||
bytes_kept: Cell::new(0),
|
||||
bridge: Cell::new(0),
|
||||
allowance_objects: Cell::new(growth_objects()),
|
||||
allowance_bytes: Cell::new(GROWTH_BYTES),
|
||||
allowance_bytes: Cell::new(growth_bytes()),
|
||||
continues: Cell::new(0),
|
||||
waiting: Cell::new(false),
|
||||
log: RefCell::new(Vec::new()),
|
||||
@@ -2255,6 +2320,7 @@ impl Session {
|
||||
files: RefCell::new(files),
|
||||
script_map: RefCell::default(),
|
||||
eval_maps: RefCell::default(),
|
||||
module_maps: RefCell::default(),
|
||||
eval_failures: RefCell::default(),
|
||||
script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE),
|
||||
report_name: Arc::from(name.as_str()),
|
||||
@@ -2319,7 +2385,13 @@ impl Session {
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
let r = realm.start(&expanded.source);
|
||||
let r = match &module_key {
|
||||
None => realm.start(&expanded.source),
|
||||
Some(key) => {
|
||||
let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH };
|
||||
realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier))
|
||||
}
|
||||
};
|
||||
// Source that does not compile defines no code, so its map is not kept.
|
||||
if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) {
|
||||
host.script_tag.set(realm.script_tag());
|
||||
@@ -2342,7 +2414,7 @@ impl Session {
|
||||
}
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
let (run, line_name) = (host.run, host.name.clone());
|
||||
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope };
|
||||
let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false };
|
||||
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(id, job));
|
||||
self.script_key = Some(JobKey { id, run, name: line_name });
|
||||
@@ -2396,6 +2468,28 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
// A run whose script ended past its growth allowance is kept once the person lets it go on,
|
||||
// and put back when they stop it.
|
||||
if job.finished {
|
||||
if self.script_stop.is_set() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
let e =
|
||||
RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
// One more allowance may still leave the growth past it: the person is asked again
|
||||
// while they may be, and past that the run ends unkept.
|
||||
if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) {
|
||||
let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false };
|
||||
return Some(self.script_failed(job, &e));
|
||||
}
|
||||
if job.host.waiting.get() {
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
return None;
|
||||
}
|
||||
return Some(self.script_ended(job));
|
||||
}
|
||||
// A stop while a dialog waits ends the run there; the interpreter cannot go on from the call.
|
||||
if job.realm.waits() {
|
||||
let kind = LimitKind::Interrupted;
|
||||
@@ -2421,24 +2515,35 @@ impl Session {
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => {
|
||||
let n = job.host.dialogs.unused();
|
||||
let kind = LimitKind::Host;
|
||||
let message = if n == 1 {
|
||||
format!("`answers` has {n} answer the script did not use")
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }))
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => {
|
||||
let r = self.script_commit(job);
|
||||
self.trim_histories();
|
||||
Some(r)
|
||||
// The point changes written as the script ended went past the growth allowance.
|
||||
Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => {
|
||||
job.finished = true;
|
||||
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
|
||||
self.script_key = Some(key);
|
||||
None
|
||||
}
|
||||
Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the run whose script has ended: it fails when answers it was given went unused, and is
|
||||
/// kept otherwise.
|
||||
fn script_ended(&mut self, job: Job) -> Result<Value> {
|
||||
let n = job.host.dialogs.unused();
|
||||
if n > 0 {
|
||||
let kind = LimitKind::Host;
|
||||
let message = if n == 1 {
|
||||
format!("`answers` has {n} answer the script did not use")
|
||||
} else {
|
||||
format!("`answers` has {n} answers the script did not use")
|
||||
};
|
||||
return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false });
|
||||
}
|
||||
let r = self.script_commit(job);
|
||||
self.trim_histories();
|
||||
r
|
||||
}
|
||||
|
||||
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
|
||||
job.host.dialogs.stopped();
|
||||
job.host.disk.borrow_mut().picker = None;
|
||||
@@ -2758,6 +2863,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let host = &job.host;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
guard::catch_panic(|| {
|
||||
@@ -2765,7 +2871,14 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
if PANIC_IN_SLICE.with(Cell::get) {
|
||||
panic!("a slice failed");
|
||||
}
|
||||
realm.advance(SLICE_FUEL)
|
||||
// Point changes that still wait in the object model are written when the script ends. Between
|
||||
// slices the run's documents are put aside, so they can wait across slices.
|
||||
realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
if matches!(progress, Progress::Done(_)) {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
}
|
||||
Ok(progress)
|
||||
})
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
@@ -2779,6 +2892,17 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
r
|
||||
}
|
||||
|
||||
/// The error that ends a run when the point changes waiting at the end of its script cannot be
|
||||
/// written.
|
||||
fn end_flush_error(e: HostError) -> RunError {
|
||||
let message = match e {
|
||||
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m,
|
||||
HostError::Marked { error, .. } => return end_flush_error(*error),
|
||||
HostError::Wait => "a host function waited for its result where the run cannot pause".into(),
|
||||
};
|
||||
RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }
|
||||
}
|
||||
|
||||
/// Tests: removes the session's running job while the session keeps its hold on it. → whether a
|
||||
/// job was removed.
|
||||
#[cfg(test)]
|
||||
@@ -2795,6 +2919,15 @@ fn growth_objects() -> u64 {
|
||||
GROWTH_OBJECTS
|
||||
}
|
||||
|
||||
/// The bytes of new document data a run may keep before it is asked to continue or stop.
|
||||
fn growth_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) {
|
||||
return n;
|
||||
}
|
||||
GROWTH_BYTES
|
||||
}
|
||||
|
||||
/// The data a run may pass to and from commands.
|
||||
fn bridge_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
@@ -2821,6 +2954,8 @@ thread_local! {
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`].
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
|
||||
@@ -111,6 +111,7 @@ impl Session {
|
||||
plugin_dir: None,
|
||||
plugin_loads: Default::default(),
|
||||
plugin_loads_in_background: false,
|
||||
packs_seen: 0,
|
||||
scripts_dir: None,
|
||||
startup_scripts_dir: None,
|
||||
script_listing_clock: Default::default(),
|
||||
@@ -359,7 +360,7 @@ impl Session {
|
||||
/// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved
|
||||
/// document stays saved, and its undo history keeps its documents as they are. The document is
|
||||
/// left as it is when `stale` picks nothing.
|
||||
fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
|
||||
pub(crate) fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
|
||||
let Some(st) = self.docs.get_mut(index) else { return };
|
||||
if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) {
|
||||
return;
|
||||
|
||||
@@ -1093,6 +1093,44 @@ impl Session {
|
||||
self.plugin_loads_in_background = on;
|
||||
}
|
||||
|
||||
/// Lays every document out again when the installed Language packs changed since the last
|
||||
/// call (an install in the background ended, or a pack was removed), since spelling and
|
||||
/// hyphenation in their languages change → whether an install or index fetch is still running,
|
||||
/// so the app looks again. The app calls it as its frames go by.
|
||||
pub fn poll_language_packs(&mut self) -> bool {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// Busy first: an install moves the generation on before it ends, so when none is
|
||||
// running any more its change is read below.
|
||||
let busy = crate::packs::busy();
|
||||
let now = crate::packs::generation();
|
||||
if now != self.packs_seen {
|
||||
self.packs_seen = now;
|
||||
for index in 0..self.docs.len() {
|
||||
// A document in the back is measured in its own composite fonts, lent for the
|
||||
// measuring, as `measure_back_document` does: the front document's are the
|
||||
// ones registered, and one of the same name may differ.
|
||||
let back_fonts = (self.active != Some(index)).then(|| self.docs.get(index).map(|st| st.doc.composite_fonts.clone())).flatten();
|
||||
let lent = back_fonts.as_ref().map(|fonts| vectorcraft_text::FontDb::global().lend_document_composite_fonts(fonts));
|
||||
// Type in a language of its own may break its lines elsewhere now: it is
|
||||
// measured again (not an edit), so its selection box and hits follow.
|
||||
self.refresh_document_text_bounds(index, |t| t.runs.iter().any(|r| r.style.language.is_some()));
|
||||
drop(lent);
|
||||
if let Some(st) = self.docs.get_mut(index) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
busy
|
||||
}
|
||||
// The web build has no packs.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = self.packs_seen;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
|
||||
/// load's file-name order, up to the first module still loading, without waiting → whether
|
||||
/// some are still loading. A load starts once the loads before it are done. When another
|
||||
|
||||
@@ -128,6 +128,8 @@ mod outlineobject;
|
||||
pub(super) mod outlinestroke;
|
||||
mod overprint;
|
||||
mod package;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod packs;
|
||||
mod paintopacity;
|
||||
mod paintproxy;
|
||||
mod panelcmds;
|
||||
@@ -180,10 +182,13 @@ mod script_console;
|
||||
mod script_dialogs;
|
||||
mod script_dollar;
|
||||
mod script_dom;
|
||||
mod script_dom_defaults;
|
||||
mod script_dom_paths;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
@@ -5171,6 +5176,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() {
|
||||
assert!(!s.doc().unwrap().selection.contains(b));
|
||||
}
|
||||
|
||||
/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With
|
||||
/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that
|
||||
/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked
|
||||
/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are.
|
||||
#[test]
|
||||
fn corner_widgets_pick_corners_across_paths_through_the_session() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
|
||||
let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]);
|
||||
let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]});
|
||||
s.select_tool("directSelection", v).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| {
|
||||
s.execute("select.anchorsMany", &start).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.contains(a) && sel.contains(b), "both stay selected");
|
||||
(sel.partial(a).cloned(), sel.partial(b).cloned())
|
||||
};
|
||||
let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() };
|
||||
// The top-right widget of b.
|
||||
assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into())));
|
||||
// The top-right widget of a, not picked.
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None));
|
||||
let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() };
|
||||
assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_commands_reject_bad_anchors_before_modifying_geometry() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -3048,6 +3048,61 @@ fn symbol_export_type_defaults_to_movie_clip_and_round_trips() {
|
||||
assert!(s.execute("symbol.options", &json!({"name": "Renamed"})).is_err());
|
||||
}
|
||||
|
||||
/// `symbol.options` whose values are the ones the symbol already has changes neither the document
|
||||
/// nor its revision, and records no undo step.
|
||||
#[test]
|
||||
fn symbol_options_that_change_nothing_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
make_symbol(&mut s);
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.revision, st.history.undo.len())
|
||||
};
|
||||
let unchanged = [
|
||||
json!({"name": "Box", "newName": "Box"}),
|
||||
json!({"name": "Box", "newName": " Box "}),
|
||||
json!({"name": "Box", "registration": 4}),
|
||||
json!({"name": "Box", "exportType": "movieClip"}),
|
||||
json!({"name": "Box", "nineSlice": false}),
|
||||
json!({"name": "Box", "type": "static"}),
|
||||
json!({"name": "Box", "alignToPixelGrid": false}),
|
||||
json!({"name": "Box", "newName": "Box", "registration": 4, "exportType": "movieClip", "type": "static", "alignToPixelGrid": false}),
|
||||
];
|
||||
let before = state(&s);
|
||||
for p in &unchanged {
|
||||
assert_eq!(s.execute("symbol.options", p).unwrap()["name"], "Box");
|
||||
assert_eq!(state(&s), before, "{p} changes nothing");
|
||||
}
|
||||
s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "changed options are one undo step");
|
||||
let before = state(&s);
|
||||
let r = s.execute("symbol.options", &json!({"name": "Box", "registration": 0, "exportType": "graphic", "type": "dynamic"})).unwrap();
|
||||
assert_eq!((r["registration"].clone(), r["exportType"].clone(), r["type"].clone()), (json!(0), json!("graphic"), json!("dynamic")));
|
||||
assert_eq!(state(&s), before, "setting the options again changes nothing");
|
||||
s.execute("symbol.options", &json!({"name": "Box", "newName": "Logo"})).unwrap();
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
|
||||
}
|
||||
|
||||
/// `symbol.replace` with the symbol the instances already show changes neither the document nor
|
||||
/// its revision, and records no undo step.
|
||||
#[test]
|
||||
fn symbol_replace_with_the_same_symbol_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
let (inst, _, _) = make_symbol(&mut s);
|
||||
rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
s.execute("symbol.new", &json!({"name": "Small"})).unwrap();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.revision, st.history.undo.len())
|
||||
};
|
||||
let before = state(&s);
|
||||
assert_eq!(s.execute("symbol.replace", &json!({"name": "Box", "ids": [inst.0]})).unwrap()["ids"], json!([inst.0]));
|
||||
assert_eq!(state(&s), before, "replacing an instance with its own symbol changes nothing");
|
||||
s.execute("symbol.replace", &json!({"name": "Small", "ids": [inst.0]})).unwrap();
|
||||
assert!(matches!(&node(&s, inst).kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Small"));
|
||||
assert_eq!(undo_steps(&s), before.2 + 1, "replacing it with another symbol is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sprayer_command_creates_a_symbol_set_and_alt_removes() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
|
||||
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
|
||||
// The fix is the color to store: the stain mixes it half way to black again, and the result
|
||||
// just meets AA against white.
|
||||
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
|
||||
assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
|
||||
}
|
||||
|
||||
/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
|
||||
/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
|
||||
#[test]
|
||||
fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
|
||||
let mut s = picked_symbol_part();
|
||||
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
|
||||
s.active_mut().unwrap().selection.symbol_part = None;
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
|
||||
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
|
||||
assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
|
||||
assert!(e.contains("has no color"), "{e}");
|
||||
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
|
||||
}
|
||||
|
||||
fn fix_color(v: &Value) -> vectorcraft_color::Color {
|
||||
crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
|
||||
}
|
||||
|
||||
fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
|
||||
let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["for"], "normalText");
|
||||
let aa = fix_color(&r["fix"]["aa"]);
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
|
||||
assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
|
||||
assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
|
||||
// White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
|
||||
assert!(r["fix"]["aaa"].is_null(), "{r}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
|
||||
}
|
||||
|
||||
/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
|
||||
/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
|
||||
/// and the fix has to paint as #767676 (4.54:1) or darker.
|
||||
#[test]
|
||||
fn a_fix_passes_as_the_canvas_paints_it() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
|
||||
let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
|
||||
assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
|
||||
// The fix is the closest one: the gray one 8-bit step lighter fails.
|
||||
let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
|
||||
assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
|
||||
/// so the Color Wheel's contrast lines use the same color.
|
||||
#[test]
|
||||
fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
|
||||
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let mut s = Session::new();
|
||||
let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
|
||||
let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
s.prefs.black_on_screen = "rich".into();
|
||||
let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
|
||||
assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
|
||||
assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
|
||||
}
|
||||
|
||||
/// A translucent fix also meets the minimum with the color, the opacity, the background and the
|
||||
/// composited pixel rounded to 8 bits per channel.
|
||||
#[test]
|
||||
fn a_translucent_fix_passes_at_eight_bits() {
|
||||
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
|
||||
let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
|
||||
let (a, b) = (eight(opacity), eight(against));
|
||||
let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
|
||||
vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
|
||||
};
|
||||
let mut s = Session::new();
|
||||
// A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
|
||||
// 232 / 255 its pixel is #747474 (4.49:1).
|
||||
let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
|
||||
// #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
|
||||
// 4.4965:1.
|
||||
let bg = 137.51 / 255.0;
|
||||
let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
|
||||
// Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
|
||||
// at that opacity gets a fix.
|
||||
let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["graphics"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aa"].is_null(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
|
||||
assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
|
||||
let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
|
||||
assert_eq!(g["for"], "graphics");
|
||||
let fix = g["fix"].as_object().unwrap();
|
||||
assert_eq!(fix.keys().collect::<Vec<_>>(), ["aa"], "{g}");
|
||||
let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
|
||||
assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
|
||||
assert!(!large["fix"]["aaa"].is_null(), "{large}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_color_answers_a_cmyk_fix() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
|
||||
assert_eq!(r["normalText"]["aa"], false, "{r}");
|
||||
let fix = fix_color(&r["fix"]["aa"]);
|
||||
assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
|
||||
assert!(ratio(&back) >= 4.5, "{back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
|
||||
let mut s = Session::new();
|
||||
// #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
|
||||
// meets large text AA (3:1) but not AAA (4.5:1).
|
||||
let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
|
||||
let r = s.execute("color.contrast", &p).unwrap();
|
||||
assert_eq!(r["largeText"]["aa"], false, "{r}");
|
||||
assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
|
||||
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
|
||||
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
|
||||
}
|
||||
|
||||
/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
|
||||
/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
|
||||
/// as it is, on the canvas and in the answer, for each blend mode of the object.
|
||||
#[test]
|
||||
fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
|
||||
for fill in ["#808080", "#ffffff", "#2040a0"] {
|
||||
for lower in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
if lower {
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
}
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
|
||||
if lower {
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [n]})).unwrap();
|
||||
}
|
||||
let plain = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (p, drawn) = canvas_ratio(&s, &plain);
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
let isolated = s.execute("color.contrast", &json!({})).unwrap();
|
||||
let (q, _) = canvas_ratio(&s, &isolated);
|
||||
let case = format!("{blend} {fill} lower row and group: {lower}");
|
||||
assert_eq!(p, q, "the canvas draws the same: {case}");
|
||||
assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
|
||||
assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
|
||||
/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
|
||||
/// other, so the white draws over different rows and there is no one answer. A given background
|
||||
/// stands for the rows below and answers.
|
||||
#[test]
|
||||
fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let square = |s: &mut Session, x: i32, isolate: bool| {
|
||||
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
|
||||
let top = items.iter().rposition(|i| i.is_fill()).unwrap();
|
||||
let lower = items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
if isolate {
|
||||
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
|
||||
}
|
||||
n
|
||||
};
|
||||
let a = square(&mut s, 30, false);
|
||||
let b = square(&mut s, 120, true);
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
|
||||
assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("the selected objects' colors differ"), "{e}");
|
||||
s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
|
||||
// A blending row at no opacity does not show, so the isolation no longer changes the answer.
|
||||
for n in [a, b] {
|
||||
let st = s.active().unwrap();
|
||||
let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// A Difference square centered on the edge between locked black and white art: the art behind it
|
||||
/// is not one color where it is read, so no one color stands for it; a given background answers,
|
||||
/// and over one color the background is read as before.
|
||||
#[test]
|
||||
fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
// Without the default stroke, which would cover the edge.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
|
||||
let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
|
||||
assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
|
||||
// In Normal mode the color is drawn as it is, over the background read as one color.
|
||||
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
// Moved over the white art alone, the square blends with one color again.
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
|
||||
let r = s.execute("color.contrast", &json!({})).unwrap();
|
||||
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
|
||||
}
|
||||
|
||||
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
|
||||
/// edge between black and white art: the square blends only with the white inside the group, so
|
||||
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
|
||||
#[test]
|
||||
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
|
||||
let mut s = session();
|
||||
let id = |v: Value| v["id"].as_u64().unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
|
||||
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [square]})).unwrap();
|
||||
s.execute("color.contrast", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
|
||||
/// contrast lines show where a solid color in its place passes.
|
||||
#[test]
|
||||
fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
|
||||
let mut s = blended_over_red("normal");
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
|
||||
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
|
||||
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
|
||||
assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
|
||||
assert_eq!(backdrop.against_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_takes_only_the_three_categories() {
|
||||
let mut s = Session::new();
|
||||
for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
|
||||
let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
|
||||
assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -399,6 +399,73 @@ fn parse_err(s: &mut Session, p: Value) -> String {
|
||||
s.execute("color.parse", &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse`
|
||||
/// reads every notation but CMYK back to the same color and opacity.
|
||||
#[test]
|
||||
fn format_writes_each_notation_and_parse_reads_it_back() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let s = &mut s;
|
||||
let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| {
|
||||
let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap();
|
||||
r["text"].as_str().unwrap().to_string()
|
||||
};
|
||||
let blue = json!("#336699");
|
||||
for (notation, at_half, at_full) in [
|
||||
("hex", "#336699", "#336699"),
|
||||
("hexAlpha", "#33669980", "#336699ff"),
|
||||
("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"),
|
||||
("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"),
|
||||
] {
|
||||
assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}");
|
||||
assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}");
|
||||
}
|
||||
let oklch = fmt(s, blue.clone(), json!(25), "oklch");
|
||||
assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}");
|
||||
// The working CMYK numbers through the color settings, as color.convert gives them.
|
||||
let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap();
|
||||
let pct: Vec<f64> = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect();
|
||||
let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]);
|
||||
assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them");
|
||||
assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected);
|
||||
assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values");
|
||||
assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40");
|
||||
for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] {
|
||||
for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] {
|
||||
let text = fmt(s, color.clone(), opacity.clone(), notation);
|
||||
let shown = fmt(s, color.clone(), Value::Null, "hex");
|
||||
let r = s.execute("color.parse", &json!({ "text": text })).unwrap();
|
||||
assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}");
|
||||
match notation {
|
||||
"hex" => assert_eq!(r["opacity"], Value::Null, "{text}"),
|
||||
"hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"),
|
||||
_ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `color.format` refuses a missing or wrong color, opacity or notation.
|
||||
#[test]
|
||||
fn format_refuses_bad_params() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string();
|
||||
let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk";
|
||||
assert!(err(json!({"color": "#336699"})).ends_with(notation));
|
||||
assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation));
|
||||
assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation));
|
||||
assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string"));
|
||||
assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`"));
|
||||
assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`"));
|
||||
for opacity in [json!(-1), json!(101), json!("50"), json!(true)] {
|
||||
assert!(
|
||||
err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"),
|
||||
"{opacity}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assign_profile_is_stored_and_undoable() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
|
||||
@@ -1184,6 +1184,28 @@ fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
|
||||
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparency_info_reports_the_picked_object_that_transparency_set_edits() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("transparency.set", &json!({"ids": [inst.0], "opacity": 75, "blend": "screen", "isolate": true, "knockout": "on"})).unwrap();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap();
|
||||
let shown = |v: &Value| (v["ids"].clone(), v["opacity"].as_f64(), v["blend"].clone(), v["isolate"].clone(), v["knockout"].clone());
|
||||
// Without ids, the picked object's opacity and blend mode, and the instance's isolate and knockout.
|
||||
let info = s.execute("transparency.info", &json!({})).unwrap();
|
||||
assert_eq!(shown(&info), (json!([inst.0]), Some(50.0), json!("Multiply"), json!(true), json!("on")));
|
||||
let panel = s.transparency_info();
|
||||
assert_eq!((panel.opacity, panel.blend.map(vectorcraft_color::BlendMode::label)), (Some(50.0), Some("Multiply")));
|
||||
// The other object of the art draws as the symbol does.
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [0]})).unwrap();
|
||||
let info = s.execute("transparency.info", &json!({})).unwrap();
|
||||
assert_eq!(shown(&info), (json!([inst.0]), Some(100.0), json!("Normal"), json!(true), json!("on")));
|
||||
// With the instance's id, the instance itself, as transparency.set with that id edits it.
|
||||
let info = s.execute("transparency.info", &json!({"id": inst.0})).unwrap();
|
||||
assert_eq!(shown(&info), (json!([inst.0]), Some(75.0), json!("Screen"), json!(true), json!("on")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -119,15 +119,50 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts
|
||||
assert!(highlights(&s).is_empty(), "two objects selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights};
|
||||
let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get));
|
||||
let since = |b: (usize, usize)| {
|
||||
let n = made();
|
||||
(n.0 - b.0, n.1 - b.1)
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let copies: Vec<NodeId> = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect();
|
||||
sel(&mut s, &[key]);
|
||||
let before = made();
|
||||
assert_eq!(highlights(&s).len(), 39);
|
||||
assert_eq!(since(before), (40, 39), "the first preview measures each object");
|
||||
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
|
||||
let before = made();
|
||||
assert_eq!(highlights(&s).len(), 39);
|
||||
assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged");
|
||||
sel(&mut s, &[copies[0]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
|
||||
sel(&mut s, &[copies[1]]);
|
||||
s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap();
|
||||
sel(&mut s, &[copies[2]]);
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
sel(&mut s, &[key]);
|
||||
let before = made();
|
||||
let shown = highlights(&s);
|
||||
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
|
||||
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
|
||||
let moved = node(&s, copies[1]).stroke_path().unwrap();
|
||||
assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() {
|
||||
let mut s = session();
|
||||
let [a, b, ..] = squares(&mut s);
|
||||
let outline = node(&s, b).stroke_path().unwrap();
|
||||
let shown = |s: &mut Session| {
|
||||
s.overlays(ViewInfo::default())
|
||||
.iter()
|
||||
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
|
||||
s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline)))
|
||||
};
|
||||
sel(&mut s, &[a]);
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
@@ -138,6 +173,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
|
||||
assert!(shown(&mut s), "while Global Edit is on, with any tool");
|
||||
}
|
||||
|
||||
/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the
|
||||
/// revision changes when the outlines are found again.
|
||||
#[test]
|
||||
fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_tools::Overlay;
|
||||
let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> {
|
||||
s.overlays(ViewInfo::default())
|
||||
.into_iter()
|
||||
.filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None })
|
||||
.collect()
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
for i in 1..200 {
|
||||
rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0);
|
||||
}
|
||||
sel(&mut s, &[key]);
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
let first = outlines(&mut s);
|
||||
let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) };
|
||||
assert_eq!(paths.len(), 199);
|
||||
let second = outlines(&mut s);
|
||||
let [(again, same)] = &second[..] else { panic!("{}", second.len()) };
|
||||
assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy");
|
||||
assert_eq!(same, revision);
|
||||
s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
let on = outlines(&mut s);
|
||||
let [(members, started)] = &on[..] else { panic!("{}", on.len()) };
|
||||
assert_eq!(members.len(), 199);
|
||||
assert_ne!(started, revision, "outlines found again take a new revision");
|
||||
let next = outlines(&mut s);
|
||||
let [(kept, still)] = &next[..] else { panic!("{}", next.len()) };
|
||||
assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_and_appearance_options_narrow_the_match() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! The new-art template (M3.65): Stroke panel options and graphic styles chosen with nothing
|
||||
//! selected, New Art Has Basic Appearance and `paint.default`.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, Dash, LineCap, Node};
|
||||
@@ -377,3 +379,98 @@ fn fill_line_gives_a_new_line_the_current_fill() {
|
||||
assert_ne!(s.paint.fill, Paint::None);
|
||||
assert!(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "fill": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// `appearance.setNewArt` sets what the next object gets while the selection keeps its own look.
|
||||
#[test]
|
||||
fn set_new_art_changes_the_next_object_and_not_the_selection() {
|
||||
let mut s = session();
|
||||
let picked = rect(&mut s, 20.0);
|
||||
run(&mut s, "select.set", json!({"ids": [picked.0]}));
|
||||
let (look, undo, recent, active) = (node(&s, picked).appearance, undo_len(&s), s.recent_colors.clone(), s.fill_active);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"appearance.setNewArt",
|
||||
json!({"fill": {"color": "#ff0000"}, "stroke": {"none": true}, "weight": 4, "cap": "round", "dash": [3, 1], "dashOffset": 1, "fillOverprint": true}),
|
||||
);
|
||||
assert_eq!(r, json!({"changed": true}));
|
||||
assert_eq!(node(&s, picked).appearance, look, "the selected art kept its look");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![picked]);
|
||||
assert_eq!((undo_len(&s), &s.recent_colors, s.fill_active), (undo, &recent, active));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let id = rect(&mut s, 200.0);
|
||||
let ap = node(&s, id).appearance;
|
||||
let (fill, st) = (ap.fill().unwrap(), ap.stroke().unwrap());
|
||||
assert_eq!(fill.paint, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!(fill.overprint);
|
||||
assert_eq!((st.paint.clone(), st.width, st.cap), (Paint::None, 4.0, LineCap::Round));
|
||||
assert_eq!(st.dash, Some(Dash { pattern: vec![3.0, 1.0], offset: 1.0, ..Default::default() }));
|
||||
// The same values again change nothing.
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 4, "cap": "round"})), json!({"changed": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_bad_values_with_nothing_changed() {
|
||||
let mut s = session();
|
||||
let before = s.paint.clone();
|
||||
for params in [
|
||||
json!({"weight": -1}),
|
||||
json!({"weight": 1001}),
|
||||
json!({"weight": "3"}),
|
||||
json!({"miterLimit": 0.5}),
|
||||
json!({"cap": "flat"}),
|
||||
json!({"join": 2}),
|
||||
json!({"dash": [0, 0]}),
|
||||
json!({"dash": [-1]}),
|
||||
json!({"dash": "4 2"}),
|
||||
json!({"dashOffset": 2}),
|
||||
json!({"fill": "#ff0000"}),
|
||||
json!({"fill": {}}),
|
||||
json!({"fill": {"color": "#ff0000"}, "weight": -1}),
|
||||
json!({"stroke": {"tint": 50, "color": "#000000"}}),
|
||||
json!({"fillOverprint": "yes"}),
|
||||
json!({"widht": 3}),
|
||||
// A setting a paint does not take, here or nested in it, is refused too.
|
||||
json!({"fill": {"color": "#ff0000", "opacity": 25}}),
|
||||
json!({"stroke": {"none": true, "weight": 2}}),
|
||||
] {
|
||||
assert!(s.execute("appearance.setNewArt", ¶ms).is_err(), "accepted {params}");
|
||||
assert_eq!(s.paint, before, "changed new art for {params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_a_tint_on_a_pattern_without_a_swatch_entry() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 20.0);
|
||||
let name = run(&mut s, "object.pattern.make", json!({"ids": [id.0], "edit": false}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "select.none", json!({}));
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).remove_swatch(&name);
|
||||
let before = s.paint.clone();
|
||||
assert!(s.execute("appearance.setNewArt", &json!({"fill": {"swatch": name, "tint": 50}})).is_err(), "accepted a tint on {name}");
|
||||
assert_eq!(s.paint, before);
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"fill": {"swatch": name}})), json!({"changed": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_a_swatch_that_is_not_a_name() {
|
||||
let mut s = session();
|
||||
let before = s.paint.clone();
|
||||
for p in [json!({"fill": {"swatch": 7, "color": "#ff0000"}}), json!({"stroke": {"swatch": null, "color": "#ff0000"}})] {
|
||||
assert!(s.execute("appearance.setNewArt", &p).is_err(), "accepted {p}");
|
||||
assert_eq!(s.paint, before, "{p} changed new art");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_new_art_refuses_while_new_art_takes_the_selected_look() {
|
||||
let mut s = session();
|
||||
let picked = rect(&mut s, 20.0);
|
||||
run(&mut s, "appearance.setNewArtBasic", json!({"on": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [picked.0]}));
|
||||
let before = s.paint.clone();
|
||||
assert!(s.execute("appearance.setNewArt", &json!({"weight": 7})).is_err());
|
||||
assert_eq!(s.paint, before);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true}));
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, 7.0);
|
||||
}
|
||||
@@ -161,6 +161,8 @@ fn ppi_overprint_preview_and_bad_params() {
|
||||
json!({"artboardLayout": {"layout": "spiral"}}),
|
||||
json!({"artboardLayout": {"columns": 0}}),
|
||||
json!({"artboardLayout": {"rows": 0}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.4}}),
|
||||
json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1001}}),
|
||||
json!({"artboardLayout": {"tiles": 2}}),
|
||||
json!({"units": "furlongs"}),
|
||||
json!({"width": 160000, "artboards": 1000}),
|
||||
@@ -1212,3 +1214,11 @@ fn the_new_layer_takes_an_id_no_profile_art_has() {
|
||||
// Ids given out later skip the symbol's art too.
|
||||
assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_presets_rows_are_read_within_the_artboard_limit() {
|
||||
let rows = |n: u32| serde_json::from_value::<crate::cmd::newdoc::DocSettings>(json!({"rows": n})).unwrap().rows;
|
||||
assert_eq!(rows(1001), crate::cmd::newdoc::MAX_ARTBOARDS, "file.new takes the listed rows again");
|
||||
assert_eq!(rows(0), 0, "0 stays: columns in their place");
|
||||
assert_eq!(rows(12), 12, "more rows than artboards stay");
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Language packs (`proof.packs`, `proof.installPack`, `proof.removePack`, #4936): an installed pack
|
||||
//! spell-checks its language in the documents, an install needs downloads on, and a pack installed
|
||||
//! in the background reaches the documents once it ends.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::packs::{self, Backend, Cancel, Pack};
|
||||
use crate::*;
|
||||
|
||||
/// Tests that set the process-wide packs backend take turns.
|
||||
fn packs_lock() -> MutexGuard<'static, ()> {
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
LOCK.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Puts the process back to no packs and no background installs when dropped, also when the test
|
||||
/// panicked: the jobs still running are cancelled and waited for, so none outlives its test. Then
|
||||
/// it deletes the test's folder.
|
||||
struct Reset(PathBuf);
|
||||
|
||||
impl Drop for Reset {
|
||||
fn drop(&mut self) {
|
||||
while packs::busy() {
|
||||
for (locale, _, _) in packs::status().installing {
|
||||
packs::cancel(&locale);
|
||||
}
|
||||
packs::cancel("");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
packs::run_in_background(false);
|
||||
packs::set_backend(None);
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new folder for one test.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-packs-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Writes a small Dutch pack into `packs/nl`, laid out as the font store unpacks one.
|
||||
fn write_dutch_pack(packs: &Path) {
|
||||
let dir = packs.join("nl");
|
||||
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
|
||||
std::fs::write(dir.join("pack.toml"), "locale = \"nl\"\nname = \"Nederlands (test)\"\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\nTRY esianrtolducgmphbykfvwjzxq\n").unwrap();
|
||||
std::fs::write(dir.join("spelling.dic"), "5\nhet\nhuis\nen\nde\nfiets\n").unwrap();
|
||||
}
|
||||
|
||||
/// A session with a new document holding Dutch point type with one misspelt word, `fietz`.
|
||||
fn dutch_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Het huis en de fietz"})).unwrap()["id"].clone();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "language": "Dutch"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The unknown words a check lists, as (word, lang).
|
||||
fn unknown(s: &mut Session) -> Vec<(String, String)> {
|
||||
let r = s.execute("text.spelling.check", &json!({})).unwrap();
|
||||
r["words"].as_array().unwrap().iter().map(|w| (w["word"].as_str().unwrap().into(), w["lang"].as_str().unwrap().into())).collect()
|
||||
}
|
||||
|
||||
fn installed_locales(s: &mut Session) -> Vec<String> {
|
||||
let r = s.execute("proof.packs", &json!({})).unwrap();
|
||||
r["installed"].as_array().unwrap().iter().map(|p| p["locale"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pack_in_the_font_store_checks_its_language_until_it_is_removed() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("store");
|
||||
let _reset = Reset(root.clone());
|
||||
let mut s = dutch_session();
|
||||
let without = unknown(&mut s);
|
||||
// A pack another Craft app installed into the shared store.
|
||||
let store = packs::font_store_in(root.clone());
|
||||
write_dutch_pack(&store.packs_dir());
|
||||
packs::set_backend(Some(store));
|
||||
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())], "checked in Dutch by the pack");
|
||||
assert_eq!(installed_locales(&mut s), ["nl"]);
|
||||
let listed = s.execute("proof.packs", &json!({})).unwrap();
|
||||
assert_eq!((listed["available"].clone(), listed["downloads"].clone()), (json!(true), json!(false)), "downloads stay off");
|
||||
let before = s.doc().unwrap().revision;
|
||||
assert_eq!(s.execute("proof.removePack", &json!({"locale": "NL"})).unwrap()["installed"], false);
|
||||
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
|
||||
assert_eq!(unknown(&mut s), without, "checked as before the pack");
|
||||
assert!(installed_locales(&mut s).is_empty());
|
||||
assert!(s.execute("proof.removePack", &json!({"locale": "nl"})).is_err(), "no longer installed");
|
||||
}
|
||||
|
||||
/// A stand-in for the font store: it lists a Dutch pack and installs it by writing its files.
|
||||
struct Fake {
|
||||
dir: PathBuf,
|
||||
downloads: bool,
|
||||
/// While set, an install waits until it is cleared.
|
||||
hold: AtomicBool,
|
||||
}
|
||||
|
||||
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> {
|
||||
let nl = Pack {
|
||||
locale: "nl".into(),
|
||||
name: "Nederlands".into(),
|
||||
size: 2,
|
||||
licence: "MIT".into(),
|
||||
class: "Embeddable".into(),
|
||||
spelling: true,
|
||||
hyphenation: false,
|
||||
};
|
||||
vec![nl]
|
||||
}
|
||||
|
||||
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
|
||||
Ok(self.cached_index())
|
||||
}
|
||||
|
||||
fn install(&self, locale: &str, cancel: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
|
||||
progress(1, 2);
|
||||
while self.hold.load(Ordering::Relaxed) {
|
||||
if cancel.is_cancelled() {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// The index lists only Dutch, which `packs::install` checks first.
|
||||
if locale != "nl" {
|
||||
return Err(format!("asked to install {locale}"));
|
||||
}
|
||||
write_dutch_pack(&self.dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, locale: &str) -> std::result::Result<(), String> {
|
||||
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn error(s: &mut Session, id: &str, p: Value) -> String {
|
||||
s.execute(id, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_install_needs_downloads_on_and_a_pack_the_index_lists() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("fake");
|
||||
let _reset = Reset(root.clone());
|
||||
let mut s = dutch_session();
|
||||
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("aren't available"), "no store, no packs");
|
||||
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: false, hold: AtomicBool::new(false) })));
|
||||
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl"})).contains("downloading is turned off"));
|
||||
assert!(error(&mut s, "proof.packs", json!({"refresh": true})).contains("downloading is turned off"));
|
||||
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
|
||||
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
|
||||
for bad in [json!({}), json!({"locale": ""}), json!({"locale": "../nl"}), json!({"locale": 5})] {
|
||||
assert!(s.execute("proof.installPack", &bad).is_err(), "{bad} is refused");
|
||||
}
|
||||
assert!(!root.exists(), "a refused locale writes nothing");
|
||||
assert!(error(&mut s, "proof.installPack", json!({"locale": "fy"})).contains("no Language pack for fy"));
|
||||
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["fy"].is_string(), "the failure is reported");
|
||||
let before = s.doc().unwrap().revision;
|
||||
assert!(error(&mut s, "proof.installPack", json!({"locale": "nl_NL"})).contains("no Language pack for nl-nl"), "nl_NL reads as nl-nl");
|
||||
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true);
|
||||
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
|
||||
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
|
||||
let listed = s.execute("proof.packs", &json!({})).unwrap();
|
||||
assert_eq!(listed["packs"][0]["installed"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_install_in_the_background_reaches_the_documents_when_it_ends() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("background");
|
||||
let _reset = Reset(root.clone());
|
||||
let mut s = dutch_session();
|
||||
let without = unknown(&mut s);
|
||||
let fake = Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) });
|
||||
packs::set_backend(Some(fake.clone()));
|
||||
packs::run_in_background(true);
|
||||
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
|
||||
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true, "asked again, it is the same install");
|
||||
let listed = s.execute("proof.packs", &json!({})).unwrap();
|
||||
assert_eq!(listed["installing"][0]["locale"], "nl");
|
||||
assert!(error(&mut s, "proof.removePack", json!({"locale": "nl"})).contains("still installing"));
|
||||
assert_eq!(unknown(&mut s), without, "not used before it is installed");
|
||||
let before = s.doc().unwrap().revision;
|
||||
fake.hold.store(false, Ordering::Relaxed);
|
||||
while s.poll_language_packs() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
s.poll_language_packs();
|
||||
assert!(s.doc().unwrap().revision > before, "the document is laid out again");
|
||||
assert_eq!(unknown(&mut s), [("fietz".to_string(), "nl".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_background_install_installs_nothing() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("cancel");
|
||||
let _reset = Reset(root.clone());
|
||||
let mut s = dutch_session();
|
||||
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(true) })));
|
||||
packs::run_in_background(true);
|
||||
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["started"], true);
|
||||
packs::cancel("nl");
|
||||
while packs::busy() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(installed_locales(&mut s).is_empty());
|
||||
assert!(s.execute("proof.packs", &json!({})).unwrap()["errors"]["nl"].as_str().unwrap_or_default().contains("cancelled"));
|
||||
}
|
||||
|
||||
/// A caller confined to automation roots lists the packs but can't fetch, install or remove them:
|
||||
/// the store they are written into is outside its roots.
|
||||
#[test]
|
||||
fn a_confined_caller_lists_packs_but_cannot_change_them() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("confined");
|
||||
let _reset = Reset(root.clone());
|
||||
let roots_dir = folder("confined-roots");
|
||||
std::fs::create_dir_all(&roots_dir).unwrap();
|
||||
let mut s = dutch_session();
|
||||
write_dutch_pack(&root);
|
||||
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[roots_dir.as_path()], &[roots_dir.as_path()]).unwrap();
|
||||
let mut confined = |cmd: &str, p: Value| crate::file_access::confine(roots.as_ref(), || s.execute(cmd, &p)).map_err(|e| e.to_string());
|
||||
for (cmd, p) in
|
||||
[("proof.installPack", json!({"locale": "nl"})), ("proof.removePack", json!({"locale": "nl"})), ("proof.packs", json!({"refresh": true}))]
|
||||
{
|
||||
let e = confined(cmd, p).unwrap_err();
|
||||
assert!(e.contains("automation path rejected"), "{cmd}: {e}");
|
||||
}
|
||||
assert_eq!(confined("proof.packs", json!({})).unwrap()["installed"][0]["locale"], "nl", "listing is allowed");
|
||||
assert!(root.join("nl").join("pack.toml").exists(), "the pack is still there");
|
||||
let _ = std::fs::remove_dir_all(&roots_dir);
|
||||
}
|
||||
|
||||
/// A script's rollback cannot put back what an install writes into the shared font store, so a
|
||||
/// script cannot run the pack commands.
|
||||
#[test]
|
||||
fn a_script_cannot_install_a_pack() {
|
||||
let _turn = packs_lock();
|
||||
let root = folder("script");
|
||||
let _reset = Reset(root.clone());
|
||||
let mut s = dutch_session();
|
||||
packs::set_backend(Some(Arc::new(Fake { dir: root.clone(), downloads: true, hold: AtomicBool::new(false) })));
|
||||
let e = error(&mut s, "script.run", json!({"source": "vc.run('proof.installPack', {locale: 'nl'});", "name": "t.js"}));
|
||||
assert!(e.contains("a script cannot run `proof.installPack`"), "{e}");
|
||||
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");
|
||||
}
|
||||
@@ -1066,6 +1066,339 @@ fn clean_up_removes_junk() {
|
||||
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
|
||||
}
|
||||
|
||||
/// A path drawn by `d`, filled black with no stroke.
|
||||
fn filled(s: &mut Session, d: &str) -> NodeId {
|
||||
let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap());
|
||||
fill_only(s, id);
|
||||
id
|
||||
}
|
||||
|
||||
fn fill_only(s: &mut Session, id: NodeId) {
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Hairline Slivers' test art: (the slivers, the shapes with a width).
|
||||
fn sliver_art(s: &mut Session) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
// A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide
|
||||
// and tall. A long one across the page. A compound path of two slivers.
|
||||
let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z");
|
||||
let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z");
|
||||
let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z");
|
||||
let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
fill_only(s, two);
|
||||
// Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it
|
||||
// draws a line), an open path, and a compound path of a sliver and a square.
|
||||
let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z");
|
||||
let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap());
|
||||
fill_only(s, dot);
|
||||
let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let open = filled(s, "M500 10 L540 40 L500.001 10.0015");
|
||||
let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z");
|
||||
let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z");
|
||||
s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap();
|
||||
let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
fill_only(s, mixed);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(vec![triangle, long, two], vec![strip, dot, stroked, open, mixed])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() {
|
||||
let mut s = session();
|
||||
let (slivers, kept) = sliver_art(&mut s);
|
||||
// Off by default.
|
||||
assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0);
|
||||
// A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is
|
||||
// at 0 % opacity paints nothing either.
|
||||
let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z");
|
||||
let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
|
||||
let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
d.node_mut(clear).unwrap().appearance = a.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let kept = [kept, vec![unpainted, clear]].concat();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
let r = s.execute("object.path.cleanUp", &only).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left");
|
||||
for (k, id) in kept.iter().enumerate() {
|
||||
assert!(d.node(*id).is_some(), "shape {k} with a width went");
|
||||
}
|
||||
assert_eq!(r["removed"], slivers.len());
|
||||
// One undo step brings every sliver back.
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some()));
|
||||
// A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot.
|
||||
let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"});
|
||||
assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1);
|
||||
assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some());
|
||||
}
|
||||
|
||||
/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or
|
||||
/// locked slivers.
|
||||
#[test]
|
||||
fn select_hairline_slivers_selects_what_clean_up_removes() {
|
||||
let mut s = session();
|
||||
let (slivers, _) = sliver_art(&mut s);
|
||||
let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z");
|
||||
let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(hidden).unwrap().visible = false;
|
||||
d.node_mut(locked).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
|
||||
assert_eq!(r["count"], slivers.len());
|
||||
let mut selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
|
||||
selected.sort_unstable();
|
||||
let mut want = slivers.clone();
|
||||
want.sort_unstable();
|
||||
assert_eq!(selected, want);
|
||||
// Inside an isolated group, only the slivers in it are selected.
|
||||
let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z");
|
||||
let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z");
|
||||
s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// A sliver in a group is selected as Clean Up finds it.
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1);
|
||||
assert!(s.doc().unwrap().selection.objects.contains(&inner));
|
||||
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
// A template layer that was unlocked afterward.
|
||||
let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.node_mut(template).unwrap();
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = true;
|
||||
}
|
||||
n.locked = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(template).unwrap().is_template());
|
||||
s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
|
||||
assert!(!s.doc().unwrap().selection.objects.contains(&traced));
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
s.execute("object.path.cleanUp", &only).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some());
|
||||
}
|
||||
|
||||
/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint
|
||||
/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's
|
||||
/// clipping path; Clean Up's other options keep the layer's clipping path too.
|
||||
#[test]
|
||||
fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() {
|
||||
let mut s = session();
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [rough.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap();
|
||||
let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z");
|
||||
let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z");
|
||||
s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap();
|
||||
s.execute("livePaint.make", &json!({})).unwrap();
|
||||
// A group's own 5 pt stroke draws along its member.
|
||||
let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A thin part of type's glyph outlines.
|
||||
let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap();
|
||||
let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(outlines).unwrap().extras_mut().type_outlines = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
|
||||
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
|
||||
// A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects
|
||||
// removes the clipping path.
|
||||
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z");
|
||||
let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z");
|
||||
let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
|
||||
let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
|
||||
s.execute("object.path.cleanUp", &only).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went");
|
||||
// A clip group whose clipping path is a sliver.
|
||||
let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z");
|
||||
let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
// A guide drawn as a sliver, and a sliver with an effect on its stroke.
|
||||
let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z");
|
||||
let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind {
|
||||
*guide = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
|
||||
s.execute("object.path.cleanUp", &only).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(mask).is_some(), "the clip group's clipping path went");
|
||||
assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went");
|
||||
// A layer clipped by a group (as an opened file can have it): its sliver member clips too.
|
||||
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z");
|
||||
let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [bare.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.edit("t", |d, _| {
|
||||
if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind {
|
||||
*clip = true;
|
||||
let i = children.iter().position(|c| c.id == g).unwrap();
|
||||
let c = children.remove(i);
|
||||
children.insert(0, c);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
|
||||
s.execute("object.path.cleanUp", &only).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went");
|
||||
}
|
||||
|
||||
/// A sliver on a locked artboard is left alone.
|
||||
#[test]
|
||||
fn hairline_slivers_leave_art_on_a_locked_artboard_alone() {
|
||||
let mut s = session();
|
||||
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
|
||||
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
|
||||
assert!(s.doc().unwrap().doc.node(sliver).is_some());
|
||||
}
|
||||
|
||||
/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone.
|
||||
#[test]
|
||||
fn hairline_slivers_leave_art_at_zero_opacity_alone() {
|
||||
let mut s = session();
|
||||
let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
|
||||
let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z");
|
||||
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
|
||||
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z");
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(clear).unwrap().opacity = 0.0;
|
||||
d.node_mut(group).unwrap().opacity = 0.0;
|
||||
d.node_mut(seen).unwrap().opacity = 0.5;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
|
||||
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went");
|
||||
assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed");
|
||||
}
|
||||
|
||||
/// A shape too complex to measure is kept, and both commands say how many there were.
|
||||
#[test]
|
||||
fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() {
|
||||
let mut s = session();
|
||||
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
|
||||
// A closed zigzag of more anchors than one shape is measured with.
|
||||
let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1;
|
||||
let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect();
|
||||
let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z");
|
||||
s.edit("t", |d, _| {
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind {
|
||||
*path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
|
||||
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
|
||||
let r = s.execute("object.path.cleanUp", &only).unwrap();
|
||||
assert_eq!(r["removed"], 1);
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.node(sliver).is_none() && d.node(huge).is_some());
|
||||
}
|
||||
|
||||
/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the
|
||||
/// document, the selection and the undo history stay as they were.
|
||||
#[test]
|
||||
fn hairline_slivers_refuse_a_width_out_of_range() {
|
||||
let mut s = session();
|
||||
sliver_art(&mut s);
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
|
||||
};
|
||||
let before = state(&s);
|
||||
for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] {
|
||||
for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] {
|
||||
let mut p = serde_json::Map::new();
|
||||
p.insert(key.into(), w.clone());
|
||||
if cmd == "object.path.cleanUp" {
|
||||
p.insert("hairlineSlivers".into(), json!(true));
|
||||
}
|
||||
let r = s.execute(cmd, &Value::Object(p));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}");
|
||||
assert!(state(&s) == before, "{cmd} {w} changed the document");
|
||||
}
|
||||
}
|
||||
// Both ends of the range are taken.
|
||||
for w in [json!(0.001), json!(3), json!("3 pt")] {
|
||||
assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}");
|
||||
let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w});
|
||||
assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A page-sized square under a ring (a compound path with a square hole), nothing selected.
|
||||
fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let art = rect(s, 0.0, 0.0, 100.0, 100.0);
|
||||
|
||||
@@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() {
|
||||
assert!(install(&mut s, DESATURATE).get("budget").is_none());
|
||||
}
|
||||
|
||||
/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its
|
||||
/// name is escaped, so it can't reorder the message around it.
|
||||
#[test]
|
||||
fn a_heavy_filter_refusal_escapes_its_name() {
|
||||
let mut s = session();
|
||||
// The override as a JSON escape in the manifest.
|
||||
let rlo = format!("\\u{:04X}", 0x202E);
|
||||
let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap();
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string();
|
||||
assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}");
|
||||
}
|
||||
|
||||
/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed
|
||||
/// without any of its code running: its start function traps and its `vc_manifest` export loops.
|
||||
#[test]
|
||||
|
||||
@@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one
|
||||
/// undo step. They change nothing past the run's first edit or its last undone one.
|
||||
#[test]
|
||||
fn app_undo_and_redo_step_through_the_runs_edits() {
|
||||
let (mut s, a, b) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\
|
||||
app.undo(); app.redo();\
|
||||
i.name = 'first'; i.opacity = 40;\
|
||||
app.undo(); vc.log([i.name, i.opacity]);\
|
||||
app.redo(); vc.log(i.opacity);\
|
||||
app.redo(); vc.log(i.opacity);\
|
||||
app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\
|
||||
vc.log(typeof app.undo());\
|
||||
d.pageItems[1].name = 'kept';",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
let st = s.active().unwrap();
|
||||
let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect();
|
||||
assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let st = s.active().unwrap();
|
||||
assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run");
|
||||
let mut s = Session::new();
|
||||
assert!(failure(&mut s, "app.undo();").contains("No active document"));
|
||||
assert!(failure(&mut s, "app.redo();").contains("No active document"));
|
||||
}
|
||||
|
||||
/// An opacity a graph mark already has still replaces the opacity another mark of its series left on
|
||||
/// the graph, as `object.setProps` does.
|
||||
#[test]
|
||||
@@ -986,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
|
||||
let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap());
|
||||
assert_eq!(plain.grid_columns(), spaced.grid_columns());
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows must be 1 or more"), "{e}");
|
||||
assert!(e.contains("rows must be from 1 to 1000"), "{e}");
|
||||
for layout in ["gridByRow", "row", "column"] {
|
||||
let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string();
|
||||
assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}");
|
||||
@@ -1043,6 +1074,22 @@ fn an_edit_keeps_direct_selected_anchors() {
|
||||
assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
|
||||
let anchors = s.active().unwrap().selection.anchors.clone();
|
||||
assert!(anchors.contains_key(&a));
|
||||
// Lists start with the topmost object, so `b` is `pageItems[0]`.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].selected = false;");
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone()));
|
||||
log(&mut s, "app.activeDocument.pageItems[0].selected = true;");
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_keeps_the_order_of_a_mixed_selection() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1228,9 +1275,11 @@ fn a_startup_preset_alone_gives_its_first_size() {
|
||||
#[test]
|
||||
fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
let (mut s, _, _) = doc();
|
||||
for source in
|
||||
["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
|
||||
{
|
||||
for source in [
|
||||
"app.activeDocument.pageItems[0].isIsolated;",
|
||||
"app.activeDocument.pageItems[0].uuid = 'x';",
|
||||
"app.activeDocument.pageItems[0].transform(5);",
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet"));
|
||||
@@ -1412,6 +1461,16 @@ fn note_is_the_attributes_note() {
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap();
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);");
|
||||
assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]);
|
||||
let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);");
|
||||
assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_preset_applies_only_its_given_fields() {
|
||||
let mut s = Session::new();
|
||||
@@ -1446,6 +1505,17 @@ fn document_preset_applies_only_its_given_fields() {
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
}
|
||||
assert_eq!(s.documents().len(), 2, "a refused preset makes no document");
|
||||
// A saved preset with the built-in preset's name does not make the refused settings fit.
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "artboardLayout": "column"})).unwrap();
|
||||
// With the layout unset, the built-in preset puts the five 1,000,000 pt artboards in one row,
|
||||
// which does not fit, while the saved preset would put them in one column.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var p = new DocumentPreset(); p.width = 1000000; p.numArtboards = 5;\
|
||||
p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; app.documents.addDocument('Print', p);",
|
||||
);
|
||||
assert!(e.contains("don't fit"), "{e}");
|
||||
assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1632,6 +1702,29 @@ fn wrappers_go_stale_after_delete_and_undo() {
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
}
|
||||
|
||||
/// A setter on a removed item reports the stale item before it checks the value it was given.
|
||||
#[test]
|
||||
fn setters_on_a_stale_item_report_it_before_a_bad_value() {
|
||||
let (mut s, _, _) = doc();
|
||||
for set in [
|
||||
"name = {}",
|
||||
"note = {}",
|
||||
"hidden = 'x'",
|
||||
"locked = 'x'",
|
||||
"opacity = 500",
|
||||
"blendingMode = 'x'",
|
||||
"selected = 'x'",
|
||||
"position = 'x'",
|
||||
"left = 'x'",
|
||||
"top = 'x'",
|
||||
"width = -1",
|
||||
"height = -1",
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0].duplicate(); i.remove(); i.{set};"));
|
||||
assert!(e.contains("Stale page item"), "{set}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// File › Revert loads objects with the ids they were saved with: an object or a layer read before
|
||||
/// the revert does not name the loaded one.
|
||||
#[test]
|
||||
@@ -2118,7 +2211,7 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! The script object model's document defaults for new art and `scaleFactor`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::LineCap;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with one rectangle, selected.
|
||||
fn doc() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> crate::doc::Node {
|
||||
s.active().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wider_default_stroke_goes_to_the_next_path_drawn() {
|
||||
let (mut s, picked) = doc();
|
||||
let (look, steps) = (node(&s, picked).appearance, undo_steps(&s));
|
||||
let wider = s.paint.stroke_width + 1.0;
|
||||
let r = run(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth);").unwrap();
|
||||
assert_eq!(r["log"][0].as_f64(), Some(wider));
|
||||
assert_eq!(undo_steps(&s), steps, "a default alone is no undo step");
|
||||
assert_eq!(node(&s, picked).appearance, look, "the selected path kept its stroke");
|
||||
assert_eq!(s.new_art().stroke().unwrap().width, wider);
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(200, 100, 50, 50); vc.log(p.strokeWidth);");
|
||||
assert_eq!(out.iter().map(Value::as_f64).collect::<Vec<_>>(), vec![Some(wider)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_default_throws_and_changes_nothing() {
|
||||
let (mut s, _) = doc();
|
||||
let before = s.paint.clone();
|
||||
for (source, name) in [
|
||||
("app.activeDocument.defaultStrokeWidth = -1", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeWidth = 1001", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeWidth = 'wide'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeMiterLimit = 0", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeCap = 'round'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeJoin = 1", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeDashes = [0, 0]", "RangeError"),
|
||||
("app.activeDocument.defaultStrokeDashes = '4 2'", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeDashOffset = 3", "Error"),
|
||||
("app.activeDocument.defaultFillColor = 5", "TypeError"),
|
||||
("var c = new RGBColor(); c.red = 300; app.activeDocument.defaultStrokeColor = c", "RangeError"),
|
||||
("app.activeDocument.defaultFilled = 1", "TypeError"),
|
||||
("app.activeDocument.defaultStrokeOverprint = 'yes'", "TypeError"),
|
||||
] {
|
||||
let out = log(&mut s, &format!("try {{ {source}; vc.log('ran'); }} catch (e) {{ vc.log(e.name); }}"));
|
||||
assert_eq!(out, vec![json!(name)], "{source}");
|
||||
assert_eq!(s.paint, before, "{source} changed new art");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_colors_and_flags_read_back_and_paint_the_next_path() {
|
||||
let (mut s, picked) = doc();
|
||||
let look = node(&s, picked).appearance;
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, c = new RGBColor(); c.red = 255;\
|
||||
d.defaultFillColor = c; vc.log(d.defaultFillColor.typename); vc.log(d.defaultFillColor.red); vc.log(d.defaultFilled);\
|
||||
d.defaultStroked = false; vc.log(d.defaultStroked); vc.log(d.defaultStrokeColor.typename);\
|
||||
d.defaultStrokeColor = new GrayColor(); vc.log(d.defaultStroked);\
|
||||
d.defaultFillColor = new NoColor(); vc.log(d.defaultFilled); d.defaultFilled = true; vc.log(d.defaultFilled);\
|
||||
d.defaultFillColor = c;",
|
||||
);
|
||||
assert_eq!(out, vec![json!("RGBColor"), json!(255), json!(true), json!(false), json!("NoColor"), json!(true), json!(false), json!(true)]);
|
||||
assert_eq!(node(&s, picked).appearance, look);
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap());
|
||||
let ap = node(&s, id).appearance;
|
||||
assert_eq!(ap.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert!(!ap.stroke_paint().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_stroke_options_read_back_and_a_same_value_runs_no_command() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeJoin = StrokeJoin.BEVELENDJOIN;\
|
||||
d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2]; d.defaultStrokeDashOffset = 1;\
|
||||
d.defaultStrokeOverprint = true; d.defaultFillOverprint = true;\
|
||||
vc.log([d.defaultStrokeCap, d.defaultStrokeJoin, d.defaultStrokeMiterLimit, d.defaultStrokeDashes, d.defaultStrokeDashOffset,\
|
||||
d.defaultStrokeOverprint, d.defaultFillOverprint]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 2], 1, true, true])]);
|
||||
let st = s.new_art().stroke().unwrap().clone();
|
||||
assert_eq!((st.cap, st.miter_limit, st.overprint), (LineCap::Round, 7.0, true));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeMiterLimit = 7;\
|
||||
d.defaultStrokeDashes = [6, 2]; d.defaultStrokeOverprint = true; d.defaultStrokeWidth = d.defaultStrokeWidth;\
|
||||
d.defaultFillColor = d.defaultFillColor;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["slowestCommands"], json!([]), "the same values run no command");
|
||||
// `{}` and `[]` give a solid line.
|
||||
assert_eq!(log(&mut s, "var d = app.activeDocument; d.defaultStrokeDashes = {}; vc.log(d.defaultStrokeDashes.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slightly_different_number_reaches_new_art() {
|
||||
let (mut s, _) = doc();
|
||||
log(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 1; d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2];");
|
||||
log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; d.defaultStrokeWidth = 1.0000000005; d.defaultStrokeMiterLimit = 7.0000000005;\
|
||||
d.defaultStrokeDashOffset = 0.0000000005;",
|
||||
);
|
||||
let st = s.new_art().stroke().unwrap().clone();
|
||||
assert_eq!(st.width, 1.000_000_000_5);
|
||||
assert_eq!(st.miter_limit, 7.000_000_000_5);
|
||||
assert_eq!(st.dash.map(|d| d.offset), Some(0.000_000_000_5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rgb_default_in_a_cmyk_document_runs_no_command_the_second_time() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let set = "var d = app.activeDocument, c = new RGBColor(); c.red = 200; c.green = 40; c.blue = 90; d.defaultFillColor = c;";
|
||||
let first = run(&mut s, set).unwrap();
|
||||
assert_ne!(first["slowestCommands"], json!([]), "the first assignment changes new art");
|
||||
let again = run(&mut s, set).unwrap();
|
||||
assert_eq!(again["slowestCommands"], json!([]), "the same RGB value runs no command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_factor_is_one_and_read_only() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log(d.scaleFactor); d.scaleFactor = 4; vc.log(d.scaleFactor);");
|
||||
assert_eq!(out, vec![json!(1), json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_refuse_while_new_art_takes_the_selected_look() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let before = s.paint.clone();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"try { app.activeDocument.defaultStrokeWidth = 9; } catch (e) { vc.log(e.message.indexOf('New Art Has Basic Appearance') >= 0); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
assert_eq!(s.paint, before);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
|
||||
fuel: script::DEFAULT_FUEL,
|
||||
locale: "en_US".into(),
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions: Vec::new(),
|
||||
};
|
||||
s.script_start(request).unwrap();
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of
|
||||
//! specifiers and paths, the run's limits, and errors at the file they are in.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for test `name`, with a `main` folder inside it for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
base
|
||||
}
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// Runs `main/<file>` in `base`, with the text `text`.
|
||||
fn run_file(base: &Path, file: &str, text: &str) -> (Result<Value>, Session) {
|
||||
let main = base.join("main").join(file);
|
||||
write(&main, text);
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy()}));
|
||||
(r, s)
|
||||
}
|
||||
|
||||
fn run(base: &Path, text: &str) -> Result<Value> {
|
||||
run_file(base, "main.mjs", text).0
|
||||
}
|
||||
|
||||
/// The report of the run of `main/main.mjs` that failed.
|
||||
fn failed(base: &Path, text: &str) -> Value {
|
||||
let (r, s) = run_file(base, "main.mjs", text);
|
||||
assert!(r.is_err(), "the run failed: {r:?}");
|
||||
s.script_report().unwrap().clone()
|
||||
}
|
||||
|
||||
fn message(report: &Value) -> &str {
|
||||
report["message"].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_from_its_folder_and_below() {
|
||||
let base = folder("imports");
|
||||
write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';");
|
||||
write(
|
||||
&base.join("main/lib/use.mjs"),
|
||||
"import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();",
|
||||
);
|
||||
let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);";
|
||||
let r = run(&base, text).unwrap();
|
||||
// count.mjs ran once: use.mjs and the script share its binding.
|
||||
assert_eq!(r["log"], json!([[2, "lib", true, true]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_two_modules_import_each_other() {
|
||||
let base = folder("cycle");
|
||||
write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }");
|
||||
write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();");
|
||||
let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["ab", "ab"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_path_above_the_script_folder_is_refused() {
|
||||
let base = folder("above");
|
||||
write(&base.join("outside.mjs"), "export var leaked = 1;");
|
||||
let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';");
|
||||
assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}");
|
||||
// `..` names that stay inside are read by name.
|
||||
write(&base.join("main/sub/x.mjs"), "export var x = 'x';");
|
||||
let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap();
|
||||
assert_eq!(r["log"], json!(["x"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_missing_file_is_named() {
|
||||
let base = folder("missing");
|
||||
write(&base.join("main/a.mjs"), "import './nope.mjs';");
|
||||
let report = failed(&base, "import './a.mjs';");
|
||||
assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() {
|
||||
let base = folder("specifiers");
|
||||
// The specifier as the script writes it, as the error names it, and why it is refused.
|
||||
for (written, shown, why) in [
|
||||
("lib", "lib", "must start with './' or '../'"),
|
||||
("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"),
|
||||
("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"),
|
||||
("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"),
|
||||
("./C:x.mjs", "./C:x.mjs", "must not contain"),
|
||||
("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"),
|
||||
("./x.txt", "./x.txt", "must name a .mjs or .js file"),
|
||||
("./x", "./x", "must name a .mjs or .js file"),
|
||||
] {
|
||||
let report = failed(&base, &format!("import '{written}';"));
|
||||
let expected = format!("SyntaxError: module specifier '{shown}' {why}");
|
||||
assert!(message(&report).starts_with(&expected), "{written}: {report}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_errors_are_at_the_file_they_are_in() {
|
||||
let base = folder("errors");
|
||||
write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;");
|
||||
let report = failed(&base, "import { a } from './bad.mjs';");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}");
|
||||
assert_eq!(report["line"], 2);
|
||||
write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');");
|
||||
let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);");
|
||||
assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}");
|
||||
assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}");
|
||||
let report = failed(&base, "import { b } from './thrower.mjs';");
|
||||
assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_preprocessor_lines_and_scripts_differ_by_extension() {
|
||||
let base = folder("kinds");
|
||||
write(&base.join("main/lib.jsxinc"), "var included = 1;");
|
||||
// A module has no preprocessor lines.
|
||||
let report = failed(&base, "#include \"lib.jsxinc\"\n");
|
||||
assert_eq!(report["kind"], "syntax", "{report}");
|
||||
// A .js or .jsx script does not read import or export.
|
||||
for file in ["main.js", "main.jsx"] {
|
||||
let (r, s) = run_file(&base, file, "import { a } from './a.mjs';");
|
||||
assert!(r.is_err(), "{file}");
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_files_count_against_the_include_limits() {
|
||||
let base = folder("limits");
|
||||
for i in 0..70 {
|
||||
write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1));
|
||||
}
|
||||
let report = failed(&base, "import './m0.mjs';");
|
||||
assert!(message(&report).contains("limit"), "{report}");
|
||||
assert_eq!(report["log"], json!([]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_paths_of_one_file_give_one_module() {
|
||||
let base = folder("same");
|
||||
write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;");
|
||||
let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string();
|
||||
// Windows file names ignore letter case.
|
||||
if cfg!(windows) {
|
||||
text.push_str("import { v as u } from './ONCE.mjs';\n");
|
||||
}
|
||||
let r = run(&base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["ran"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere.
|
||||
/// `false` when the system does not allow it here.
|
||||
fn link_folder(target: &Path, link: &Path) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success());
|
||||
made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok()
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, link).is_ok()
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = (target, link);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_link_out_of_the_folder_is_refused() {
|
||||
let base = folder("link");
|
||||
write(&base.join("outside/x.mjs"), "export var leaked = 1;");
|
||||
if !link_folder(&base.join("outside"), &base.join("main").join("away")) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);");
|
||||
assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_listed_and_taken_by_path() {
|
||||
assert!(cmd::scripts::runs("tool.MJS"));
|
||||
let base = folder("text");
|
||||
let root = base.join("Scripts");
|
||||
write(&root.join("tool.mjs"), "export var a = 1;");
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let listed = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}]));
|
||||
// A script given as text is not a module, whatever its name.
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"}));
|
||||
assert!(r.is_err());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_is_chosen_by_the_module_param() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap();
|
||||
assert_eq!(r["log"], json!([[1, true]]));
|
||||
// A source run as a module imports no files.
|
||||
let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true}));
|
||||
assert!(r.is_err());
|
||||
assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report());
|
||||
let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"}));
|
||||
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
|
||||
// `module: false` runs a .mjs file as a script, where `export` is a syntax error.
|
||||
let base = folder("param");
|
||||
let main = base.join("main").join("main.mjs");
|
||||
write(&main, "export var a = 1;");
|
||||
let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false}));
|
||||
assert!(r.is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "syntax");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_read_again_through_another_path_is_not_counted_again() {
|
||||
let base = folder("budget");
|
||||
// 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run.
|
||||
let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024));
|
||||
write(&base.join("main/lib/big.mjs"), &big);
|
||||
let mut text = String::new();
|
||||
for i in 0..5 {
|
||||
if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) {
|
||||
eprintln!("skipped: a folder link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n"));
|
||||
}
|
||||
text.push_str("vc.log(v0 + v4);");
|
||||
let r = run(&base, &text);
|
||||
assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2])));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_imports_are_read_from_the_folder_the_file_is_in() {
|
||||
let base = folder("realdir");
|
||||
write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;");
|
||||
write(&base.join("main/real/dep.mjs"), "export const d = 'real';");
|
||||
write(&base.join("main/other/dep.mjs"), "export const d = 'other';");
|
||||
#[cfg(unix)]
|
||||
let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(windows)]
|
||||
let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok();
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let linked = false;
|
||||
if !linked {
|
||||
eprintln!("skipped: a file link can't be made here");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap();
|
||||
assert_eq!(r["log"], json!(["real"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_eval_file_reads_beside_the_module_that_calls_it() {
|
||||
let base = folder("evalfile");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');");
|
||||
let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap();
|
||||
assert_eq!(r["log"], json!([["sub", "top"]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() {
|
||||
let base = folder("evalfile-entry");
|
||||
write(&base.join("main/helper.jsx"), "'top'");
|
||||
write(&base.join("main/sub/helper.jsx"), "'sub'");
|
||||
// The file in `sub` calls the script's function while it is the file being run.
|
||||
write(&base.join("main/sub/caller.jsx"), "$.global.load()");
|
||||
let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));";
|
||||
let r = run(&base, text).unwrap();
|
||||
assert_eq!(r["log"], json!(["top"]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::cell::Cell;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES};
|
||||
use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_GROWTH_BYTES, TEST_RESULT_BYTES};
|
||||
use crate::*;
|
||||
|
||||
fn rect(x: i64) -> Value {
|
||||
@@ -1371,6 +1371,54 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() {
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() {
|
||||
// The point change waits in the object model until the script ends.
|
||||
let source = "app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, -4];";
|
||||
let mut s = two_docs();
|
||||
let start = s.documents()[1].doc.clone();
|
||||
assert_eq!(run(&mut s, source).unwrap()["ok"], true);
|
||||
let added = start.retained_bytes_each(&s.documents()[1].doc).1 as u64;
|
||||
assert!(added >= 3, "{added}");
|
||||
// The change goes past this allowance and stays within twice it.
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(Some(added * 2 / 3)));
|
||||
let run_to_the_question = |s: &mut Session| {
|
||||
s.script_frames = true;
|
||||
run(s, source).unwrap();
|
||||
for _ in 0..1_000 {
|
||||
if s.script_waiting() {
|
||||
break;
|
||||
}
|
||||
assert!(s.script_pump().is_none());
|
||||
}
|
||||
assert!(s.script_waiting());
|
||||
assert!(s.script_pump().is_none());
|
||||
assert!(s.script_running());
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
let undo = s.documents()[1].history.undo.len();
|
||||
run_to_the_question(&mut s);
|
||||
assert_eq!(state(&s), before);
|
||||
s.script_continue();
|
||||
assert!(!s.script_waiting());
|
||||
let done = s.script_pump().expect("the run ends once it may go on");
|
||||
assert_eq!(done.unwrap()["ok"], true);
|
||||
assert_eq!(s.documents()[1].history.undo.len(), undo + 1);
|
||||
assert_ne!(state(&s), before);
|
||||
|
||||
let mut s = two_docs();
|
||||
let before = state(&s);
|
||||
run_to_the_question(&mut s);
|
||||
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
|
||||
let ended = s.script_pump().expect("a stopped run ends");
|
||||
TEST_GROWTH_BYTES.with(|g| g.set(None));
|
||||
assert!(ended.is_err());
|
||||
assert_eq!(s.script_report().unwrap()["kind"], "stopped");
|
||||
assert!(!s.script_running());
|
||||
assert_eq!(state(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() {
|
||||
TEST_GROWTH.with(|g| g.set(Some(20)));
|
||||
|
||||
@@ -630,6 +630,7 @@ impl Session {
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
scale_strokes: self.prefs.scale_strokes,
|
||||
glyph_bounds: self.prefs.type_glyph_bounds,
|
||||
preview_memo: Some(&self.preview_memo),
|
||||
unit,
|
||||
@@ -1477,9 +1478,12 @@ impl Session {
|
||||
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
|
||||
// with the Selection tool, the objects it would take.
|
||||
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
|
||||
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
|
||||
for (path, color) in shown {
|
||||
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
|
||||
// One overlay per layer color, sharing the kept outlines.
|
||||
if ge_on || self.tool.id() == "selection" {
|
||||
let shown = crate::cmd::globaledit::highlights(self);
|
||||
for (color, paths) in &shown.groups {
|
||||
v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision });
|
||||
}
|
||||
}
|
||||
if let Some((cmd, p)) = deferred_preview {
|
||||
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
|
||||
|
||||
@@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
|
||||
/// behind the selection, given back, answers the same ratio.
|
||||
#[test]
|
||||
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
|
||||
let _g = settings();
|
||||
let before = cms::active_settings();
|
||||
let _g = restored_settings();
|
||||
let mut s = session();
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
|
||||
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
|
||||
@@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
|
||||
let below = s.execute("color.contrast", &json!({}));
|
||||
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
|
||||
cms::set_active(&before).unwrap();
|
||||
let given = given.unwrap();
|
||||
assert_eq!(given["against"], "#806040", "{given}");
|
||||
let (below, again) = (below.unwrap(), again.unwrap());
|
||||
@@ -1250,6 +1248,45 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() {
|
||||
assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again");
|
||||
}
|
||||
|
||||
/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS
|
||||
/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each
|
||||
/// back to the hex color `color.format` gives.
|
||||
#[test]
|
||||
fn color_format_writes_every_css_form_through_the_intent() {
|
||||
let _g = settings();
|
||||
let old = cms::active_settings();
|
||||
let mut s = session();
|
||||
let format = |s: &mut Session, color: &serde_json::Value, notation: &str| {
|
||||
s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string())
|
||||
};
|
||||
s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap();
|
||||
let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string());
|
||||
// The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent.
|
||||
let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name;
|
||||
s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap();
|
||||
let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0});
|
||||
let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8);
|
||||
let intents_differ =
|
||||
absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8);
|
||||
// Collected as results, so that a failure still restores the process-wide settings first.
|
||||
let mut read_back = vec![];
|
||||
for notation in ["hex", "rgb", "hsl", "oklch"] {
|
||||
let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string());
|
||||
let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string()));
|
||||
read_back.push((notation, text, hex));
|
||||
}
|
||||
cms::set_active(&old).unwrap();
|
||||
cms::unregister_icc(&icc);
|
||||
assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}");
|
||||
assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB");
|
||||
let hex = read_back[0].1.clone().unwrap();
|
||||
let [r, g, b] = absolute;
|
||||
assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB");
|
||||
for (notation, text, back) in read_back {
|
||||
assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in
|
||||
/// `Color Settings.json`.
|
||||
#[test]
|
||||
|
||||
@@ -995,11 +995,17 @@ fn structured_junk() {
|
||||
("addon.arrange.grid", json!({"columns": u64::MAX, "gapX": 1e6, "gapY": -1e6, "centerOnArtboard": true})),
|
||||
("addon.arrange.grid", json!({"layout": "row", "gapX": f64::MAX, "columns": -1})),
|
||||
("addon.arrange.grid", json!({"layout": "column", "gapX": -1e6})),
|
||||
("addon.arrange.offset", json!({"direction": "column", "gap": -1e6, "order": "position", "reverse": true})),
|
||||
("addon.arrange.offset", json!({"direction": "diagonal", "gap": f64::MAX, "order": 3, "reverse": "x"})),
|
||||
("addon.arrange.swap", json!({"size": true, "scaleStrokes": true})),
|
||||
("addon.arrange.replace", json!({"fit": "proportional", "keep": true})),
|
||||
("addon.arrange.replace", json!({"fit": "bounds", "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})),
|
||||
("addon.arrange.match", json!({"size": "both", "rotate": true, "stacking": true, "reference": 8, "scaleStrokes": true})),
|
||||
("addon.arrange.match", json!({"source": "bottom", "size": "width", "patterns": true})),
|
||||
("addon.arrange.match", json!({"source": "key", "rotate": true})),
|
||||
("addon.arrange.match", json!({"source": "nope", "size": 3, "rotate": "x", "reference": u64::MAX})),
|
||||
("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})),
|
||||
("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})),
|
||||
|
||||
@@ -83,15 +83,16 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"",
|
||||
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
|
||||
Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \
|
||||
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \
|
||||
PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \
|
||||
ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \
|
||||
unloadAction unloadAction=",
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
|
||||
undo unloadAction unloadAction=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -107,8 +108,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -129,6 +135,25 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||||
),
|
||||
("PathItems.", "prototype"),
|
||||
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
|
||||
("PathItem.", "prototype"),
|
||||
(
|
||||
"PathItem.prototype.",
|
||||
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
|
||||
filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \
|
||||
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
|
||||
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
|
||||
strokeWidth strokeWidth= stroked stroked= translate",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
("PathPoint.", "prototype"),
|
||||
(
|
||||
"PathPoint.prototype.",
|
||||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||||
rightDirection= selected selected= typename",
|
||||
),
|
||||
("Tags.", "prototype"),
|
||||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Tag.", "prototype"),
|
||||
@@ -150,8 +175,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed",
|
||||
),
|
||||
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
|
||||
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
|
||||
("PointType.", "CORNER SMOOTH"),
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||||
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
|
||||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
(
|
||||
"",
|
||||
@@ -282,9 +313,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("TextFrame.prototype.", "contentVariable contentVariable="),
|
||||
];
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types.
|
||||
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
|
||||
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem";
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
|
||||
/// other than `PathItem`, and the color classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
|
||||
SymbolItem cmykColor";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
|
||||
@@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() {
|
||||
let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []}));
|
||||
assert_eq!(r["started"], false);
|
||||
assert_eq!(r["ok"], false);
|
||||
assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}");
|
||||
assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+108
-3
@@ -8,12 +8,16 @@
|
||||
//! in and rebuilds the table, which has one entry per chunk.
|
||||
//!
|
||||
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
|
||||
//!
|
||||
//! The list also keeps the box round its anchors' points and handles ([`Anchors::control_bounds`])
|
||||
//! once it has been measured, until the list changes.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
use std::ops::{Index, IndexMut, RangeBounds};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use kurbo::Rect;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::path::Anchor;
|
||||
@@ -40,12 +44,49 @@ pub struct Anchors {
|
||||
ends: Vec<usize>,
|
||||
/// The number of anchors.
|
||||
len: usize,
|
||||
/// The box round every anchor's point and handles, once measured; emptied by every change.
|
||||
control: OnceLock<Rect>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`measured_control_anchors`] of this thread.
|
||||
static MEASURED_CONTROL_ANCHORS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many anchors [`Anchors::control_bounds`] has read on this thread.
|
||||
pub fn measured_control_anchors() -> u64 {
|
||||
MEASURED_CONTROL_ANCHORS.get()
|
||||
}
|
||||
|
||||
impl Anchors {
|
||||
/// An empty list.
|
||||
pub const fn new() -> Self {
|
||||
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
|
||||
Self { chunks: Vec::new(), ends: Vec::new(), len: 0, control: OnceLock::new() }
|
||||
}
|
||||
|
||||
/// The box round every anchor's point and handles, or `None` when the list is empty. The list
|
||||
/// reads its anchors for it once, and again only after it has changed.
|
||||
pub fn control_bounds(&self) -> Option<Rect> {
|
||||
if self.len == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(*self.control.get_or_init(|| {
|
||||
MEASURED_CONTROL_ANCHORS.set(MEASURED_CONTROL_ANCHORS.get().saturating_add(self.len as u64));
|
||||
let mut r: Option<Rect> = None;
|
||||
for c in &self.chunks {
|
||||
for a in c.iter() {
|
||||
for p in [a.p, a.h_in, a.h_out] {
|
||||
r = Some(r.map_or(Rect::from_points(p, p), |r| r.union_pt(p)));
|
||||
}
|
||||
}
|
||||
}
|
||||
r.unwrap_or_default()
|
||||
}))
|
||||
}
|
||||
|
||||
/// Forget the measured [`Self::control_bounds`]: every change calls it.
|
||||
fn changed(&mut self) {
|
||||
self.control.take();
|
||||
}
|
||||
|
||||
/// The number of anchors.
|
||||
@@ -85,6 +126,7 @@ impl Anchors {
|
||||
if i >= self.len {
|
||||
return None;
|
||||
}
|
||||
self.changed();
|
||||
let (c, o) = self.locate(i);
|
||||
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
|
||||
}
|
||||
@@ -101,11 +143,13 @@ impl Anchors {
|
||||
|
||||
/// The first anchor to change.
|
||||
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
|
||||
self.changed();
|
||||
Arc::make_mut(self.chunks.first_mut()?).first_mut()
|
||||
}
|
||||
|
||||
/// The last anchor to change.
|
||||
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
|
||||
self.changed();
|
||||
Arc::make_mut(self.chunks.last_mut()?).last_mut()
|
||||
}
|
||||
|
||||
@@ -118,6 +162,7 @@ impl Anchors {
|
||||
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
|
||||
/// iterator reaches it.
|
||||
pub fn iter_mut(&mut self) -> IterMut<'_> {
|
||||
self.changed();
|
||||
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
|
||||
self.chunks.iter_mut().flat_map(chunk)
|
||||
}
|
||||
@@ -177,6 +222,7 @@ impl Anchors {
|
||||
|
||||
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
|
||||
fn reindex(&mut self) {
|
||||
self.changed();
|
||||
self.chunks.retain(|c| !c.is_empty());
|
||||
self.len = self.chunks.iter().map(|c| c.len()).sum();
|
||||
let n = self.chunks.len();
|
||||
@@ -193,6 +239,7 @@ impl Anchors {
|
||||
|
||||
/// Add `a` at the end.
|
||||
pub fn push(&mut self, a: Anchor) {
|
||||
self.changed();
|
||||
match self.chunks.last_mut() {
|
||||
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
|
||||
_ => {
|
||||
@@ -210,6 +257,7 @@ impl Anchors {
|
||||
|
||||
/// Remove the last anchor.
|
||||
pub fn pop(&mut self) -> Option<Anchor> {
|
||||
self.changed();
|
||||
let last = self.chunks.last_mut()?;
|
||||
let a = Arc::make_mut(last).pop();
|
||||
if last.is_empty() {
|
||||
@@ -489,6 +537,7 @@ impl Index<usize> for Anchors {
|
||||
impl IndexMut<usize> for Anchors {
|
||||
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
|
||||
fn index_mut(&mut self, i: usize) -> &mut Anchor {
|
||||
self.changed();
|
||||
let (c, o) = self.locate(i);
|
||||
&mut Arc::make_mut(&mut self.chunks[c])[o]
|
||||
}
|
||||
@@ -501,7 +550,7 @@ impl From<Vec<Anchor>> for Anchors {
|
||||
}
|
||||
let len = v.len();
|
||||
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
|
||||
Self { chunks, ends: Vec::new(), len }
|
||||
Self { chunks, ends: Vec::new(), len, control: OnceLock::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -725,6 +774,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
assert_eq!(a.len(), v.len(), "step {step}");
|
||||
// The box kept from the step before is measured again after the edit.
|
||||
assert_eq!(a.control_bounds(), Anchors::from(v.clone()).control_bounds(), "step {step}");
|
||||
if step % 50 == 0 {
|
||||
assert_eq!(a, v, "step {step}");
|
||||
for i in 0..v.len() {
|
||||
@@ -737,6 +788,60 @@ mod tests {
|
||||
assert_eq!(a.get(v.len()), None);
|
||||
}
|
||||
|
||||
/// The box of every anchor of `v` with its handles, measured anchor by anchor.
|
||||
fn box_of(v: &[Anchor]) -> Option<Rect> {
|
||||
let mut it = v.iter().flat_map(|a| [a.p, a.h_in, a.h_out]);
|
||||
let first = it.next()?;
|
||||
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_bounds_read_the_anchors_once_until_they_change() {
|
||||
let n = 1000;
|
||||
let mut a = Anchors::from(line(n));
|
||||
let read = measured_control_anchors;
|
||||
let before = read();
|
||||
assert_eq!(a.control_bounds(), box_of(&line(n)));
|
||||
assert_eq!(read() - before, n as u64, "the first call reads every anchor");
|
||||
let copy = a.clone();
|
||||
for _ in 0..5 {
|
||||
assert_eq!(a.control_bounds(), box_of(&line(n)));
|
||||
assert_eq!(copy.control_bounds(), box_of(&line(n)));
|
||||
}
|
||||
assert_eq!(read() - before, n as u64, "later calls, and a copy's, read no anchor");
|
||||
// Every change measures again, and only the list that changed.
|
||||
let far = Point::new(-50.0, 900.0);
|
||||
type Edit = fn(&mut Anchors, Point);
|
||||
let edits: [(&str, Edit); 11] = [
|
||||
("get_mut", |a, p| a.get_mut(3).into_iter().for_each(|x| x.h_out = p)),
|
||||
("index_mut", |a, p| a[4].h_in = p),
|
||||
("first_mut", |a, p| a.first_mut().into_iter().for_each(|x| x.p = p)),
|
||||
("last_mut", |a, p| a.last_mut().into_iter().for_each(|x| x.p = p)),
|
||||
("iter_mut", |a, p| a.iter_mut().take(1).for_each(|x| x.p = p)),
|
||||
("push", |a, p| a.push(Anchor::corner(p))),
|
||||
("insert", |a, p| a.insert(1, Anchor::corner(p))),
|
||||
("pop", |a, _| {
|
||||
let _ = a.pop();
|
||||
}),
|
||||
("remove", |a, _| {
|
||||
let _ = a.try_remove(0);
|
||||
}),
|
||||
("truncate", |a, _| a.truncate(10)),
|
||||
("reverse", |a, _| a.reverse()),
|
||||
];
|
||||
for (k, (what, edit)) in edits.iter().enumerate() {
|
||||
let p = Point::new(far.x - k as f64, far.y + k as f64);
|
||||
assert!(a.control_bounds().is_some());
|
||||
edit(&mut a, p);
|
||||
let r = read();
|
||||
assert_eq!(a.control_bounds(), box_of(&a.to_vec()), "after {what}");
|
||||
assert_eq!(read() - r, a.len() as u64, "after {what}: measured again");
|
||||
}
|
||||
assert_eq!(copy.control_bounds(), box_of(&line(n)), "the copy keeps its box");
|
||||
a.clear();
|
||||
assert_eq!(a.control_bounds(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterators_skip_and_count_as_a_slice_does() {
|
||||
let v = line(1000);
|
||||
|
||||
@@ -745,11 +745,10 @@ impl PathData {
|
||||
}
|
||||
bbox
|
||||
}
|
||||
/// Bounds including control handles (used for quick culling).
|
||||
/// Bounds including control handles (used for quick culling). Each subpath keeps its own box
|
||||
/// ([`Anchors::control_bounds`]) until its anchors change.
|
||||
pub fn control_bounds(&self) -> Option<Rect> {
|
||||
let mut it = self.subpaths.iter().flat_map(|s| s.anchors.iter()).flat_map(|a| [a.p, a.h_in, a.h_out]);
|
||||
let first = it.next()?;
|
||||
Some(it.fold(Rect::from_points(first, first), |r, p| r.union_pt(p)))
|
||||
self.subpaths.iter().filter_map(|s| s.anchors.control_bounds()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
for sp in &mut self.subpaths {
|
||||
|
||||
@@ -614,8 +614,67 @@ pub struct Program {
|
||||
pub(crate) lines: crate::LineTable,
|
||||
/// It was read with [`crate::Options::es2015`].
|
||||
pub(crate) es2015: bool,
|
||||
/// What `super` and `new.target` may do at its top: nothing in a script, and in eval code
|
||||
/// what they may do in the code that calls a direct `eval` (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// The name an import takes from the module it names, or an export from a module it re-exports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportName {
|
||||
/// The export of this name (`default` for a default import).
|
||||
Name(String),
|
||||
/// The module's namespace object (`* as ns`).
|
||||
Namespace,
|
||||
}
|
||||
|
||||
/// A module a module imports or re-exports from: the specifier as written and where it stands.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleRequest {
|
||||
/// The specifier as text, with each unpaired surrogate written as U+FFFD.
|
||||
pub specifier: String,
|
||||
/// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16,
|
||||
/// ModuleRequests). It may hold an unpaired surrogate, which no host path can name.
|
||||
pub units: Vec<u16>,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImportEntry {
|
||||
/// The index of the module in [`ModuleInfo::requests`].
|
||||
pub request: usize,
|
||||
pub import: ImportName,
|
||||
/// The name bound in the importing module.
|
||||
pub local: Name,
|
||||
}
|
||||
|
||||
/// One name a module exports (ExportEntry).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ExportEntry {
|
||||
/// `export_name` is the module's own binding `local` (`*default*` for a default export of an
|
||||
/// expression or an anonymous function).
|
||||
Local { export_name: String, local: String, span: Span },
|
||||
/// `export_name` is the export `import` of the module `request` (`export { a as b } from`,
|
||||
/// `export * as ns from`, or an exported import).
|
||||
Indirect { export_name: String, request: usize, import: ImportName, span: Span },
|
||||
/// Every export of the module `request` but `default` (`export * from`).
|
||||
Star { request: usize, span: Span },
|
||||
}
|
||||
|
||||
/// What a module imports and exports, read by [`crate::parse_module`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ModuleInfo {
|
||||
/// The modules it names, each specifier once, in the order they first appear.
|
||||
pub requests: Vec<ModuleRequest>,
|
||||
pub imports: Vec<ImportEntry>,
|
||||
pub exports: Vec<ExportEntry>,
|
||||
}
|
||||
|
||||
/// The binding name of a default export that has no name of its own (ECMA-262 2015 section
|
||||
/// 15.2.3.5); no identifier can name it.
|
||||
pub const DEFAULT_BINDING: &str = "*default*";
|
||||
|
||||
impl Program {
|
||||
/// The line and column (both from 1, the column in UTF-16 code units) of a source offset.
|
||||
pub fn line_column(&self, offset: u32) -> (u32, u32) {
|
||||
|
||||
@@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
|
||||
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
|
||||
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let k = interp.to_prop_key(&arg(args, 0))?;
|
||||
let o = interp.to_object(&this)?;
|
||||
Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?))
|
||||
}
|
||||
|
||||
// ---- Function ----
|
||||
|
||||
@@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _:
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let k = interp.to_prop_key(&arg(args, 1))?;
|
||||
match interp.get_own_pk(o, &k)? {
|
||||
match interp.own_pk(o, &k)? {
|
||||
Some(p) => from_prop(interp, &p),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
@@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
let o = *o;
|
||||
for k in own_prop_keys(interp, o)? {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
@@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
let mut names = Vec::new();
|
||||
for k in interp.own_keys(o)? {
|
||||
interp.use_fuel()?;
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
if interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
names.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +453,10 @@ pub(crate) struct Code {
|
||||
/// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]),
|
||||
/// and it is not a constructor.
|
||||
pub(crate) generator: bool,
|
||||
/// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the
|
||||
/// rules of the function's body, of the code around an arrow function, or those eval code was
|
||||
/// read with (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) supers: crate::parser::SuperRules,
|
||||
}
|
||||
|
||||
/// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors.
|
||||
|
||||
+87
-27
@@ -25,6 +25,7 @@ use crate::ast::{
|
||||
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::heap::Key;
|
||||
use crate::parser::SuperRules;
|
||||
use crate::value::Str;
|
||||
use pattern::Mode;
|
||||
|
||||
@@ -97,6 +98,8 @@ struct FnCompiler<'a> {
|
||||
recursion: u32,
|
||||
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
|
||||
es2015: bool,
|
||||
/// The code is a module's ([`compile_module`]), which has no completion value.
|
||||
module: bool,
|
||||
scopes: Vec<BlockScope>,
|
||||
templates: Vec<Template>,
|
||||
uses_this: bool,
|
||||
@@ -112,6 +115,8 @@ struct FnCompiler<'a> {
|
||||
optional: Vec<(Label, u32)>,
|
||||
/// The code is a generator function's.
|
||||
generator: bool,
|
||||
/// [`Code::supers`].
|
||||
supers: SuperRules,
|
||||
}
|
||||
|
||||
/// The `var` names and function declarations a body hoists.
|
||||
@@ -153,6 +158,7 @@ impl<'a> FnCompiler<'a> {
|
||||
uses_arguments: false,
|
||||
recursion,
|
||||
es2015: false,
|
||||
module: false,
|
||||
scopes: Vec::new(),
|
||||
templates: Vec::new(),
|
||||
uses_this: false,
|
||||
@@ -162,9 +168,16 @@ impl<'a> FnCompiler<'a> {
|
||||
annex: HashSet::new(),
|
||||
optional: Vec::new(),
|
||||
generator: false,
|
||||
supers: SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Script and eval code keep the value of the last expression statement as their
|
||||
/// completion value; function and module code do not.
|
||||
fn keeps_completion(&self) -> bool {
|
||||
self.kind != CodeKind::Function && !self.module
|
||||
}
|
||||
|
||||
// ---- emitting ----
|
||||
|
||||
fn emit(&mut self, op: Op) {
|
||||
@@ -266,8 +279,10 @@ impl<'a> FnCompiler<'a> {
|
||||
let mut seen = HashSet::new();
|
||||
// The `let` and `const` names and the block functions of each statement list and loop the
|
||||
// walk enters, with the index of the one around it; the body's are first, and its
|
||||
// functions are var-scoped.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
|
||||
// functions are var-scoped. Only Annex B's block functions read them, so without
|
||||
// [`crate::Options::es2015`] none is collected.
|
||||
let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() };
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, top, HashSet::new())];
|
||||
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
|
||||
let mut add_var = |out: &mut Hoisted, k: Key| {
|
||||
if seen.insert(k.clone()) {
|
||||
@@ -302,7 +317,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Stmt::Block(list) => {
|
||||
let s = enter(self.lexical_names(list), self.block_function_names(list));
|
||||
let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope };
|
||||
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
@@ -310,7 +325,7 @@ impl<'a> FnCompiler<'a> {
|
||||
// (Annex B.3.4).
|
||||
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
|
||||
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
|
||||
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
work.push((branch, nested || inner, s));
|
||||
}
|
||||
}
|
||||
@@ -343,30 +358,38 @@ impl<'a> FnCompiler<'a> {
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::Switch { cases, .. } => {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
let s = enter(names, funcs);
|
||||
let s = if inner {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
enter(names, funcs)
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
for case in cases.iter().rev() {
|
||||
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => {
|
||||
if let Some(f) = finalizer {
|
||||
let s = enter(self.lexical_names(f), self.block_function_names(f));
|
||||
let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope };
|
||||
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
if let Some(h) = handler {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that name
|
||||
// in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
let s = enter(names, self.block_function_names(&h.body));
|
||||
let s = if inner {
|
||||
// A `var` cannot redeclare a destructured catch parameter's names
|
||||
// (ECMA-262 11th edition section B.3.5), so a block function of that
|
||||
// name in the body is not also made a `var` (section B.3.3).
|
||||
let mut names = self.lexical_names(&h.body);
|
||||
if matches!(h.param, Binding::Pattern(_)) {
|
||||
names.extend(self.bound_keys(&h.param));
|
||||
}
|
||||
enter(names, self.block_function_names(&h.body))
|
||||
} else {
|
||||
scope
|
||||
};
|
||||
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
let s = enter(self.lexical_names(block), self.block_function_names(block));
|
||||
let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope };
|
||||
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::Expr(_)
|
||||
@@ -489,7 +512,10 @@ impl<'a> FnCompiler<'a> {
|
||||
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
|
||||
for d in decls {
|
||||
match (d.init, &d.target) {
|
||||
(Some(init), Binding::Name(name)) => self.named_expr(init, &name.name)?,
|
||||
(Some(init), Binding::Name(name)) => {
|
||||
let public_name = if name.name == crate::ast::DEFAULT_BINDING { "default" } else { &name.name };
|
||||
self.named_expr(init, public_name)?;
|
||||
}
|
||||
(Some(init), Binding::Pattern(_)) => self.expr(init)?,
|
||||
(None, Binding::Name(_)) => self.emit(Op::Undefined),
|
||||
(None, Binding::Pattern(_)) => return internal("a destructuring declaration without an initializer"),
|
||||
@@ -501,7 +527,7 @@ impl<'a> FnCompiler<'a> {
|
||||
|
||||
/// Compiles a nested function and returns its index in the function table.
|
||||
fn function(&mut self, fid: FunctionId) -> CResult<u32> {
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015, self.supers)?;
|
||||
// An arrow function reads the `this`, `arguments` and `new.target` of the code around it.
|
||||
if code.arrow {
|
||||
self.uses_this |= code.uses_this;
|
||||
@@ -548,7 +574,7 @@ impl<'a> FnCompiler<'a> {
|
||||
Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Expr(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
|
||||
self.emit(if self.keeps_completion() { Op::SetCompletion } else { Op::Pop });
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Block(list) => self.block(list),
|
||||
@@ -1012,8 +1038,12 @@ impl<'a> FnCompiler<'a> {
|
||||
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
|
||||
self.statement_completion_start();
|
||||
self.expr(*discriminant)?;
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
let scope = self.list_scope(&all, true)?;
|
||||
let scope = if self.es2015 {
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
self.list_scope(&all, true)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(scope) = scope {
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
@@ -1243,7 +1273,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.bind(fin_entry);
|
||||
// In script and eval code the finally block keeps the completion value of the try or
|
||||
// catch block when it ends normally (ECMA-262 5.1 section 12.14).
|
||||
let keeps_completion = self.kind != CodeKind::Function;
|
||||
let keeps_completion = self.keeps_completion();
|
||||
if keeps_completion {
|
||||
self.emit(Op::GetCompletion);
|
||||
}
|
||||
@@ -2389,6 +2419,7 @@ impl<'a> FnCompiler<'a> {
|
||||
own_name: meta.own_name,
|
||||
method: meta.method,
|
||||
generator: self.generator,
|
||||
supers: self.supers,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -2419,12 +2450,22 @@ fn len_u32(n: usize) -> u32 {
|
||||
}
|
||||
|
||||
/// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in.
|
||||
pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in, and `outer` the
|
||||
/// [`Code::supers`] of the code around it, which an arrow function keeps.
|
||||
pub(crate) fn compile_function(
|
||||
ast: &Ast,
|
||||
fid: FunctionId,
|
||||
source: &Rc<Source>,
|
||||
recursion: u32,
|
||||
bind_name: bool,
|
||||
es2015: bool,
|
||||
outer: SuperRules,
|
||||
) -> CResult<Rc<Code>> {
|
||||
let Some(f) = ast.function(fid) else { return internal("function out of range") };
|
||||
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
|
||||
c.es2015 = es2015;
|
||||
c.generator = f.generator;
|
||||
c.supers = if f.kind == FunctionKind::Arrow { outer } else { SuperRules::function(f.home, f.kind == FunctionKind::DerivedConstructor) };
|
||||
c.at(f.span.start);
|
||||
c.enter()?;
|
||||
// A destructured parameter has a binding of its own under a name no script can write, which
|
||||
@@ -2504,7 +2545,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
class_ctor: f.is_class_constructor(),
|
||||
derived: f.kind == FunctionKind::DerivedConstructor,
|
||||
pattern_names,
|
||||
own_name: es2015.then(|| key_of(f.name.as_ref().map_or("", |n| n.name.as_str()))),
|
||||
own_name: es2015.then(|| {
|
||||
let name = f.name.as_ref().map_or("", |n| n.name.as_str());
|
||||
key_of(if f.kind == FunctionKind::Declaration && name == crate::ast::DEFAULT_BINDING { "default" } else { name })
|
||||
}),
|
||||
method: (f.home && !f.is_class_constructor())
|
||||
|| (es2015 && matches!(f.kind, FunctionKind::Method | FunctionKind::Getter | FunctionKind::Setter)),
|
||||
};
|
||||
@@ -2515,6 +2559,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0);
|
||||
c.es2015 = program.es2015;
|
||||
c.supers = program.supers;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
@@ -2523,6 +2568,21 @@ pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kin
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an
|
||||
/// environment of its own, as strict eval code does, and returns `undefined`.
|
||||
pub(crate) fn compile_module(program: &crate::Program, source: &Rc<Source>) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0);
|
||||
c.es2015 = true;
|
||||
c.module = true;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
c.emit(Op::Undefined);
|
||||
c.emit(Op::Return);
|
||||
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
|
||||
/// must be that one parenthesized function expression and nothing else. The name `anonymous` is
|
||||
/// not bound inside the function (section 15.3.2.1).
|
||||
@@ -2531,5 +2591,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc
|
||||
let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) };
|
||||
let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) };
|
||||
let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) };
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some)
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015, program.supers).map(Some)
|
||||
}
|
||||
@@ -119,8 +119,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() {
|
||||
syntax("'use strict'; { function f() {} function f() {} }");
|
||||
syntax("for (let x = 1 in {}) {}");
|
||||
syntax("if (1) let x = 1;");
|
||||
// No statement starts with `let [`, in a statement list or in the body of an `if` or a loop.
|
||||
for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] {
|
||||
syntax(&format!("var let = [1]; {body}"));
|
||||
}
|
||||
// Outside strict mode code `let` is still a name where no declaration can start.
|
||||
truth("var let = 3; let === 3");
|
||||
truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1");
|
||||
truth("var let = [2]; if (true) let\n; let.length === 1");
|
||||
// ECMAScript 5.1 reads it as a property read.
|
||||
assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0)));
|
||||
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
|
||||
// A labeled function in a block declares its name in the block.
|
||||
syntax("{ let f; label: function f() {} }");
|
||||
@@ -202,7 +210,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
|
||||
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
|
||||
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
|
||||
let restricted = realm.run("let undefined = 1;");
|
||||
assert!(restricted.is_err(), "{restricted:?}");
|
||||
assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,8 +396,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
|
||||
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
|
||||
// Deleting the property itself, not through the global environment, keeps the record
|
||||
// (ECMA-262 2015 sections 12.5.3.2 and 8.1.1.4.7).
|
||||
// Deleting the global object's property, not the variable, leaves the name declared
|
||||
// (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`).
|
||||
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let w = 4;"), "SyntaxError"));
|
||||
let after_property = realm.run("let w = 4; w");
|
||||
assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true)));
|
||||
let after_with = realm.run("let v = 4; v");
|
||||
assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}");
|
||||
assert_eq!(realm.run("(0, eval)('var u = 1'); with (this) { delete u; }"), Ok(JsValue::Bool(true)));
|
||||
assert!(is_thrown(&realm.run("let u = 5;"), "SyntaxError"));
|
||||
// Deleting a name the global object only inherits deletes no variable.
|
||||
@@ -525,6 +539,17 @@ fn arrow_functions_cannot_be_constructed() {
|
||||
truth("((a, b) => 0).length === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_arrow_functions_length_is_configurable_and_read_only() {
|
||||
truth(
|
||||
"var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \
|
||||
d.configurable && !d.writable && !d.enumerable && d.value === 1",
|
||||
);
|
||||
truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')");
|
||||
// In ECMAScript 2015 code the other functions' `length` is configurable too (section 19.2.4.1).
|
||||
truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); d.configurable && !d.writable && !d.enumerable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arrow_functions_are_syntax_errors() {
|
||||
syntax("var f = x\n=> x;");
|
||||
@@ -1639,6 +1664,56 @@ fn eval_inside_a_function_reads_its_new_target() {
|
||||
throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a method reads `super` properties of the method's home object, from an
|
||||
/// arrow function and a nested `eval` too; in a function that is not a method, at the top of a
|
||||
/// script, through an indirect `eval` and in a `Function` body it is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_method_reads_super_properties() {
|
||||
truth("class A { get x() { return 'a' + this.n; } } class B extends A { m() { this.n = 1; return eval('super.x'); } } new B().m() === 'a1'");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return (() => eval('super.f()'))(); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('eval(\"super[\\'f\\']()\")'); } } new B().m() === 3");
|
||||
truth("class A { f() { return 3; } } class B extends A { m() { return eval('() => super.f()')(); } } new B().m() === 3");
|
||||
truth("class A {} class B extends A { m() { eval('super.y = 5'); return this.y; } } new B().m() === 5");
|
||||
truth("class A { static s() { return 4; } } class B extends A { static s() { return eval('super.s()'); } } B.s() === 4");
|
||||
truth("class A { constructor() { this.t = eval('super.constructor'); } } new A().t === Object");
|
||||
truth("var o = { __proto__: { x: 2 }, m() { 'use strict'; return eval('super.x'); } }; o.m() === 2");
|
||||
throws("function F() { return eval('super.x'); } F()", "SyntaxError");
|
||||
throws("eval('super.x')", "SyntaxError");
|
||||
throws("class A { m() { return (function () { return eval('super.x'); })(); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return (0, eval)('super.x'); } } new A().m()", "SyntaxError");
|
||||
throws("class A { m() { return Function('return super.x'); } } new A().m()", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a derived class's constructor calls the superclass's constructor with
|
||||
/// `super(…)` and binds `this` once; elsewhere `super(…)` in eval code is a `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_derived_constructor_calls_super() {
|
||||
let a = "class A { constructor(v) { this.a = v; this.t = new.target; } } ";
|
||||
truth(&format!(
|
||||
"{a}class B extends A {{ constructor() {{ eval('super(1)'); this.b = 2; }} }} var b = new B(); b.a === 1 && b.b === 2 && b.t === B && b instanceof B"
|
||||
));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ var r = eval('super(1)'); this.r = r === this; }} }} new B().r"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ (() => eval('super(1)'))(); }} }} new B().a === 1"));
|
||||
truth(&format!("{a}class B extends A {{ constructor() {{ 'use strict'; eval('super(1)'); }} }} new B().a === 1"));
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ super(1); eval('super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('super(1); super(2)'); }} }} new B()"), "ReferenceError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ eval('this'); super(1); }} }} new B()"), "ReferenceError");
|
||||
throws("class A { constructor() { eval('super()'); } } new A()", "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ m() {{ eval('super()'); }} }} new B(1).m()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('super(1)'); }})(); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ (0, eval)('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws(&format!("{a}class B extends A {{ constructor() {{ Function('super(1)'); }} }} new B()"), "SyntaxError");
|
||||
throws("function F() { eval('super()'); } F()", "SyntaxError");
|
||||
throws("eval('super()')", "SyntaxError");
|
||||
}
|
||||
|
||||
/// A `Function` body reads its own `new.target`, wherever the `Function` constructor is called.
|
||||
#[test]
|
||||
fn a_function_body_reads_its_own_new_target() {
|
||||
truth("var G = Function('return new.target'); new G() === G && G() === undefined");
|
||||
truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -305,6 +305,8 @@ impl Interp {
|
||||
completion,
|
||||
boundary,
|
||||
generator: Some(generator),
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+54
-3
@@ -199,7 +199,7 @@ pub(crate) enum Func {
|
||||
Pausable { f: crate::interp::PausableFn, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, read: crate::host::ArgRead },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str> },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, strict_writes: Rc<dyn Fn() -> Option<bool>>, name: Rc<str>, site: bool },
|
||||
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
|
||||
}
|
||||
|
||||
@@ -272,6 +272,9 @@ pub(crate) enum Class {
|
||||
Xmp(Box<crate::xmp::Meta>),
|
||||
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
|
||||
XmpFile(Box<PropMap<Value>>),
|
||||
/// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the
|
||||
/// module's exports, read live from the bindings they name.
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
@@ -598,6 +601,8 @@ impl Class {
|
||||
Class::String(_) => "String",
|
||||
Class::RegExp(_) => "RegExp",
|
||||
Class::Date(_) => "Date",
|
||||
// The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1).
|
||||
Class::ModuleNamespace(_) => "Module",
|
||||
Class::UnitValue(_) => "UnitValue",
|
||||
Class::Map(_) => "Map",
|
||||
Class::Set(_) => "Set",
|
||||
@@ -644,17 +649,49 @@ pub(crate) struct Binding {
|
||||
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
|
||||
/// declares cannot take its name.
|
||||
pub(crate) lexical: bool,
|
||||
/// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5,
|
||||
/// CreateImportBinding): reading it reads the binding of that name in that environment, and
|
||||
/// writing it is a `TypeError`. `value` is unused.
|
||||
pub(crate) import: Option<(EnvId, Key)>,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// An initialized binding.
|
||||
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None }
|
||||
}
|
||||
|
||||
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
|
||||
pub(crate) fn lexical(constant: bool) -> Self {
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None }
|
||||
}
|
||||
|
||||
/// An import of the binding `name` of the environment `env`.
|
||||
pub(crate) fn import(env: EnvId, name: Key) -> Self {
|
||||
Self {
|
||||
value: Value::Undefined,
|
||||
mutable: false,
|
||||
deletable: false,
|
||||
uninitialized: false,
|
||||
constant: true,
|
||||
lexical: true,
|
||||
import: Some((env, name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in
|
||||
/// code unit order, with the environment and name of the binding it reads, or `None` for an export
|
||||
/// whose value is fixed (another module's namespace object), kept in the object's own property.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct ModuleExports {
|
||||
pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>,
|
||||
}
|
||||
|
||||
impl ModuleExports {
|
||||
/// The binding the export `name` reads, when it reads one.
|
||||
pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> {
|
||||
self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1103,6 +1140,16 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
work.push(map.env.0);
|
||||
extra = ARG_NAME_BYTES * map.names.len();
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
for (k, b) in &exports.bindings {
|
||||
strings.add_key(k);
|
||||
if let Some((env, name)) = b {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
@@ -1233,6 +1280,10 @@ fn trace_env(e: &Env, work: &mut Vec<u32>, strings: &mut StringSizes) -> usize {
|
||||
for (k, b) in bindings.iter() {
|
||||
strings.add_key(k);
|
||||
mark_value(&b.value, work, strings);
|
||||
if let Some((env, name)) = &b.import {
|
||||
work.push(env.0);
|
||||
strings.add_key(name);
|
||||
}
|
||||
}
|
||||
ENV_BYTES + PROP_BYTES * bindings.len()
|
||||
}
|
||||
|
||||
+19
-6
@@ -160,11 +160,14 @@ pub enum HostItem {
|
||||
/// that is not a string is the call's result. `end` is called when the source has run,
|
||||
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
|
||||
/// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`]
|
||||
/// for that source alone; with `None` it takes the calling code's.
|
||||
/// for that source alone; with `None` it takes the calling code's. With `site`, `source` is
|
||||
/// given the [`CallSite`] of the code that calls it first, as the three numbers its source
|
||||
/// tag, line and column, and the arguments after them.
|
||||
Evaluator {
|
||||
source: HostFunction,
|
||||
end: Rc<dyn Fn()>,
|
||||
strict_writes: Rc<dyn Fn() -> Option<bool>>,
|
||||
site: bool,
|
||||
},
|
||||
/// A read-only property that reads the interpreter's own state.
|
||||
Script(ScriptItem),
|
||||
@@ -311,6 +314,8 @@ impl Interp {
|
||||
out
|
||||
}
|
||||
|
||||
/// The [`crate::host_ref`] of the object of a host class `id`, its key, class name and handle
|
||||
/// charged to `r` as the plain data they are before they are copied.
|
||||
fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult<Data> {
|
||||
let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) };
|
||||
self.charge_entries(r, len.saturating_add(2))?;
|
||||
@@ -466,7 +471,8 @@ impl Interp {
|
||||
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
|
||||
/// value. A result that is not a string is given to the script as it is. `end` is called once
|
||||
/// the source has run, normally or not. `strict_writes` gives the source's
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's.
|
||||
/// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`,
|
||||
/// `f` is given the calling code's [`CallSite`] before the arguments.
|
||||
pub(crate) fn call_evaluator(
|
||||
&mut self,
|
||||
f: &crate::heap::DataFn,
|
||||
@@ -474,8 +480,13 @@ impl Interp {
|
||||
strict_writes: &Rc<dyn Fn() -> Option<bool>>,
|
||||
name: &Rc<str>,
|
||||
args: &[Value],
|
||||
site: bool,
|
||||
) -> JsResult<Value> {
|
||||
let data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
let caller = site.then(|| self.call_site());
|
||||
let mut data = self.read_args(name, None, args, &ArgRead::Data)?;
|
||||
if let Some(caller) = caller {
|
||||
data.splice(0..0, site_data(caller));
|
||||
}
|
||||
let source = match f(data) {
|
||||
Ok(Data::String(source)) => source,
|
||||
Ok(d) => return self.write_data(d, 0, false),
|
||||
@@ -517,7 +528,9 @@ impl Interp {
|
||||
r
|
||||
}
|
||||
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first.
|
||||
/// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the
|
||||
/// first is the object `this` stands for, or `undefined` when it is not an object of a host
|
||||
/// class, charged to the same limits as the arguments.
|
||||
fn read_args(&mut self, name: &Rc<str>, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading {
|
||||
limits: match how {
|
||||
@@ -689,9 +702,9 @@ impl Interp {
|
||||
HostItem::Converted(list, f) => {
|
||||
Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::Evaluator { source, end, strict_writes } => {
|
||||
HostItem::Evaluator { source, end, strict_writes, site } => {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into() };
|
||||
let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site };
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto)));
|
||||
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
|
||||
}
|
||||
|
||||
@@ -270,6 +270,8 @@ impl Interp {
|
||||
Ok(Some(host_ref(&name, &h.handle)))
|
||||
}
|
||||
|
||||
/// The length of the class name and of the handle of the object of a host class `id`, or `None`
|
||||
/// when it is not one.
|
||||
pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult<Option<(usize, usize)>> {
|
||||
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
|
||||
let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?;
|
||||
|
||||
@@ -433,7 +433,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
Ok(Data::Number(f64::from(s.line)))
|
||||
});
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
|
||||
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
|
||||
let first = r.script_tag();
|
||||
@@ -455,6 +455,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
|
||||
}
|
||||
|
||||
/// An evaluator made with `site` is given the place of the code that calls it before its
|
||||
/// arguments; one made without it is given only the arguments.
|
||||
#[test]
|
||||
fn an_evaluator_with_site_is_told_where_it_is_called() {
|
||||
let mut r = realm(10_000_000);
|
||||
let given: Rc<RefCell<Vec<Vec<Data>>>> = Rc::default();
|
||||
let evaluator = |site: bool| {
|
||||
let log = given.clone();
|
||||
let source: HostFunction = Rc::new(move |a| {
|
||||
log.borrow_mut().push(a);
|
||||
Ok(Data::String("1".into()))
|
||||
});
|
||||
HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site }
|
||||
};
|
||||
r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap();
|
||||
r.run("\n\n host.at('x');\nhost.plain('y');").unwrap();
|
||||
let tag = f64::from(r.script_tag());
|
||||
let given = given.borrow();
|
||||
assert_eq!(given.len(), 2, "{given:?}");
|
||||
assert_eq!(given[0].len(), 4, "{given:?}");
|
||||
assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}");
|
||||
assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}");
|
||||
assert_eq!(given[1], vec![Data::String("y".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -849,6 +874,40 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
|
||||
}
|
||||
|
||||
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
|
||||
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
|
||||
/// with the handle `[0]`.
|
||||
fn with_long_things(r: &mut Realm, len: usize) {
|
||||
let make: HostFunction = Rc::new(move |a| {
|
||||
let mut handle = vec![if let Some(Data::Number(n)) = a.get(1) { *n } else { 0.0 }];
|
||||
handle.resize(len, 0.0);
|
||||
Ok(host_ref("Thing", &handle))
|
||||
});
|
||||
let take: HostFunction = Rc::new(|_| Ok(Data::Undefined));
|
||||
let members = vec![("make".to_string(), HostMember::Method(make)), ("take".to_string(), HostMember::Method(take))];
|
||||
let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
|
||||
r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() {
|
||||
let mut r = realm(100_000_000);
|
||||
with_long_things(&mut r, 1024);
|
||||
// 100 references to an object with a handle of 1,024 numbers are more than 100,000 entries.
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 100_000 });
|
||||
let probe = "var t = thing.make(1), list = []; for (var i = 0; i < 100; i++) list.push(t); var m = 'none'; \
|
||||
try { thing.take(list); } catch (e) { m = e.name + '|' + e.message; } m";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
|
||||
// The object a member is called on counts too.
|
||||
r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 });
|
||||
let probe = "var m = 'none'; try { thing.make(2).take(); } catch (e) { m = e.name + '|' + e.message; } m";
|
||||
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}");
|
||||
// Short handles stay within the limits.
|
||||
assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_constructor_called_with_new_cannot_wait() {
|
||||
let mut r = realm(1_000_000);
|
||||
@@ -978,7 +1037,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() {
|
||||
fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
r.run("function late() { throw new Error('late'); }").unwrap();
|
||||
assert!(r.run("host.load()").is_err());
|
||||
@@ -1000,7 +1059,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
let s = seen.clone();
|
||||
r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units)));
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap();
|
||||
assert_eq!(out, JsValue::Number(49.0));
|
||||
@@ -1015,7 +1074,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() {
|
||||
fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() {
|
||||
let mut r = realm(10_000_000);
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
r.define_host_object("host", vec![("load".into(), load)]).unwrap();
|
||||
assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet");
|
||||
r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap();
|
||||
@@ -1048,7 +1107,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() {
|
||||
let ends = Rc::new(Cell::new(0));
|
||||
let ended = ends.clone();
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(10_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
let e = r.run("host.evaluate()").unwrap_err();
|
||||
@@ -1069,7 +1128,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() {
|
||||
// The source does not parse, so a parse would throw a syntax error instead.
|
||||
let n = (1 << 17) + 1;
|
||||
let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1)))));
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false };
|
||||
let mut r = realm(1_000_000);
|
||||
r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap();
|
||||
r.interp().collect_for_room();
|
||||
|
||||
+307
-27
@@ -26,9 +26,10 @@ use crate::ast::BinaryOp;
|
||||
use crate::bytecode::{Code, CodeKind, NamePrefix, Op, Source};
|
||||
use crate::compiler::{CompileFail, compile_program};
|
||||
use crate::heap::{
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId,
|
||||
Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES,
|
||||
OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes,
|
||||
};
|
||||
use crate::parser::SuperRules;
|
||||
use crate::string_builtins::flat_charged;
|
||||
use crate::symbol::PropKey;
|
||||
use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32};
|
||||
@@ -230,6 +231,11 @@ pub(crate) struct Frame {
|
||||
pub(crate) boundary: bool,
|
||||
/// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it.
|
||||
pub(crate) generator: Option<ObjId>,
|
||||
/// The frame runs a module that another module of the same run waits under (ECMA-262 2015
|
||||
/// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception
|
||||
/// that leaves it ends the run at the boundary frame without stopping in the frames between.
|
||||
pub(crate) chained: bool,
|
||||
pub(crate) pending_module: bool,
|
||||
}
|
||||
|
||||
/// Where the exception being thrown was raised: the code and the instruction.
|
||||
@@ -274,6 +280,7 @@ pub(crate) struct Interp {
|
||||
pub(crate) heap: Heap,
|
||||
pub(crate) stack: Vec<Value>,
|
||||
pub(crate) frames: Vec<Frame>,
|
||||
pending_module_frames: usize,
|
||||
/// Values native code holds while it may run JavaScript.
|
||||
pub(crate) temp_roots: Vec<Value>,
|
||||
/// Environments native code is still building.
|
||||
@@ -636,6 +643,7 @@ impl Interp {
|
||||
heap,
|
||||
stack: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
pending_module_frames: 0,
|
||||
temp_roots: Vec::new(),
|
||||
temp_envs: Vec::new(),
|
||||
temp_codes: Vec::new(),
|
||||
@@ -1031,7 +1039,11 @@ impl Interp {
|
||||
self.push(v)?;
|
||||
return Ok(None);
|
||||
}
|
||||
if self.frames.last().is_some_and(|frame| frame.pending_module) {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
let frame = self.frame_mut()?;
|
||||
frame.pending_module = false;
|
||||
let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") };
|
||||
frame.pc += 1;
|
||||
match op {
|
||||
@@ -1100,10 +1112,14 @@ impl Interp {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) };
|
||||
let Some(frame) = self.pop_frame() else { return Err(Abrupt::Throw(v)) };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
if frame.chained {
|
||||
// The modules under it have not started, so no handler of theirs takes it.
|
||||
self.abort_to_boundary();
|
||||
}
|
||||
if frame.boundary || frame.chained {
|
||||
self.passing = v.clone();
|
||||
return Err(Abrupt::Throw(v));
|
||||
}
|
||||
@@ -1113,11 +1129,24 @@ impl Interp {
|
||||
/// Each running frame of script code, outermost first: its code, the index of its next
|
||||
/// instruction, and whether it runs a function (not global or eval code).
|
||||
pub(crate) fn script_frames(&self) -> impl Iterator<Item = (&Rc<Code>, usize, bool)> {
|
||||
self.frames.iter().map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
self.frames.iter().filter(|f| !f.pending_module).map(|f| (&f.code, f.pc, f.callee.is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn clear_frames(&mut self) {
|
||||
self.frames.clear();
|
||||
self.pending_module_frames = 0;
|
||||
}
|
||||
|
||||
fn pop_frame(&mut self) -> Option<Frame> {
|
||||
let frame = self.frames.pop()?;
|
||||
if frame.pending_module {
|
||||
self.pending_module_frames -= 1;
|
||||
}
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
fn abort_to_boundary(&mut self) {
|
||||
while let Some(frame) = self.frames.pop() {
|
||||
while let Some(frame) = self.pop_frame() {
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
if frame.boundary {
|
||||
@@ -1147,7 +1176,7 @@ impl Interp {
|
||||
Some(_) => crate::builtins::iterator::iter_result(self, v, true)?,
|
||||
None => v,
|
||||
};
|
||||
let Some(frame) = self.frames.pop() else { return internal("return without a frame") };
|
||||
let Some(frame) = self.pop_frame() else { return internal("return without a frame") };
|
||||
self.stack.truncate(frame.base);
|
||||
self.end_generator(frame.generator);
|
||||
// A `return` in a finally block leaves the block, and the value takes its exception's slot.
|
||||
@@ -1159,6 +1188,9 @@ impl Interp {
|
||||
if frame.boundary {
|
||||
return Ok(Some(v));
|
||||
}
|
||||
if frame.chained {
|
||||
return Ok(None);
|
||||
}
|
||||
self.push(v)?;
|
||||
Ok(None)
|
||||
}
|
||||
@@ -1489,6 +1521,15 @@ impl Interp {
|
||||
matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized))
|
||||
}
|
||||
|
||||
/// The binding the binding `name` of the declarative environment `env` imports, when it is a
|
||||
/// module's import.
|
||||
fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> {
|
||||
match self.heap.env(env) {
|
||||
Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn not_initialized(&mut self, name: &[u16]) -> Abrupt {
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized"))
|
||||
@@ -1501,6 +1542,14 @@ impl Interp {
|
||||
|
||||
/// GetValue of a reference whose base was resolved earlier (section 8.7.1).
|
||||
fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> {
|
||||
if let Resolved::Decl(e) = r
|
||||
&& let Some((target, target_name)) = self.import_of(e, name)
|
||||
{
|
||||
if self.uninitialized(target, &target_name) {
|
||||
return Err(self.not_initialized(name));
|
||||
}
|
||||
return Ok((self.binding_value(target, &target_name)?, Value::Undefined));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)),
|
||||
@@ -1520,6 +1569,12 @@ impl Interp {
|
||||
/// PutValue of a reference whose base was resolved earlier (section 8.7.2).
|
||||
fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> {
|
||||
let strict = self.strict();
|
||||
if let Resolved::Decl(e) = r
|
||||
&& self.import_of(e, name).is_some()
|
||||
{
|
||||
let ident = String::from_utf16_lossy(name);
|
||||
return Err(self.type_error(&format!("assignment to the import '{ident}'")));
|
||||
}
|
||||
match r {
|
||||
Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)),
|
||||
Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => {
|
||||
@@ -1725,18 +1780,59 @@ impl Interp {
|
||||
return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN }));
|
||||
}
|
||||
}
|
||||
Class::ModuleNamespace(exports) => {
|
||||
if let Some((env, name)) = exports.binding(k)
|
||||
&& let Some(Prop::Data { flags, .. }) = o.props.get(k)
|
||||
{
|
||||
return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags }));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(o.props.get(k).cloned())
|
||||
}
|
||||
|
||||
/// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like):
|
||||
/// [`Self::get_own_property`], except that an export of a module namespace object read before
|
||||
/// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5).
|
||||
pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
self.check_namespace_export(id, k)?;
|
||||
self.get_own_property(id, k)
|
||||
}
|
||||
|
||||
/// [`Self::own_property`] for a name or a Symbol: [`Self::get_own_pk`], with the same
|
||||
/// `ReferenceError` for a namespace export read before its module initialized it.
|
||||
pub(crate) fn own_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
if let PropKey::Str(name) = k {
|
||||
self.check_namespace_export(id, name)?;
|
||||
}
|
||||
self.get_own_pk(id, k)
|
||||
}
|
||||
|
||||
/// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module
|
||||
/// has not initialized yet.
|
||||
fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> {
|
||||
if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class)
|
||||
&& let Some((env, name)) = exports.binding(k)
|
||||
&& self.uninitialized(*env, name)
|
||||
{
|
||||
return Err(self.not_initialized(k));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [[GetProperty]]: the property found on the object or its prototype chain.
|
||||
pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult<Option<Prop>> {
|
||||
Ok(self.find_property_on(id, k)?.map(|(_, p)| p))
|
||||
}
|
||||
|
||||
/// [`Self::find_property`], with the object on the prototype chain that has the property.
|
||||
fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult<Option<(ObjId, Prop)>> {
|
||||
let mut cur = Some(id);
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
if let Some(p) = self.get_own_property(o, k)? {
|
||||
return Ok(Some(p));
|
||||
return Ok(Some((o, p)));
|
||||
}
|
||||
// A typed array's prototypes are not searched for a numeric name (section 9.4.5.4).
|
||||
if crate::builtins::binary::typed_key(self, o, k).is_some() {
|
||||
@@ -1763,7 +1859,14 @@ impl Interp {
|
||||
{
|
||||
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
|
||||
}
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
// A module's export read before the module ran is in its temporal dead zone (ECMA-262
|
||||
// 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it
|
||||
// through a prototype chain.
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
// A name the object and its prototypes lack is the indexer's answer too.
|
||||
None => match self.host_indexer(start)? {
|
||||
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
|
||||
@@ -1779,7 +1882,11 @@ impl Interp {
|
||||
/// class: a name the object and its prototypes lack is `undefined`. For names the engine looks
|
||||
/// up itself, such as `toJSON`, which a collection's indexer would answer with an error.
|
||||
pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult<Value> {
|
||||
match self.find_property(start, k)? {
|
||||
let found = self.find_property_on(start, k)?;
|
||||
if let Some((holder, _)) = &found {
|
||||
self.check_namespace_export(*holder, k)?;
|
||||
}
|
||||
match found.map(|(_, p)| p) {
|
||||
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Some(Prop::Data { value, .. }) => Ok(value),
|
||||
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
@@ -1891,10 +1998,26 @@ impl Interp {
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw),
|
||||
_ => self.define_ordinary(id, k, desc, throw),
|
||||
}
|
||||
}
|
||||
|
||||
/// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.5): only a
|
||||
/// descriptor that leaves an export as it is (enumerable, writable, not configurable, its
|
||||
/// current value) succeeds.
|
||||
fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else {
|
||||
return self.reject_bool(throw, k, "a module namespace object is not extensible");
|
||||
};
|
||||
let unchanged = desc.configurable != Some(true)
|
||||
&& desc.enumerable != Some(false)
|
||||
&& !desc.is_accessor()
|
||||
&& desc.writable != Some(false)
|
||||
&& desc.value.as_ref().is_none_or(|v| same_value(v, &value));
|
||||
if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") }
|
||||
}
|
||||
|
||||
pub(crate) fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<bool> {
|
||||
if throw {
|
||||
let key = String::from_utf16_lossy(k);
|
||||
@@ -2067,6 +2190,10 @@ impl Interp {
|
||||
if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) {
|
||||
return crate::builtins::binary::set_element(self, id, n, &v);
|
||||
}
|
||||
// A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9).
|
||||
if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
match self.get_own_property(id, &k)? {
|
||||
Some(Prop::Data { flags, .. }) => {
|
||||
if flags & WRITABLE == 0 {
|
||||
@@ -2078,8 +2205,25 @@ impl Interp {
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
None => {}
|
||||
}
|
||||
let proto = self.object(id)?.proto;
|
||||
let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten();
|
||||
let mut inherited = None;
|
||||
let mut cur = self.object(id)?.proto;
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
// A write that reaches a module namespace object on the prototype chain is refused
|
||||
// there too: its [[Set]] returns false for every key.
|
||||
if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) {
|
||||
return self.reject(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
if let Some(p) = self.get_own_property(o, &k)? {
|
||||
inherited = Some(p);
|
||||
break;
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return internal("prototype chain too long");
|
||||
}
|
||||
}
|
||||
match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop),
|
||||
Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"),
|
||||
@@ -2952,6 +3096,8 @@ impl Interp {
|
||||
// listed or their bytes reserved must not free it.
|
||||
let saved = self.temp_roots.len();
|
||||
self.temp_roots.push(Value::Object(o));
|
||||
// Listing a namespace object's exports does not read them (ECMA-262 2015 section
|
||||
// 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed.
|
||||
let keys = self.enumerable_keys(o).and_then(|keys| {
|
||||
let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::<usize>();
|
||||
self.reserve_heap(bytes)?;
|
||||
@@ -3066,8 +3212,8 @@ impl Interp {
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?));
|
||||
}
|
||||
Func::Eval { f, end, strict_writes, name } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?));
|
||||
Func::Eval { f, end, strict_writes, name, site } => {
|
||||
return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?));
|
||||
}
|
||||
Func::Host { f: host, .. } => {
|
||||
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
|
||||
@@ -3156,9 +3302,7 @@ impl Interp {
|
||||
/// the stack.
|
||||
pub(crate) fn enter_function(&mut self, entry: Entry, construct: Option<ObjId>, boundary: bool) -> JsResult<()> {
|
||||
let Entry { callee, code, env, this, args, new_target } = entry;
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
self.check_frame_room()?;
|
||||
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
// An arrow function reads the `arguments` object of the function around it.
|
||||
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
|
||||
@@ -3219,6 +3363,8 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
};
|
||||
@@ -3545,17 +3691,16 @@ impl Interp {
|
||||
|
||||
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
|
||||
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
self.compile_units(units, strict, writes, kind, false)
|
||||
self.compile_units(units, strict, writes, kind, SuperRules::default())
|
||||
}
|
||||
|
||||
/// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function,
|
||||
/// where `new.target` is allowed.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result<Rc<Code>, CompileError> {
|
||||
/// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at
|
||||
/// the top of the code: what they may do where a direct `eval` is called.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result<Rc<Code>, CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 };
|
||||
let program = parse(units, &options).map_err(CompileError::Syntax)?;
|
||||
let program = crate::parse_utf16_with_supers(units, &options, supers).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
@@ -3563,6 +3708,22 @@ impl Interp {
|
||||
})
|
||||
}
|
||||
|
||||
/// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the
|
||||
/// source limit, with [`Self::source_tag`] as its source's tag.
|
||||
pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc<Code>, crate::ModuleInfo), CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { max_source_units: remaining, ..self.options.clone() };
|
||||
let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let writes = self.writes_mode();
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
CompileFail::Internal(m) => CompileError::Internal(m),
|
||||
})?;
|
||||
Ok((code, info))
|
||||
}
|
||||
|
||||
/// Turns a compile failure inside a running script into what it throws.
|
||||
pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt {
|
||||
match e {
|
||||
@@ -3582,10 +3743,12 @@ impl Interp {
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
// Inside a function the eval code reads the function's `new.target` (section 18.2.1.1).
|
||||
let new_target = self.caller_new_target()?;
|
||||
// The eval code may use `super` and `new.target` as the code that calls it may, and reads
|
||||
// the `new.target` of the function it is in (section 18.2.1.1).
|
||||
let supers = self.frame()?.code.supers;
|
||||
let new_target = if supers.new_target { self.caller_new_target()? } else { None };
|
||||
let writes = self.writes_mode();
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
@@ -3749,7 +3912,7 @@ impl Interp {
|
||||
|
||||
/// A [`LimitKind::Frames`] error when no other frame fits under the frame limit.
|
||||
fn check_frame_room(&self) -> JsResult<()> {
|
||||
if self.frames.len() >= self.limits.frames {
|
||||
if self.frames.len() - self.pending_module_frames >= self.limits.frames {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
Ok(())
|
||||
@@ -3775,10 +3938,127 @@ impl Interp {
|
||||
completion: Value::Undefined,
|
||||
boundary,
|
||||
generator: None,
|
||||
chained: false,
|
||||
pending_module: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4,
|
||||
/// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global
|
||||
/// scope holds its variables and functions, and one inside that its `let` and `const` names,
|
||||
/// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary
|
||||
/// roots for the caller to remove.
|
||||
pub(crate) fn instantiate_module(&mut self, code: &Rc<Code>) -> JsResult<(EnvId, EnvId)> {
|
||||
// The code itself was counted when the module was loaded ([`Self::hold_module_code`]).
|
||||
self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?;
|
||||
let scope = self.global_lex;
|
||||
let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) });
|
||||
self.temp_envs.push(env);
|
||||
let lex = self.instantiate_global(code, env, env, true)?;
|
||||
self.temp_envs.push(lex);
|
||||
Ok((lex, env))
|
||||
}
|
||||
|
||||
/// Adds `binding` (an import) to the module environment `env`, which must not have `name`.
|
||||
pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> {
|
||||
self.use_fuel()?;
|
||||
// The binding's value (a namespace object) stays reachable while room is made.
|
||||
self.temp_roots.push(binding.value.clone());
|
||||
let reserved = self.reserve_heap(binding_bytes(name.len()));
|
||||
self.temp_roots.pop();
|
||||
reserved?;
|
||||
self.env_insert(env, name, binding)
|
||||
}
|
||||
|
||||
/// The environment that holds `name` of a module whose code runs in `lex` inside `env`.
|
||||
pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option<EnvId> {
|
||||
[lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name)))
|
||||
}
|
||||
|
||||
/// A module namespace object for the exports `exports`, each `(name, binding)` with the
|
||||
/// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit
|
||||
/// order and distinct.
|
||||
pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult<ObjId> {
|
||||
let names = exports.iter().map(|(name, _)| string_bytes(name.len())).sum::<usize>();
|
||||
let bindings = PROP_BYTES.saturating_mul(exports.len());
|
||||
let tag = self.well_known(|symbols| &symbols.to_string_tag);
|
||||
let tagged = if tag.is_some() { PROP_BYTES.saturating_add(string_bytes(6)) } else { 0 };
|
||||
let extra = bindings.saturating_add(names).saturating_add(tagged);
|
||||
self.reserve_heap(OBJECT_BYTES.saturating_add(bindings).saturating_add(extra))?;
|
||||
let mut object = Object::new(Class::ModuleNamespace(Box::default()), None);
|
||||
if let Some(tag) = tag {
|
||||
object.syms.get_or_insert_with(Default::default).insert(tag, Prop::Data { value: Value::str("Module"), flags: 0 });
|
||||
}
|
||||
object.extensible = false;
|
||||
for (name, _) in &exports {
|
||||
self.use_fuel()?;
|
||||
let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone());
|
||||
object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE });
|
||||
}
|
||||
object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports }));
|
||||
let namespace = self.heap.alloc_object(object);
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
Ok(namespace)
|
||||
}
|
||||
|
||||
/// Pushes the frames of a run of modules: `modules` in the order they run, each with its code,
|
||||
/// the environment it runs in and the outer one. The last is the boundary frame, pushed first;
|
||||
/// each of the others is pushed above the one that runs after it, so the first to run is on
|
||||
/// top.
|
||||
pub(crate) fn push_module_frames(&mut self, modules: &[(Rc<Code>, EnvId, EnvId)]) -> JsResult<()> {
|
||||
for (i, (code, env, var_env)) in modules.iter().enumerate().rev() {
|
||||
let last = i + 1 == modules.len();
|
||||
self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?;
|
||||
if let Some(frame) = self.frames.last_mut() {
|
||||
frame.chained = !last;
|
||||
frame.pending_module = true;
|
||||
}
|
||||
self.pending_module_frames += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the temporary roots from `mark` on.
|
||||
pub(crate) fn drop_temp_envs(&mut self, mark: usize) {
|
||||
self.temp_envs.truncate(mark);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_envs_mark(&self) -> usize {
|
||||
self.temp_envs.len()
|
||||
}
|
||||
|
||||
/// Counts a loaded module's code against the heap once, when the module is loaded, and keeps
|
||||
/// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules
|
||||
/// load counts it too.
|
||||
pub(crate) fn hold_module_code(&mut self, code: &Rc<Code>) -> JsResult<()> {
|
||||
self.charge_code(code, 0)?;
|
||||
self.temp_codes.push(code.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn temp_codes_mark(&self) -> usize {
|
||||
self.temp_codes.len()
|
||||
}
|
||||
|
||||
/// Ends module linking: drops the modules' code held from `mark` on.
|
||||
pub(crate) fn drop_temp_codes(&mut self, mark: usize) {
|
||||
self.temp_codes.truncate(mark);
|
||||
}
|
||||
|
||||
/// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it.
|
||||
pub(crate) fn hold(&mut self, v: Value) {
|
||||
self.temp_roots.push(v);
|
||||
}
|
||||
|
||||
pub(crate) fn temp_roots_mark(&self) -> usize {
|
||||
self.temp_roots.len()
|
||||
}
|
||||
|
||||
pub(crate) fn drop_temp_roots(&mut self, mark: usize) {
|
||||
self.temp_roots.truncate(mark);
|
||||
}
|
||||
|
||||
/// Declaration binding instantiation for global and eval code (section 10.5). The caller has
|
||||
/// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel.
|
||||
///
|
||||
|
||||
@@ -1048,6 +1048,7 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
own_name: None,
|
||||
method: false,
|
||||
generator: false,
|
||||
supers: crate::parser::SuperRules::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+50
-8
@@ -63,7 +63,17 @@
|
||||
//! closes its iterator. In a realm made without the option and later given it with
|
||||
//! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects
|
||||
//! by index and strings by code point, and throw a `TypeError` for other values.
|
||||
//! Object rest properties (`{ a, ...rest }`) and modules stay syntax errors.
|
||||
//! Object rest properties (`{ a, ...rest }`) stay syntax errors, and so do `import` and `export`
|
||||
//! in a script.
|
||||
//!
|
||||
//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import`
|
||||
//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a
|
||||
//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module
|
||||
//! once, after the modules it imports, with each import reading the exporting module's binding. In
|
||||
//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does
|
||||
//! not wait for a module that is still waiting for its own imports, and reading a binding of that
|
||||
//! module before it is initialized throws a `ReferenceError`.
|
||||
//! Dynamic `import()` is a syntax error.
|
||||
//!
|
||||
//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition,
|
||||
//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in
|
||||
@@ -129,6 +139,7 @@ mod host_classes;
|
||||
mod interp;
|
||||
mod iteration;
|
||||
mod lexer;
|
||||
mod module;
|
||||
mod number;
|
||||
mod number_builtins;
|
||||
mod parser;
|
||||
@@ -151,15 +162,16 @@ mod xmp_classes;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId,
|
||||
FunctionKind, LexKind, LogicalOp, MethodKind, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece,
|
||||
UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, Binding, CatchClause, ClassDef, ClassElement, ClassKey, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget,
|
||||
ForInit, Function, FunctionId, FunctionKind, ImportEntry, ImportName, LexKind, LogicalOp, MethodKind, ModuleInfo, ModuleRequest, Name, Program,
|
||||
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{
|
||||
Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE,
|
||||
@@ -222,11 +234,39 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
|
||||
/// (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
|
||||
/// Parses `source` as a module (ECMA-262 2015 section 15.2): strict mode code with
|
||||
/// [`Options::es2015`]'s forms, `import` and `export` declarations at its top, and no preprocessor
|
||||
/// lines, whatever `options` says about those three. Gives its statements and what it imports and
|
||||
/// exports.
|
||||
pub fn parse_module(source: &str, options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
parse_module_utf16(&units, options)
|
||||
}
|
||||
|
||||
/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]).
|
||||
pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program)
|
||||
parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info))
|
||||
}
|
||||
|
||||
/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module
|
||||
/// ([`parse_module`]). The source must be a valid module.
|
||||
pub fn tokenize_module(source: &str, options: &Options) -> Result<Vec<Token>, SyntaxError> {
|
||||
let units = to_utf16(source, options)?;
|
||||
check_length(units.len(), options)?;
|
||||
parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens)
|
||||
}
|
||||
|
||||
/// `options` as a module is read with them.
|
||||
pub(crate) fn module_options(options: &Options) -> Options {
|
||||
Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() }
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the
|
||||
/// code that calls it may (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result<Program, SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_supers(rules).parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and
|
||||
@@ -324,6 +364,8 @@ mod host_tests;
|
||||
#[cfg(test)]
|
||||
mod interp_tests;
|
||||
#[cfg(test)]
|
||||
mod module_tests;
|
||||
#[cfg(test)]
|
||||
mod promise_tests;
|
||||
#[cfg(test)]
|
||||
mod reflect_tests;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports,
|
||||
//! linking their imports to the bindings their exports name, and readying them to run, each once,
|
||||
//! the modules a module imports before it.
|
||||
//!
|
||||
//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17,
|
||||
//! HostResolveImportedModule): it gives a key that names the module, and its source the first time
|
||||
//! it gives that key. Every module is parsed and compiled before any runs, and every import is
|
||||
//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host
|
||||
//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many
|
||||
//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each
|
||||
//! binding made in linking takes a unit.
|
||||
//!
|
||||
//! An import reads the exporting module's binding itself, so it sees each later assignment, and a
|
||||
//! read before that binding is initialized (a module that imports one that imports it back) is a
|
||||
//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no
|
||||
//! prototype, takes no writes and has the module's export names, in code unit order, as its
|
||||
//! properties. `export *` passes on every name but `default`; a name two `export *` give from
|
||||
//! different bindings is left out of a namespace and is a `SyntaxError` to import.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ast::{ExportEntry, ImportName, ModuleInfo};
|
||||
use crate::bytecode::Code;
|
||||
use crate::heap::{Binding, Env, EnvId, ObjId, Prop, key};
|
||||
use crate::interp::{Abrupt, CompileError, ErrorType, Interp};
|
||||
use crate::value::Value;
|
||||
|
||||
/// What the host gives for a module a run imports.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoadedModule {
|
||||
/// What names the module: two specifiers that give one key import one module, which runs once.
|
||||
pub key: String,
|
||||
/// The module's source, given the first time the host gives its key in a run. `None` for a key
|
||||
/// the host gave before in the same run.
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
/// Why the host cannot give a module, which ends the run before any module runs: the error the
|
||||
/// `import` raises, with its message.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LoadError {
|
||||
/// A specifier the host does not read: a `SyntaxError`.
|
||||
Syntax(String),
|
||||
/// A limit of the host's: a `RangeError`.
|
||||
Range(String),
|
||||
/// A module that is missing, refused or unreadable: an `Error`.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
/// The host's map from a specifier to a module: called with the key of the importing module and
|
||||
/// the specifier as written.
|
||||
pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result<LoadedModule, LoadError> + 'a;
|
||||
|
||||
/// Bounds on the modules of one run.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ModuleLimits {
|
||||
/// The most modules a run loads, the first included.
|
||||
pub modules: usize,
|
||||
/// The most imports from the first module to any other, along the shortest chain.
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
impl Default for ModuleLimits {
|
||||
fn default() -> Self {
|
||||
Self { modules: 64, depth: 16 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The most modules a run loads, whatever its limits say: [`resolve_export`] and
|
||||
/// [`exported_names`] recurse once for each module at most.
|
||||
const MAX_MODULES: usize = 1024;
|
||||
/// The most `(module, name)` pairs one export's resolution visits.
|
||||
const MAX_RESOLVE_STEPS: usize = 1024;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ResolveSeen {
|
||||
pairs: HashSet<ResolveKey>,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
struct ResolveKey {
|
||||
module: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl PartialEq for ResolveKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(count.get() + 1));
|
||||
self.module == other.module && self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ResolveKey {}
|
||||
|
||||
impl std::hash::Hash for ResolveKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&(self.module, &self.name), state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
pub(crate) static RESOLVED_STAR_EDGES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
pub(crate) static RESOLVE_MEMBERSHIP_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A loaded module.
|
||||
struct Record {
|
||||
key: String,
|
||||
info: ModuleInfo,
|
||||
code: Rc<Code>,
|
||||
tag: u32,
|
||||
/// The module each of `info.requests` names, by index.
|
||||
requested: Vec<usize>,
|
||||
/// The environment its code runs in and the outer one, once instantiated.
|
||||
envs: Option<(EnvId, EnvId)>,
|
||||
namespace: Option<ObjId>,
|
||||
/// Each name the module exports itself or re-exports by name, with its entry in
|
||||
/// `info.exports`.
|
||||
explicit: HashMap<String, usize>,
|
||||
/// Each `export *` request, replaced by distinct canonical targets after loading, in order.
|
||||
stars: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Why a module run could not start.
|
||||
pub(crate) enum LinkFail {
|
||||
/// A module does not parse; `tag` is its source's.
|
||||
Syntax { tag: u32, error: crate::SyntaxError },
|
||||
/// An exception, raised at `line` and `column` of the module whose source has `tag`.
|
||||
At { tag: u32, line: u32, column: u32, abrupt: Abrupt },
|
||||
/// A limit or an internal error, not at any place.
|
||||
Run(Abrupt),
|
||||
}
|
||||
|
||||
/// Where an export resolves to (ResolvedBinding).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum Resolution {
|
||||
/// The binding `name` of module `module`.
|
||||
Binding { module: usize, name: String },
|
||||
/// The namespace object of module `module` (`export * as ns from`).
|
||||
Namespace(usize),
|
||||
}
|
||||
|
||||
/// An export that two `export *` declarations give from different places.
|
||||
struct Ambiguous;
|
||||
|
||||
/// The modules of a run, loaded and linked.
|
||||
struct Graph<'a, 'l> {
|
||||
interp: &'a mut Interp,
|
||||
records: Vec<Record>,
|
||||
by_key: HashMap<String, usize>,
|
||||
load: &'a mut ModuleLoader<'l>,
|
||||
}
|
||||
|
||||
/// Loads the module `key` with `source` and every module it imports, instantiates and links them,
|
||||
/// and gives them in the order they run, each with its code, the environment it runs in and the
|
||||
/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes
|
||||
/// the next tag. The environments stay in the interpreter's temporary roots for the caller to
|
||||
/// remove once their frames are pushed.
|
||||
pub(crate) fn link(
|
||||
interp: &mut Interp,
|
||||
key_name: &str,
|
||||
source: &str,
|
||||
entry_tag: u32,
|
||||
limits: ModuleLimits,
|
||||
load: &mut ModuleLoader<'_>,
|
||||
) -> Result<Vec<(Rc<Code>, EnvId, EnvId)>, LinkFail> {
|
||||
let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load };
|
||||
if limits.modules == 0 {
|
||||
return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached"));
|
||||
}
|
||||
graph.add(key_name.to_string(), source, entry_tag)?;
|
||||
graph.load_imports(limits)?;
|
||||
graph.instantiate()?;
|
||||
graph.link_imports()?;
|
||||
Ok(graph.evaluation_order())
|
||||
}
|
||||
|
||||
impl Graph<'_, '_> {
|
||||
/// Parses and compiles a module's source under `tag`.
|
||||
fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result<usize, LinkFail> {
|
||||
let interp = &mut *self.interp;
|
||||
let minimum_units = source.len().div_ceil(3);
|
||||
if u64::try_from(minimum_units).unwrap_or(u64::MAX) > interp.fuel {
|
||||
interp.prepare_source(minimum_units).map_err(LinkFail::Run)?;
|
||||
}
|
||||
interp.prepare_source(0).map_err(LinkFail::Run)?;
|
||||
interp.prepare_source(source.encode_utf16().count()).map_err(LinkFail::Run)?;
|
||||
let saved = std::mem::replace(&mut interp.source_tag, tag);
|
||||
let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units));
|
||||
interp.source_tag = saved;
|
||||
let (code, info) = match compiled {
|
||||
Ok(c) => c,
|
||||
Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }),
|
||||
Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))),
|
||||
};
|
||||
// The record keeps the code from here on, so the heap counts it from here on.
|
||||
self.interp.hold_module_code(&code).map_err(LinkFail::Run)?;
|
||||
let mut explicit = HashMap::new();
|
||||
let mut stars = Vec::new();
|
||||
for (i, e) in info.exports.iter().enumerate() {
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
explicit.entry(export_name.clone()).or_insert(i);
|
||||
}
|
||||
ExportEntry::Star { request, .. } => stars.push(*request),
|
||||
}
|
||||
}
|
||||
self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars });
|
||||
let index = self.records.len() - 1;
|
||||
self.by_key.insert(key_name, index);
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// An exception of type `t` with `message`, at the source offset `offset` of module `m`.
|
||||
fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail {
|
||||
let (tag, (line, column)) = match self.records.get(m) {
|
||||
Some(r) => (r.tag, r.code.source.lines.line_column(offset)),
|
||||
None => (crate::realm::UNKNOWN_SOURCE, (0, 0)),
|
||||
};
|
||||
LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) }
|
||||
}
|
||||
|
||||
/// Loads the modules each loaded module imports, breadth first, so a module's depth is the
|
||||
/// length of the shortest chain of imports to it.
|
||||
fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> {
|
||||
let max_modules = limits.modules.min(MAX_MODULES);
|
||||
let mut depths = vec![0usize];
|
||||
let mut i = 0;
|
||||
while i < self.records.len() {
|
||||
let requests: Vec<(String, bool, u32)> = self.records[i]
|
||||
.info
|
||||
.requests
|
||||
.iter()
|
||||
.map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start))
|
||||
.collect();
|
||||
let depth = depths.get(i).copied().unwrap_or(0);
|
||||
for (specifier, text, offset) in requests {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
// The host maps text to modules, and a specifier with an unpaired surrogate is not
|
||||
// text, so it is refused here, as a host refuses a specifier it does not read.
|
||||
if !text {
|
||||
let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Syntax, &message));
|
||||
}
|
||||
let referrer = self.records[i].key.clone();
|
||||
let loaded = match (self.load)(&referrer, &specifier) {
|
||||
Ok(loaded) => loaded,
|
||||
Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)),
|
||||
Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)),
|
||||
Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)),
|
||||
};
|
||||
let target = match (self.by_key.get(&loaded.key), loaded.source) {
|
||||
(Some(&j), _) => j,
|
||||
(None, None) => {
|
||||
let message = format!("the module '{specifier}' was given without its source");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Error, &message));
|
||||
}
|
||||
(None, Some(source)) => {
|
||||
if depth >= limits.depth {
|
||||
let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth);
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
if self.records.len() >= max_modules {
|
||||
let message = format!("module limit ({max_modules}) reached at '{specifier}'");
|
||||
return Err(self.fail_at(i, offset, ErrorType::Range, &message));
|
||||
}
|
||||
let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag));
|
||||
self.interp.evaluated = tag;
|
||||
depths.push(depth + 1);
|
||||
self.add(loaded.key, &source, tag)?
|
||||
}
|
||||
};
|
||||
self.records[i].requested.push(target);
|
||||
}
|
||||
let mut seen_targets = HashSet::new();
|
||||
let targets: Vec<usize> = self.records[i]
|
||||
.stars
|
||||
.iter()
|
||||
.filter_map(|&request| self.records[i].requested.get(request).copied())
|
||||
.filter(|target| seen_targets.insert(*target))
|
||||
.collect();
|
||||
self.records[i].stars = targets;
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Makes each module's environments, with its variables, functions and `let` and `const`
|
||||
/// names.
|
||||
fn instantiate(&mut self) -> Result<(), LinkFail> {
|
||||
for i in 0..self.records.len() {
|
||||
let code = self.records[i].code.clone();
|
||||
let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?;
|
||||
self.records[i].envs = Some(envs);
|
||||
for import in &self.records[i].info.imports {
|
||||
if matches!(&import.import, ImportName::Namespace) {
|
||||
self.interp.add_import(envs.1, key(&import.local.name), Binding::lexical(true)).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The module the request `request` of module `m` names.
|
||||
fn target(&self, m: usize, request: usize) -> Option<usize> {
|
||||
self.records.get(m).and_then(|r| r.requested.get(request)).copied()
|
||||
}
|
||||
|
||||
/// The specifier of request `request` of module `m`, as written.
|
||||
fn specifier(&self, m: usize, request: usize) -> String {
|
||||
self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from,
|
||||
/// `None` when the module has no such export (or only through a cycle).
|
||||
fn resolve_export(&mut self, m: usize, name: &str, seen: &mut ResolveSeen) -> Result<Result<Option<Resolution>, Ambiguous>, LinkFail> {
|
||||
#[cfg(test)]
|
||||
RESOLVE_CALLS.with(|count| count.set(count.get() + 1));
|
||||
let visit = ResolveKey { module: m, name: name.to_string() };
|
||||
if seen.pairs.contains(&visit) {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
if seen.count >= MAX_RESOLVE_STEPS {
|
||||
let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'");
|
||||
return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message)));
|
||||
}
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
seen.pairs.insert(visit);
|
||||
seen.count += 1;
|
||||
let Some(record) = self.records.get(m) else { return Ok(Ok(None)) };
|
||||
// The module's own export of the name, looked up in its index, comes before any `export *`.
|
||||
let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i));
|
||||
match explicit {
|
||||
Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))),
|
||||
Some(ExportEntry::Indirect { request, import, .. }) => {
|
||||
let (request, import) = (*request, import.clone());
|
||||
let Some(t) = self.target(m, request) else { return Ok(Ok(None)) };
|
||||
return match import {
|
||||
ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))),
|
||||
ImportName::Name(n) => self.resolve_export(t, &n, seen),
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if name == "default" {
|
||||
return Ok(Ok(None));
|
||||
}
|
||||
let mut star = None;
|
||||
let stars = record.stars.clone();
|
||||
for t in stars {
|
||||
#[cfg(test)]
|
||||
RESOLVED_STAR_EDGES.with(|count| count.set(count.get() + 1));
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
match self.resolve_export(t, name, seen)? {
|
||||
Err(Ambiguous) => return Ok(Err(Ambiguous)),
|
||||
Ok(None) => {}
|
||||
Ok(Some(r)) => match &star {
|
||||
None => star = Some(r),
|
||||
Some(s) if *s == r => {}
|
||||
Some(_) => return Ok(Err(Ambiguous)),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(Ok(star))
|
||||
}
|
||||
|
||||
/// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its
|
||||
/// `export *` modules but `default` included, each once.
|
||||
fn exported_names(
|
||||
&mut self,
|
||||
m: usize,
|
||||
star: bool,
|
||||
visited: &mut Vec<usize>,
|
||||
names: &mut Vec<String>,
|
||||
seen: &mut HashSet<String>,
|
||||
) -> Result<(), LinkFail> {
|
||||
if visited.contains(&m) {
|
||||
return Ok(());
|
||||
}
|
||||
visited.push(m);
|
||||
let count = self.records.get(m).map_or(0, |r| r.info.exports.len());
|
||||
for i in 0..count {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break };
|
||||
match e {
|
||||
ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => {
|
||||
if !(star && export_name == "default") && !seen.contains(export_name) {
|
||||
seen.insert(export_name.clone());
|
||||
names.push(export_name.clone());
|
||||
}
|
||||
}
|
||||
ExportEntry::Star { request, .. } => {
|
||||
if let Some(t) = self.target(m, *request) {
|
||||
self.exported_names(t, true, visited, names, seen)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The environment and name of the binding `name` of module `m`.
|
||||
fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> {
|
||||
let (lex, env) = self.records.get(m)?.envs?;
|
||||
let k = key(name);
|
||||
self.interp.module_binding(lex, env, &k).map(|e| (e, k))
|
||||
}
|
||||
|
||||
/// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time.
|
||||
fn namespace(&mut self, m: usize) -> Result<ObjId, LinkFail> {
|
||||
if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) {
|
||||
return Ok(ns);
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?;
|
||||
let mut resolved = Vec::new();
|
||||
for name in names {
|
||||
if let Ok(Some(r)) = self.resolve_export(m, &name, &mut ResolveSeen::default())? {
|
||||
resolved.push((key(&name), r));
|
||||
}
|
||||
}
|
||||
resolved.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
let mut exports = Vec::new();
|
||||
let mut later = Vec::new();
|
||||
for (k, r) in resolved {
|
||||
match r {
|
||||
Resolution::Binding { module, name } => match self.binding_of(module, &name) {
|
||||
Some(b) => exports.push((k, Some(b))),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Resolution::Namespace(module) => {
|
||||
exports.push((k.clone(), None));
|
||||
later.push((k, module));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?;
|
||||
self.interp.hold(Value::Object(ns));
|
||||
if let Some(r) = self.records.get_mut(m) {
|
||||
r.namespace = Some(ns);
|
||||
}
|
||||
// A namespace that holds another is made first, so two that hold each other end.
|
||||
for (k, module) in later {
|
||||
let inner = self.namespace(module)?;
|
||||
let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE;
|
||||
self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?;
|
||||
}
|
||||
Ok(ns)
|
||||
}
|
||||
|
||||
/// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that
|
||||
/// each re-export resolves.
|
||||
fn link_imports(&mut self) -> Result<(), LinkFail> {
|
||||
for m in 0..self.records.len() {
|
||||
let exports = self.records[m].info.exports.clone();
|
||||
for e in &exports {
|
||||
let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue };
|
||||
if self.target(m, *request).is_none() {
|
||||
continue;
|
||||
}
|
||||
match self.resolve_export(m, export_name, &mut ResolveSeen::default())? {
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request));
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{export_name}' is ambiguous");
|
||||
return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
}
|
||||
}
|
||||
let imports = self.records[m].info.imports.clone();
|
||||
let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) };
|
||||
for imp in imports {
|
||||
let Some(t) = self.target(m, imp.request) else { continue };
|
||||
let local = key(&imp.local.name);
|
||||
let binding = match &imp.import {
|
||||
ImportName::Namespace => self.namespace_binding(t)?,
|
||||
ImportName::Name(n) => match self.resolve_export(t, n, &mut ResolveSeen::default())? {
|
||||
Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) {
|
||||
Some((target_env, target_name)) => Binding::import(target_env, target_name),
|
||||
None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))),
|
||||
},
|
||||
Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?,
|
||||
Ok(None) => {
|
||||
let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
Err(Ambiguous) => {
|
||||
let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request));
|
||||
return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message));
|
||||
}
|
||||
},
|
||||
};
|
||||
if matches!(&imp.import, ImportName::Namespace) {
|
||||
self.interp.use_fuel().map_err(LinkFail::Run)?;
|
||||
let Some(Env::Decl { bindings, .. }) = self.interp.heap.env_mut(env) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import environment not found".into())));
|
||||
};
|
||||
let Some(slot) = bindings.get_mut(&local) else {
|
||||
return Err(LinkFail::Run(Abrupt::Internal("namespace import binding not found".into())));
|
||||
};
|
||||
*slot = binding;
|
||||
} else {
|
||||
self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An immutable binding of module `m`'s namespace object.
|
||||
fn namespace_binding(&mut self, m: usize) -> Result<Binding, LinkFail> {
|
||||
let ns = self.namespace(m)?;
|
||||
Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) })
|
||||
}
|
||||
|
||||
/// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module
|
||||
/// after the modules it imports, in the order it imports them, and each once; a module an
|
||||
/// import cycle reaches again while it waits is not waited for.
|
||||
fn evaluation_order(&self) -> Vec<(Rc<Code>, EnvId, EnvId)> {
|
||||
let mut state = vec![0u8; self.records.len()];
|
||||
let mut order = Vec::new();
|
||||
let mut stack = vec![(0usize, 0usize)];
|
||||
if let Some(s) = state.first_mut() {
|
||||
*s = 1;
|
||||
}
|
||||
while let Some(top) = stack.last_mut() {
|
||||
let m = top.0;
|
||||
let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice());
|
||||
if let Some(&t) = requested.get(top.1) {
|
||||
top.1 += 1;
|
||||
if let Some(s @ 0) = state.get_mut(t) {
|
||||
*s = 1;
|
||||
stack.push((t, 0));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
stack.pop();
|
||||
if let Some(r) = self.records.get(m)
|
||||
&& let Some((lex, env)) = r.envs
|
||||
{
|
||||
order.push((r.code.clone(), lex, env));
|
||||
}
|
||||
}
|
||||
order
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,759 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::{
|
||||
JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module,
|
||||
};
|
||||
|
||||
fn es() -> Realm {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
// Modules declare no globals, so they report through this array.
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
realm
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_var_records_survive_deleting_only_an_inherited_property() {
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete this.w; Object.prototype.w = 7; delete w;"), Ok(JsValue::Bool(true)));
|
||||
let error = realm.run("let w = 2; w;").unwrap_err();
|
||||
assert!(matches!(error.kind, RunErrorKind::Syntax | RunErrorKind::Thrown), "{error:?}");
|
||||
|
||||
let mut realm = es();
|
||||
realm.run("Object.defineProperty(this, 'w', {value: 1, writable: true, configurable: true});").unwrap();
|
||||
assert_eq!(realm.run("var w; delete w;"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("let w = 2; w;"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_allocations_charge_binding_tables_and_symbols() {
|
||||
use crate::heap::{OBJECT_BYTES, PROP_BYTES, key};
|
||||
let mut realm = es();
|
||||
let interp = realm.interp();
|
||||
let before = interp.heap.bytes;
|
||||
let exports = (0..128).map(|n| (key(&format!("v{n}")), None)).collect();
|
||||
let namespace = interp.module_namespace(exports, &[]).unwrap();
|
||||
let symbols = interp.heap.object(namespace).unwrap().syms.as_ref().map_or(0, |symbols| symbols.len());
|
||||
let required = OBJECT_BYTES + PROP_BYTES * (128 * 2 + symbols);
|
||||
assert!(interp.heap.bytes - before >= required, "namespace charged {} bytes, needs at least {required}", interp.heap.bytes - before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_resolution_membership_work_is_bounded_per_visit() {
|
||||
let mut files: Vec<(String, String)> = (0..31).map(|n| (format!("./m{n}.mjs"), format!("export * from './m{}.mjs';", n + 1))).collect();
|
||||
let source = (0..32).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
files.push(("./m31.mjs".into(), source));
|
||||
let references: Vec<_> = files.iter().map(|(name, source)| (name.as_str(), source.as_str())).collect();
|
||||
let mut load = loader(&references);
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVE_CALLS.with(|count| count.set(0));
|
||||
crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './m0.mjs'; out.push(ns.v0, ns.v31);", ModuleLimits { modules: 64, depth: 64 }, &mut load)
|
||||
.unwrap();
|
||||
let visits = crate::module::RESOLVE_CALLS.with(std::cell::Cell::get);
|
||||
let checks = crate::module::RESOLVE_MEMBERSHIP_CHECKS.with(std::cell::Cell::get);
|
||||
assert!(visits > 32);
|
||||
assert!(checks <= visits * 4, "{checks} membership checks for {visits} export visits");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("0|31".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_aliases_resolve_each_canonical_target_once_per_name() {
|
||||
let exports: String = (0..100).map(|n| format!("export var v{n} = {n};")).collect();
|
||||
let stars: String = (0..100).map(|n| format!("export * from './alias{n}.mjs';")).collect();
|
||||
let mut supplied = HashSet::new();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
let (key, source) = if specifier == "./stars.mjs" { ("stars", &stars) } else { ("canonical", &exports) };
|
||||
Ok(LoadedModule { key: key.into(), source: supplied.insert(key).then(|| source.clone()) })
|
||||
};
|
||||
let mut realm = es();
|
||||
crate::module::RESOLVED_STAR_EDGES.with(|count| count.set(0));
|
||||
realm
|
||||
.run_module("main.mjs", "import * as ns from './stars.mjs'; out.push(ns.v99, Object.keys(ns).length);", ModuleLimits::default(), &mut load)
|
||||
.unwrap();
|
||||
let steps = crate::module::RESOLVED_STAR_EDGES.with(|count| count.get());
|
||||
assert!(steps <= 200, "{steps} star edges inspected");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("99|100".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ending_a_module_queue_restores_normal_frame_accounting() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", "for (var i = 0; i < 1000; i++) {}")]);
|
||||
realm.start_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load).unwrap();
|
||||
assert!(matches!(realm.advance(1), Ok(Progress::Paused)));
|
||||
realm.end();
|
||||
assert_eq!(realm.run("function f() { return 1; } f();"), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_module_bodies_do_not_consume_active_call_frames() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { frames: 2, ..Limits::default() });
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "function f() { return 1; } f();")];
|
||||
let mut load = loader(&files);
|
||||
let result = realm.run_module("main.mjs", "import './a.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
let mut load = loader(&[]);
|
||||
let result = realm.run_module("main.mjs", "function f() { return f(); } f();", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(result.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Frames)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_stack_excludes_bodies_waiting_to_run() {
|
||||
let mut realm = es();
|
||||
realm.define_host_object("$", [("stack".to_string(), crate::HostItem::Script(crate::ScriptItem::Stack))].into_iter().collect()).unwrap();
|
||||
let (result, out) = run_with(
|
||||
&mut realm,
|
||||
"import './m.mjs';",
|
||||
&[("./m.mjs", "function trace() { var s = $.stack; out.push(s.split('[global]').length - 1, s.indexOf('trace:') >= 0); } trace();")],
|
||||
ModuleLimits::default(),
|
||||
);
|
||||
assert_eq!(result, Ok(JsValue::Undefined));
|
||||
assert_eq!(out, "1|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_sources_charge_utf16_units_instead_of_utf8_bytes() {
|
||||
let mut remaining = Vec::new();
|
||||
for character in ['a', 'é', '界'] {
|
||||
let source = format!("/*{}*/ export var value = 1;", character.to_string().repeat(1000));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default());
|
||||
let mut load = loader(&[]);
|
||||
realm.start_module("main.mjs", &source, ModuleLimits::default(), &mut load).unwrap();
|
||||
remaining.push(realm.fuel_left());
|
||||
}
|
||||
assert!(remaining.windows(2).all(|pair| pair[0] == pair[1]), "{remaining:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exported_functions_keep_their_public_names() {
|
||||
for (source, name) in [
|
||||
("export default function () {}", "default"),
|
||||
("export default () => {};", "default"),
|
||||
("export default (function () {});", "default"),
|
||||
("export default function named() {}", "named"),
|
||||
] {
|
||||
let out = run("import value from './m.mjs'; out.push(value.name);", &[("./m.mjs", source)]);
|
||||
assert_eq!(out, name, "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_writes_through_namespace_prototypes_are_refused() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; var k = Symbol('new'), child = Object.create(ns); \
|
||||
try { child[k] = 1; } catch (e) { out.push(e.name); } \
|
||||
out.push(Object.getOwnPropertySymbols(child).length); \
|
||||
Object.defineProperty(child, k, {value: 3, writable: true}); child[k] = 4; out.push(child[k]);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "TypeError|0|4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_exposes_its_own_immutable_symbol_tag() {
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs'; \
|
||||
var d = Object.getOwnPropertyDescriptor(ns, Symbol.toStringTag); \
|
||||
out.push(ns[Symbol.toStringTag], Object.getOwnPropertySymbols(ns).length, \
|
||||
d && d.writable, d && d.enumerable, d && d.configurable);",
|
||||
&[("./m.mjs", "export var value = 1;")],
|
||||
);
|
||||
assert_eq!(out, "Module|1|false|false|false");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_reject_await_identifiers_before_running_dependencies() {
|
||||
for source in ["export const await = 1;", "var aw\\u0061it = 1;", "await;", "function await() {}"] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./effect.mjs", "out.push('dependency');")]);
|
||||
let result = realm.run_module("main.mjs", "import './effect.mjs'; export const await = 1;", ModuleLimits::default(), &mut load);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(realm.run("out.length").unwrap(), JsValue::Number(0.0));
|
||||
assert!(realm.run("var await = 1; await").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synchronous_and_sliced_modules_drain_promise_jobs() {
|
||||
let source = "out.push('body'); Promise.resolve().then(function () { out.push('resolved'); }); \
|
||||
Promise.reject('rejected').catch(function (e) { out.push(e); });";
|
||||
for sliced in [false, true] {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[]);
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
match realm.advance(100).unwrap() {
|
||||
Progress::Paused => {}
|
||||
Progress::Done(value) => {
|
||||
assert_eq!(value, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
assert_eq!(realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap(), JsValue::Undefined);
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("body|resolved|rejected".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_a_module_discards_a_paused_script() {
|
||||
for (sliced, invalid) in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
let mut realm = es();
|
||||
realm.start("out.push('old');").unwrap();
|
||||
assert_eq!(realm.advance(1).unwrap(), Progress::Paused);
|
||||
let mut load = loader(&[]);
|
||||
let source = if invalid { "var = ;" } else { "out.push('new');" };
|
||||
if invalid {
|
||||
let result = if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load)
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).map(drop)
|
||||
};
|
||||
assert!(result.is_err());
|
||||
assert!(!realm.is_running(), "sliced={sliced}");
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String(String::new()));
|
||||
continue;
|
||||
}
|
||||
if sliced {
|
||||
realm.start_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
loop {
|
||||
if let Progress::Done(_) = realm.advance(100).unwrap() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
realm.run_module("main.mjs", source, ModuleLimits::default(), &mut load).unwrap();
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')").unwrap(), JsValue::String("new".into()), "sliced={sliced}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A loader over `files`: each specifier is its own key, given with its source the first time.
|
||||
fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result<LoadedModule, LoadError> + use<> {
|
||||
let map: HashMap<String, String> = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
let mut given = HashSet::new();
|
||||
move |_, specifier| {
|
||||
if !specifier.starts_with('.') && specifier != "main" {
|
||||
return Err(LoadError::Syntax(format!("bare specifier: {specifier}")));
|
||||
}
|
||||
let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?;
|
||||
let first = given.insert(specifier.to_string());
|
||||
Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`.
|
||||
fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result<JsValue, RunError>, String) {
|
||||
let mut load = loader(files);
|
||||
let result = realm.run_module("main.mjs", entry, limits, &mut load);
|
||||
let out = match realm.run("out.join('|')") {
|
||||
Ok(JsValue::String(s)) => s,
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
(result, out)
|
||||
}
|
||||
|
||||
fn run(entry: &str, files: &[(&str, &str)]) -> String {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Ok(v), out) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
out
|
||||
}
|
||||
(Err(e), _) => panic!("{entry}\n{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The run ends with an error whose message starts with `start`, and `out` holds `ran`.
|
||||
fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError {
|
||||
match run_with(&mut es(), entry, files, ModuleLimits::default()) {
|
||||
(Err(e), out) => {
|
||||
assert!(e.message.starts_with(start), "{entry}: {e:?}");
|
||||
assert_eq!(out, ran, "{entry}");
|
||||
e
|
||||
}
|
||||
(Ok(_), out) => panic!("{entry}: completed with {out}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn syntax(src: &str) {
|
||||
assert!(parse_module(src, &Options::default()).is_err(), "{src}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_reads_the_exporting_binding_each_time() {
|
||||
let counter = "export let count = 0; export function inc() { count++; }";
|
||||
let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]);
|
||||
assert_eq!(out, "0|2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_can_be_renamed_and_combined() {
|
||||
let m = "export default 'd'; export var a = 1; export const b = 2;";
|
||||
let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|2");
|
||||
let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "d|1|d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destructuring_declaration_exports_every_name_it_binds() {
|
||||
let m = "export const { a, b: [c, ...d] } = { a: 1, b: [2, 3, 4] }; export var [e = 5] = [];";
|
||||
let out = run("import { a, c, d, e } from './m.mjs'; out.push(a, c, d.join('+'), e);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "1|2|3+4|5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_exports_of_expressions_and_functions() {
|
||||
let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]);
|
||||
assert_eq!(out, "42");
|
||||
let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]);
|
||||
assert_eq!(out, "anon");
|
||||
// A named default function is a declaration: hoisted, and its name is bound in the module.
|
||||
let f = "out.push(typeof g); export default function g() { return 'g'; }";
|
||||
let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]);
|
||||
assert_eq!(out, "function|g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() {
|
||||
let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null);
|
||||
try { ns.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { ns.added = 5; } catch (e) { out.push(e.name); }
|
||||
try { delete ns.alpha; } catch (e) { out.push(e.name); }
|
||||
out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() {
|
||||
let m = "export var alpha = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
var o = Object.create(ns);
|
||||
Object.defineProperty(o, 'own', { value: 1, writable: true });
|
||||
o.own = 2;
|
||||
try { o.alpha = 5; } catch (e) { out.push(e.name); }
|
||||
try { o.fresh = 5; } catch (e) { out.push(e.name); }
|
||||
try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); }
|
||||
out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1");
|
||||
// A script's sloppy write is ignored.
|
||||
let mut realm = es();
|
||||
let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default());
|
||||
assert_eq!(out, (Ok(JsValue::Undefined), String::new()));
|
||||
// A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`.
|
||||
let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \
|
||||
[own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()";
|
||||
assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_takes_only_definitions_that_change_nothing() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run(
|
||||
"import * as ns from './m.mjs';
|
||||
out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns));
|
||||
out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns);
|
||||
var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }];
|
||||
for (var i = 0; i < ds.length; i++) {
|
||||
try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); }
|
||||
}
|
||||
try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); }
|
||||
try { Object.freeze(ns); } catch (e) { out.push(e.name); }
|
||||
out.push(ns.a);",
|
||||
&[("./m.mjs", m)],
|
||||
);
|
||||
assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_reads_live_values() {
|
||||
let m = "export var n = 1; export function bump() { n = n + 1; }";
|
||||
let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_to_an_import_is_a_type_error() {
|
||||
let m = "export var a = 1;";
|
||||
let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError|1");
|
||||
let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]);
|
||||
assert_eq!(out, "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_of_two_modules_runs_each_once_dependency_first() {
|
||||
// main imports b, b imports main back: b runs first and sees main's hoisted function.
|
||||
let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';";
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./b.mjs", b), ("main", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) }
|
||||
};
|
||||
let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);";
|
||||
let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_an_import_before_its_module_ran_is_a_reference_error() {
|
||||
let b = "import { a } from 'main'; out.push('b'); out.push(a);";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
match r {
|
||||
Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() {
|
||||
let b = "import * as ns from 'main';
|
||||
var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'),
|
||||
() => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns),
|
||||
() => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns),
|
||||
() => Object.create(ns).a, () => Object.create(Object.create(ns)).a];
|
||||
tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } });
|
||||
// Listing the export names reads none of them.
|
||||
var names = [];
|
||||
for (var k in ns) names.push(k);
|
||||
out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());";
|
||||
let mut realm = es();
|
||||
let mut inner = loader(&[("./b.mjs", b)]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) }
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
let errors = "ReferenceError|".repeat(13);
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_two_modules_import_runs_once() {
|
||||
let shared = "out.push('shared'); export var s = 1;";
|
||||
let a = "import { s } from './shared.mjs'; out.push('a' + s);";
|
||||
let b = "import { s } from './shared.mjs'; out.push('b' + s);";
|
||||
let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]);
|
||||
assert_eq!(out, "shared|a1|b1|main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn re_exports_pass_names_on() {
|
||||
let base = "export var x = 1, y = 2; export default 'base';";
|
||||
let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';";
|
||||
let out = run(
|
||||
"import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));",
|
||||
&[("./base.mjs", base), ("./mid.mjs", mid)],
|
||||
);
|
||||
// `export *` does not pass `default` on.
|
||||
assert_eq!(out, "1|1|2|base|all,renamed,x,y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_import_is_a_re_export() {
|
||||
let base = "export var v = 'v';";
|
||||
let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };";
|
||||
let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]);
|
||||
assert_eq!(out, "v|v");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_two_stars_give_is_ambiguous() {
|
||||
let files =
|
||||
[("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")];
|
||||
fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", "");
|
||||
// The namespace leaves the name out.
|
||||
let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files);
|
||||
assert_eq!(out, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_export_ends_the_run_before_any_module_runs() {
|
||||
let files = [("./m.mjs", "out.push('m'); export var a = 1;")];
|
||||
let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", "");
|
||||
assert_eq!((e.line, e.column), (1, 10));
|
||||
let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")];
|
||||
fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_loader_cannot_give_is_named_in_the_error() {
|
||||
let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", "");
|
||||
assert_eq!(e.line, 2);
|
||||
fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_syntax_error_in_an_imported_module_names_its_source() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]);
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load);
|
||||
let e = r.err().unwrap_or_else(|| panic!("ran"));
|
||||
assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2));
|
||||
// The entry is source 0, then each module in the order it was loaded.
|
||||
assert_eq!(realm.error_source(), 2);
|
||||
assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_code_is_strict_and_its_this_is_undefined() {
|
||||
let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]);
|
||||
assert_eq!(out, "true|true|ReferenceError");
|
||||
// Its declarations stay in the module.
|
||||
let mut realm = es();
|
||||
let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default());
|
||||
assert_eq!(r, Ok(JsValue::Undefined));
|
||||
assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() {
|
||||
let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")];
|
||||
fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_count_and_import_depth_are_limited() {
|
||||
let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")];
|
||||
let mut realm = es();
|
||||
let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}");
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() {
|
||||
let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")];
|
||||
let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 });
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_limit_of_zero_runs_no_module() {
|
||||
let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 });
|
||||
assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}");
|
||||
assert_eq!(out, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_is_held_to_the_fuel_limit() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() });
|
||||
let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]);
|
||||
let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() {
|
||||
let mut realm = es();
|
||||
let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]);
|
||||
let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');";
|
||||
assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(()));
|
||||
let mut slices = 0;
|
||||
loop {
|
||||
match realm.advance(10) {
|
||||
Ok(Progress::Paused) => slices += 1,
|
||||
Ok(Progress::Done(v)) => {
|
||||
assert_eq!(v, JsValue::Undefined);
|
||||
break;
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(slices > 20, "{slices}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_es5_realm_runs_no_module() {
|
||||
let mut realm = Realm::new();
|
||||
let mut load = loader(&[]);
|
||||
let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load);
|
||||
assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_does_not_read_import_or_export() {
|
||||
for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] {
|
||||
assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}");
|
||||
assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_early_errors() {
|
||||
for src in [
|
||||
"export var a; export { a };",
|
||||
"export { undeclared };",
|
||||
"export default 1; export default 2;",
|
||||
"import { a } from './x.mjs'; var a;",
|
||||
"var a; import a from './x.mjs';",
|
||||
"import { a, a } from './x.mjs';",
|
||||
"function f() { import a from './x.mjs'; }",
|
||||
"{ export var a; }",
|
||||
"import { default } from './x.mjs';",
|
||||
"export { default };",
|
||||
"import a from x;",
|
||||
"import * from './x.mjs';",
|
||||
"with (a) {}",
|
||||
"export default class {}",
|
||||
"import('./x.mjs');",
|
||||
"#include 'x.js'\n",
|
||||
// Top-level functions are lexical declarations in a module.
|
||||
"function f() {} function f() {}",
|
||||
"var f; function f() {}",
|
||||
"function f() {} var f;",
|
||||
"let f; function f() {}",
|
||||
] {
|
||||
syntax(src);
|
||||
}
|
||||
for src in [
|
||||
"import { default as d, if as i } from './x.mjs'; export { d as default, i as if };",
|
||||
"import {} from './x.mjs'; export {};",
|
||||
"export function f() {} export { f as g };",
|
||||
"var as = 1, from = 2; export { as, from };",
|
||||
"export * as default from './x.mjs';",
|
||||
"function f() {} { function f() {} } function g() { var g; function h() {} var h; }",
|
||||
] {
|
||||
assert!(parse_module(src, &Options::default()).is_ok(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_lists_what_it_imports_and_exports() {
|
||||
let (_, info) =
|
||||
match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default())
|
||||
{
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect();
|
||||
assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]);
|
||||
assert_eq!(info.imports.len(), 2);
|
||||
assert!(
|
||||
matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() {
|
||||
let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';";
|
||||
let (_, info) = match parse_module(src, &Options::default()) {
|
||||
Ok(p) => p,
|
||||
Err(e) => panic!("{e:?}"),
|
||||
};
|
||||
let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect();
|
||||
let dot = [u16::from(b'.'), u16::from(b'/')];
|
||||
let ext: Vec<u16> = ".mjs".encode_utf16().collect();
|
||||
let with = |u: u16| [&dot[..], &[u], &ext[..]].concat();
|
||||
assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]);
|
||||
assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs");
|
||||
// The run stops when the module is to be loaded, before any module runs, and the loader is
|
||||
// not asked for it.
|
||||
let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", "");
|
||||
assert_eq!(e.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_namespace_of_many_exports_lists_each_once_in_order() {
|
||||
let names: Vec<String> = (0..3000).rev().map(|i| format!("e{i}")).collect();
|
||||
let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect();
|
||||
let star = "export * from './m.mjs'; export var e5 = 'own';";
|
||||
let out = run(
|
||||
"import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);",
|
||||
&[("./m.mjs", m.as_str()), ("./star.mjs", star)],
|
||||
);
|
||||
assert_eq!(out, "3000|e0|e999|own|e2999");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modules_survive_a_collection_while_they_link() {
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() });
|
||||
assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok());
|
||||
let m = "export var v = 'kept'; export function f() { return v; }";
|
||||
let mut load = loader(&[("./m.mjs", m)]);
|
||||
// A collection runs at every heap reservation while the modules load and link, before any
|
||||
// of their code runs.
|
||||
let before = realm.interp().heap.collections;
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let started = realm.start_module(
|
||||
"main.mjs",
|
||||
"import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());",
|
||||
ModuleLimits::default(),
|
||||
&mut load,
|
||||
);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(started, Ok(()));
|
||||
assert!(realm.interp().heap.collections > before);
|
||||
assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined))));
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_heap_counts_each_module_from_when_it_loads() {
|
||||
// Each module holds about 4 MB of code (its text and its string). The heap holds one of them,
|
||||
// and not two, so the run stops while the second loads and never asks for the third.
|
||||
let body = format!("export var v = '{}';", "x".repeat(1_000_000));
|
||||
let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() };
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
assert!(realm.run("var out = [];").is_ok());
|
||||
let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default());
|
||||
assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string()));
|
||||
let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits());
|
||||
let asked = std::cell::RefCell::new(Vec::new());
|
||||
let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]);
|
||||
let mut load = |referrer: &str, specifier: &str| {
|
||||
asked.borrow_mut().push(specifier.to_string());
|
||||
inner(referrer, specifier)
|
||||
};
|
||||
let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}");
|
||||
assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_keeps_no_expression_value_alive_after_its_statement() {
|
||||
// The heap holds one of these arrays and not two, so each must be collectable once the
|
||||
// expression statement that made it ends.
|
||||
let big = "function big() { var a = []; for (var i = 0; i < 50000; i++) a[i] = { i: i }; return a; }";
|
||||
let mut realm = es();
|
||||
assert!(realm.run(&format!("{big} var held = big();")).is_ok());
|
||||
let with_one = realm.collect_garbage();
|
||||
assert!(realm.run("held = null;").is_ok());
|
||||
let without = realm.collect_garbage();
|
||||
let one = with_one - without;
|
||||
realm.set_limits(Limits { heap_bytes: without + one * 3 / 2, ..Limits::default() });
|
||||
let entry = format!("{big} big(); big(); try {{ big(); }} finally {{ big(); }} out.push('done');");
|
||||
let (r, out) = run_with(&mut realm, &entry, &[], ModuleLimits::default());
|
||||
assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "done"));
|
||||
// Script and eval code still complete with the value of their last expression statement.
|
||||
assert_eq!(realm.run("1; 2;"), Ok(JsValue::Number(2.0)));
|
||||
assert_eq!(realm.run("eval('3; 4;')"), Ok(JsValue::Number(4.0)));
|
||||
assert_eq!(realm.run("try { 5; } finally { 6; }"), Ok(JsValue::Number(5.0)));
|
||||
}
|
||||
+41
-10
@@ -7,6 +7,7 @@
|
||||
//! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long
|
||||
//! runs of them do not nest at all.
|
||||
|
||||
mod module;
|
||||
mod pattern;
|
||||
mod xml;
|
||||
|
||||
@@ -68,14 +69,23 @@ struct Scope {
|
||||
|
||||
/// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1,
|
||||
/// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct SuperRules {
|
||||
/// Eval code run by a direct `eval` has the rules of the code that calls it (section 18.2.1.1).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct SuperRules {
|
||||
/// `super.property` and `super[index]`: in a class's methods, accessors and constructor.
|
||||
property: bool,
|
||||
pub(crate) property: bool,
|
||||
/// `super(arguments)`: in a derived class's constructor.
|
||||
call: bool,
|
||||
pub(crate) call: bool,
|
||||
/// `new.target`: in any function other than an arrow function at the top of a script.
|
||||
new_target: bool,
|
||||
pub(crate) new_target: bool,
|
||||
}
|
||||
|
||||
impl SuperRules {
|
||||
/// The rules in the body of a function that is not an arrow function: `home` for one with a
|
||||
/// home object, `derived` for a derived class's constructor.
|
||||
pub(crate) fn function(home: bool, derived: bool) -> Self {
|
||||
Self { property: home, call: derived, new_target: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of a function as they are read: names or patterns, each one's default value,
|
||||
@@ -125,6 +135,9 @@ pub(crate) struct Parser<'s> {
|
||||
scopes: Vec<Scope>,
|
||||
/// What `super` and `new.target` may do in the function being read.
|
||||
supers: SuperRules,
|
||||
/// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical
|
||||
/// declarations (ECMA-262 2015 section 15.2.1.11).
|
||||
module: bool,
|
||||
/// Where each shorthand property with an initializer (`{a = 1}`) not yet read as part of a
|
||||
/// destructuring pattern starts; one left when its expression ends is a `SyntaxError`.
|
||||
cover_inits: Vec<u32>,
|
||||
@@ -166,6 +179,7 @@ impl<'s> Parser<'s> {
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
supers: SuperRules::default(),
|
||||
module: false,
|
||||
cover_inits: Vec::new(),
|
||||
cover_ok: false,
|
||||
rest_commas: HashSet::new(),
|
||||
@@ -176,9 +190,12 @@ impl<'s> Parser<'s> {
|
||||
Ok(parser)
|
||||
}
|
||||
|
||||
/// Allows `new.target` at the top of the source: eval code run inside a function.
|
||||
pub(crate) fn with_new_target(mut self) -> Self {
|
||||
self.supers.new_target = self.es2015;
|
||||
/// Reads the top of the source with `rules`: eval code run by a direct `eval` inside a
|
||||
/// function. Without [`crate::Options::es2015`] the rules stay the default.
|
||||
pub(crate) fn with_supers(mut self, rules: SuperRules) -> Self {
|
||||
if self.es2015 {
|
||||
self.supers = rules;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -190,7 +207,15 @@ impl<'s> Parser<'s> {
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 };
|
||||
let program = Program {
|
||||
ast: self.ast,
|
||||
body,
|
||||
strict: self.ctx.strict,
|
||||
directives: self.directives,
|
||||
lines: self.lines,
|
||||
es2015: self.es2015,
|
||||
supers: self.supers,
|
||||
};
|
||||
Ok((program, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -312,6 +337,9 @@ impl<'s> Parser<'s> {
|
||||
/// Checks a name used as an identifier: not a reserved word written with escapes, and not a
|
||||
/// strict-mode reserved word in strict code.
|
||||
fn check_identifier(&self, token: &Token, name: &str) -> Result<()> {
|
||||
if self.module && name == "await" {
|
||||
return Err(self.error_at_token(token, "'await' is a reserved word in modules"));
|
||||
}
|
||||
if token.escaped && Keyword::from_word(name).is_some() {
|
||||
return Err(self.error_at_token(token, format!("keyword '{name}' must not contain escaped characters")));
|
||||
}
|
||||
@@ -411,6 +439,9 @@ impl<'s> Parser<'s> {
|
||||
/// body or the script, lexical in a block.
|
||||
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
|
||||
let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) };
|
||||
if self.module && self.scopes.len() == 1 {
|
||||
return self.declare_lexical(&name, true);
|
||||
}
|
||||
match self.scopes.last_mut() {
|
||||
Some(scope) if scope.function => {
|
||||
if scope.lexical.contains_key(&name.name) {
|
||||
@@ -1149,7 +1180,7 @@ impl<'s> Parser<'s> {
|
||||
generator: bool,
|
||||
) -> Result<crate::ast::FunctionId> {
|
||||
self.enter()?;
|
||||
let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true };
|
||||
let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor);
|
||||
let outer = std::mem::replace(&mut self.supers, rules);
|
||||
// The parameters are read with the function's own `yield` rule, not the enclosing code's.
|
||||
let outer_generator = std::mem::replace(&mut self.ctx.generator, generator);
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a
|
||||
//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1).
|
||||
//!
|
||||
//! A module is strict mode code throughout. An import binds its names as lexical declarations at
|
||||
//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name
|
||||
//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an
|
||||
//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be
|
||||
//! exported once, and a name an `export { … }` list exports from the module itself must be one it
|
||||
//! declares or imports.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Parser, Result, describe};
|
||||
use crate::ast::{
|
||||
Binding, DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId,
|
||||
VarDecl,
|
||||
};
|
||||
use crate::token::{Keyword, Punct, Span, Token, TokenKind};
|
||||
|
||||
/// A name an `export { … }` list without `from` exports: the module's own binding (or import)
|
||||
/// `local`, exported as `export_name`.
|
||||
struct ClauseExport {
|
||||
export_name: String,
|
||||
local: String,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct RequestUnits(Vec<u16>);
|
||||
|
||||
impl std::hash::Hash for RequestUnits {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(&self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RequestUnits {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq)]
|
||||
struct ImportLocal<'a>(&'a str);
|
||||
|
||||
impl std::hash::Hash for ImportLocal<'_> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::hash::Hash::hash(self.0, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ImportLocal<'_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static REQUEST_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static EXPORT_SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
/// Reads the source as a module: its statements, without its import and export declarations
|
||||
/// but with the declarations they export, and what it imports and exports.
|
||||
pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec<Token>)> {
|
||||
self.module = true;
|
||||
#[cfg(test)]
|
||||
REQUEST_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut info = ModuleInfo::default();
|
||||
let mut requests = HashMap::new();
|
||||
let mut clause = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
while self.tok.kind != TokenKind::Eof {
|
||||
if self.at_keyword(Keyword::Import) {
|
||||
self.import_declaration(&mut info, &mut requests)?;
|
||||
} else if self.at_keyword(Keyword::Export) {
|
||||
if let Some(stmt) = self.export_declaration(&mut info, &mut clause, &mut requests)? {
|
||||
body.push(stmt);
|
||||
}
|
||||
} else {
|
||||
body.push(self.parse_statement_item()?);
|
||||
}
|
||||
}
|
||||
self.finish_exports(&mut info, clause)?;
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program =
|
||||
Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015, supers: self.supers };
|
||||
Ok((program, info, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// The current token is the contextual keyword `word` (`as` or `from`), written without escapes.
|
||||
fn at_contextual(&self, word: &str) -> bool {
|
||||
self.tok.ident() == Some(word) && !self.tok.escaped
|
||||
}
|
||||
|
||||
fn expect_contextual(&mut self, word: &str) -> Result<()> {
|
||||
if self.at_contextual(word) {
|
||||
self.bump()?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok))))
|
||||
}
|
||||
|
||||
/// A module specifier: a string literal, added to the module's requests once. → its index.
|
||||
/// Any string value is a specifier here; the host decides which it can load.
|
||||
fn module_specifier(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<usize> {
|
||||
let TokenKind::String(units) = &self.tok.kind else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok))));
|
||||
};
|
||||
if self.tok.legacy_octal {
|
||||
return Err(self.error_at_token(&self.tok, "octal escape sequences are not allowed in strict mode"));
|
||||
}
|
||||
let units = RequestUnits(units.to_vec());
|
||||
let span = self.bump()?.span;
|
||||
if let Some(index) = requests.get(&units) {
|
||||
return Ok(*index);
|
||||
}
|
||||
let specifier = String::from_utf16_lossy(&units.0);
|
||||
let index = info.requests.len();
|
||||
info.requests.push(ModuleRequest { specifier, units: units.0.clone(), span });
|
||||
requests.insert(units, index);
|
||||
Ok(info.requests.len() - 1)
|
||||
}
|
||||
|
||||
/// A name as an import or export list gives it: any identifier name, keywords included. → the
|
||||
/// name and whether it was an identifier (not a keyword).
|
||||
fn list_name(&mut self) -> Result<(Name, bool)> {
|
||||
let Some(name) = self.tok.identifier_name().map(str::to_string) else {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok))));
|
||||
};
|
||||
let ident = matches!(self.tok.kind, TokenKind::Ident(_));
|
||||
let token = self.bump()?;
|
||||
Ok((Name { name, span: token.span }, ident))
|
||||
}
|
||||
|
||||
/// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope.
|
||||
fn import_declaration(&mut self, info: &mut ModuleInfo, requests: &mut HashMap<RequestUnits, usize>) -> Result<()> {
|
||||
let import = self.bump()?;
|
||||
if self.at(Punct::LParen) {
|
||||
return Err(self.error_at_token(&import, "import() is not supported"));
|
||||
}
|
||||
if matches!(self.tok.kind, TokenKind::String(_)) {
|
||||
self.module_specifier(info, requests)?;
|
||||
return self.semicolon();
|
||||
}
|
||||
let mut bound: Vec<(ImportName, Name)> = Vec::new();
|
||||
let mut list = true;
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name("default".into()), local));
|
||||
list = self.eat(Punct::Comma)?;
|
||||
}
|
||||
if list {
|
||||
if self.eat(Punct::Star)? {
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Namespace, local));
|
||||
} else {
|
||||
self.expect(Punct::LBrace)?;
|
||||
while !self.at(Punct::RBrace) {
|
||||
if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() {
|
||||
// A name without `as` binds itself, so it must be one a declaration may bind.
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(local.name.clone()), local));
|
||||
} else {
|
||||
let (imported, _) = self.list_name()?;
|
||||
self.expect_contextual("as")?;
|
||||
let local = self.binding_identifier()?;
|
||||
bound.push((ImportName::Name(imported.name), local));
|
||||
}
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
}
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (import, local) in bound {
|
||||
self.declare_lexical(&local, false)?;
|
||||
info.imports.push(ImportEntry { request, import, local });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The token after the current one is the contextual keyword `as`.
|
||||
fn next_is_as(&self) -> bool {
|
||||
self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as"))
|
||||
}
|
||||
|
||||
/// `export …` (section 15.2.3). → the declaration it exports, which runs in place.
|
||||
fn export_declaration(
|
||||
&mut self,
|
||||
info: &mut ModuleInfo,
|
||||
clause: &mut Vec<ClauseExport>,
|
||||
requests: &mut HashMap<RequestUnits, usize>,
|
||||
) -> Result<Option<StmtId>> {
|
||||
let export = self.bump()?;
|
||||
let span = export.span;
|
||||
if self.eat(Punct::Star)? {
|
||||
if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
let (name, _) = self.list_name()?;
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span });
|
||||
return Ok(None);
|
||||
}
|
||||
self.expect_contextual("from")?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
info.exports.push(ExportEntry::Star { request, span });
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at(Punct::LBrace) {
|
||||
self.bump()?;
|
||||
// Each name: the name it refers to (and whether that was an identifier) and the name it
|
||||
// is exported as.
|
||||
let mut names: Vec<(Name, bool, Name)> = Vec::new();
|
||||
while !self.at(Punct::RBrace) {
|
||||
let (local, ident) = self.list_name()?;
|
||||
let exported = if self.at_contextual("as") {
|
||||
self.bump()?;
|
||||
self.list_name()?.0
|
||||
} else {
|
||||
local.clone()
|
||||
};
|
||||
names.push((local, ident, exported));
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RBrace)?;
|
||||
if self.at_contextual("from") {
|
||||
self.bump()?;
|
||||
let request = self.module_specifier(info, requests)?;
|
||||
self.semicolon()?;
|
||||
for (local, _, exported) in names {
|
||||
let import = ImportName::Name(local.name);
|
||||
info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
self.semicolon()?;
|
||||
for (local, ident, exported) in names {
|
||||
// Without `from`, each name refers to a binding of the module (section 15.2.3.1).
|
||||
if !ident || crate::token::strict_reserved(&local.name) {
|
||||
return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name)));
|
||||
}
|
||||
clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
if self.at_keyword(Keyword::Default) {
|
||||
self.bump()?;
|
||||
return self.export_default(info, span).map(Some);
|
||||
}
|
||||
let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some();
|
||||
if !exportable {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok))));
|
||||
}
|
||||
let stmt = self.parse_statement_item()?;
|
||||
let names: Vec<Name> = match self.ast.stmt(stmt) {
|
||||
Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).collect(),
|
||||
Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(),
|
||||
_ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")),
|
||||
};
|
||||
for name in names {
|
||||
info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span });
|
||||
}
|
||||
Ok(Some(stmt))
|
||||
}
|
||||
|
||||
/// `export default …` after `default`: a function declaration (named or not) or an expression.
|
||||
fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result<StmtId> {
|
||||
if self.at_keyword(Keyword::Class) {
|
||||
return Err(self.error_at_token(&self.tok, "classes are not supported"));
|
||||
}
|
||||
if self.at_keyword(Keyword::Function) {
|
||||
self.enter()?;
|
||||
let result = self.default_function();
|
||||
self.leave();
|
||||
let (stmt, fid, local) = result?;
|
||||
self.declare_function(fid)?;
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span });
|
||||
return Ok(stmt);
|
||||
}
|
||||
let start = self.tok.span;
|
||||
let value = self.parse_assignment(false)?;
|
||||
self.semicolon()?;
|
||||
let target = Binding::Name(Name { name: DEFAULT_BINDING.into(), span: start });
|
||||
let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { target, init: Some(value) }]), self.span_from(start));
|
||||
info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span });
|
||||
Ok(stmt)
|
||||
}
|
||||
|
||||
/// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of
|
||||
/// `name`, or of [`DEFAULT_BINDING`] for a function without one.
|
||||
fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> {
|
||||
let keyword = self.expect_keyword(Keyword::Function)?;
|
||||
let start = keyword.span;
|
||||
let generator = self.es2015 && self.eat(Punct::Star)?;
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) {
|
||||
self.function_name()?
|
||||
} else {
|
||||
(Name { name: DEFAULT_BINDING.into(), span: start }, keyword)
|
||||
};
|
||||
let local = name.0.name.clone();
|
||||
let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?;
|
||||
let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start));
|
||||
Ok((stmt, fid, local))
|
||||
}
|
||||
|
||||
/// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and
|
||||
/// each name an `export { … }` list takes from the module itself declared or imported there. An
|
||||
/// exported named import becomes a re-export of its imported binding (section 15.2.1.16.1).
|
||||
/// A namespace import keeps its local binding.
|
||||
fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec<ClauseExport>) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
EXPORT_SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let mut imports = HashMap::with_capacity(info.imports.len());
|
||||
for import in &info.imports {
|
||||
imports.entry(ImportLocal(&import.local.name)).or_insert(import);
|
||||
}
|
||||
let top = self.scopes.first();
|
||||
for c in clause {
|
||||
let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local));
|
||||
if !declared {
|
||||
return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local)));
|
||||
}
|
||||
let imported = imports.get(&ImportLocal(&c.local));
|
||||
let entry = match imported {
|
||||
Some(i) if matches!(&i.import, ImportName::Name(_)) => {
|
||||
ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }
|
||||
}
|
||||
_ => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span },
|
||||
};
|
||||
info.exports.push(entry);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for e in &info.exports {
|
||||
let (name, span) = match e {
|
||||
ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span),
|
||||
ExportEntry::Star { .. } => continue,
|
||||
};
|
||||
if !seen.insert(name.as_str()) {
|
||||
return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{EXPORT_SEARCH_STEPS, REQUEST_SEARCH_STEPS};
|
||||
use crate::{Options, parse_module};
|
||||
|
||||
fn run_namespace_modules(main: &str, files: &[(&str, &str)]) -> (Result<crate::JsValue, crate::RunError>, crate::Realm) {
|
||||
let mut realm = crate::Realm::with_options(Options { es2015: true, ..Options::default() }, crate::Limits::default());
|
||||
realm.run("var out = [];").unwrap();
|
||||
let mut load = |_: &str, specifier: &str| {
|
||||
files.iter().find(|(name, _)| *name == specifier).map_or_else(
|
||||
|| Err(crate::LoadError::Other(format!("missing module {specifier}"))),
|
||||
|(_, source)| Ok(crate::LoadedModule { key: specifier.into(), source: Some((*source).into()) }),
|
||||
)
|
||||
};
|
||||
let result = realm.run_module("main.mjs", main, crate::ModuleLimits::default(), &mut load);
|
||||
(result, realm)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexport_bindings_keep_their_origin() {
|
||||
let files = [
|
||||
("./a.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./b.mjs", "import * as ns from './shared.mjs'; export {ns};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7;"),
|
||||
];
|
||||
let (result, _) = run_namespace_modules("import {ns} from './barrel.mjs'; out.push(ns.value);", &files);
|
||||
assert!(result.as_ref().is_err_and(|error| error.message.contains("ambiguous")), "{result:?}");
|
||||
let files = [
|
||||
("./a.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./b.mjs", "import {value} from './shared.mjs'; export {value};"),
|
||||
("./barrel.mjs", "export * from './a.mjs'; export * from './b.mjs';"),
|
||||
("./shared.mjs", "export var value = 7; export function change() { value = 9; }"),
|
||||
];
|
||||
let (result, mut realm) =
|
||||
run_namespace_modules("import {value} from './barrel.mjs'; import {change} from './shared.mjs'; change(); out.push(value);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("9".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_reexports_link_through_cycles() {
|
||||
let files = [("./a.mjs", "import * as ns from './b.mjs'; export {ns};"), ("./b.mjs", "import * as ns from './a.mjs'; export {ns};")];
|
||||
let (result, mut realm) = run_namespace_modules("import * as a from './a.mjs'; out.push(a.ns.ns === a);", &files);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_specifiers_reject_legacy_octal_escapes() {
|
||||
for source in
|
||||
[r"import './\141.mjs';", r"import value from './\141.mjs';", r"export * from './\141.mjs';", r"export { value } from './\141.mjs';"]
|
||||
{
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
for source in [r"import './\u0061.mjs';", r"export * from './\x61.mjs';", r"import './\uD800.mjs';"] {
|
||||
assert!(parse_module(source, &Options::default()).is_ok(), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_request_search_work_is_bounded_by_request_count() {
|
||||
let count = 1_000;
|
||||
let mut source = String::new();
|
||||
for index in 0..count {
|
||||
source.push_str(&format!("import './{index}.mjs';"));
|
||||
}
|
||||
source.push_str(r"import './\u0030.mjs'; import './\uD800.mjs'; import './\uFFFD.mjs'; import './\uDC00.mjs'; import './\uD800.mjs';");
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.requests.len(), count + 3);
|
||||
for (index, request) in info.requests.iter().take(count).enumerate() {
|
||||
assert_eq!(request.specifier, format!("./{index}.mjs"));
|
||||
}
|
||||
assert_eq!(info.requests[count].units[2], 0xD800);
|
||||
assert_eq!(info.requests[count + 1].units[2], 0xFFFD);
|
||||
assert_eq!(info.requests[count + 2].units[2], 0xDC00);
|
||||
let steps = REQUEST_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0, "the repeated requests compare their exact UTF-16 keys");
|
||||
assert!(steps <= 2 * (count + 5), "{steps} request-search steps for {} requests", count + 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_export_resolution_work_is_bounded_by_binding_count() {
|
||||
let count = 1_000;
|
||||
let bindings = (0..count).map(|index| format!("value as local{index}")).collect::<Vec<_>>().join(",");
|
||||
let exports = (0..count).map(|index| format!("local{index} as exported{index}")).collect::<Vec<_>>().join(",");
|
||||
let source = format!(
|
||||
"import {{{bindings}}} from './values.mjs'; import * as ns from './namespace.mjs'; export {{{exports},ns as namespace,local0 as again}};"
|
||||
);
|
||||
let (_, info) = match parse_module(&source, &Options::default()) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => panic!("{error:?}"),
|
||||
};
|
||||
assert_eq!(info.imports.len(), count + 1);
|
||||
assert_eq!(info.exports.len(), count + 2);
|
||||
for (index, export) in info.exports.iter().take(count).enumerate() {
|
||||
assert!(matches!(export, crate::ExportEntry::Indirect { export_name, request: 0, import: crate::ast::ImportName::Name(name), .. }
|
||||
if export_name == &format!("exported{index}") && name == "value"));
|
||||
}
|
||||
assert!(matches!(&info.exports[count], crate::ExportEntry::Local { export_name, local, .. } if export_name == "namespace" && local == "ns"));
|
||||
assert!(
|
||||
matches!(&info.exports[count + 1], crate::ExportEntry::Indirect { request: 0, import: crate::ast::ImportName::Name(name), .. } if name == "value")
|
||||
);
|
||||
let steps = EXPORT_SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
assert!(steps > 0);
|
||||
assert!(steps <= 3 * (count + 2), "{steps} import-local comparisons for {} exports", count + 2);
|
||||
for source in [
|
||||
"import {value as x} from './values.mjs'; export {x,x};",
|
||||
"import {value as x} from './values.mjs'; import * as x from './namespace.mjs';",
|
||||
] {
|
||||
assert!(parse_module(source, &Options::default()).is_err(), "{source}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 315 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user