Merge main into fix/followup-8463-preview-test

This commit is contained in:
dotCooCoo committed 2026-11-25 03:32:31 -08:00
commit 883b54bbe7
136 files changed
+5275 -505

No files matched your search

+9 -2
View File
@@ -257,7 +257,7 @@ All 57 approximated Photoshop-style raster filters are available. The Effect Gal
**What's missing:**
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
- the rest of 3D and Materials (base and Adobe Substance materials, shadows from lights after the first, ray-traced rendering, Turntable; see [docs/three-d.md](docs/three-d.md));
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
- scripting, and the rest of Variables (image and graph kinds, dataset import);
- generative AI features.
@@ -287,7 +287,9 @@ signed and published. Every bundled asset is listed with its licence in [`ASSETS
|---|---|---|
| x64 (64-bit Intel/AMD) | `vectorcraft-<ver>-windows-x64.msi` | `vectorcraft-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `vectorcraft-<ver>-windows-arm64.msi` | `vectorcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `vectorcraft-<ver>-windows-x86.msi` | `vectorcraft-<ver>-windows-x86-portable.zip` |
For 32-bit Windows, [VectorCraft v0.22.0](https://github.com/storytold/vectorcraft/releases/tag/v0.22.0)
was the last release with both an x86 MSI and portable ZIP.
Installers and executables are code-signed.
@@ -306,13 +308,18 @@ Installers and executables are code-signed.
| Flatpak | `vectorcraft-<ver>-linux-x86_64.flatpak` | `vectorcraft-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `vectorcraft-<ver>-linux-x86_64.deb` | `vectorcraft-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `vectorcraft-<ver>-linux-x86_64.rpm` | `vectorcraft-<ver>-linux-aarch64.rpm` | |
| Arch Linux | `vectorcraft-<ver>-linux-x86_64.pkg.tar.zst` | `vectorcraft-<ver>-linux-aarch64.pkg.tar.zst` | |
| Tarball | `vectorcraft-<ver>-linux-x86_64.tar.gz` | `vectorcraft-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64) packages are `vectorcraft-<ver>-linux-riscv64.deb`,
`vectorcraft-<ver>-linux-riscv64.rpm`, and `vectorcraft-<ver>-linux-riscv64.tar.gz`.
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` |
| aarch64 (ARM64) | `vectorcraft-<ver>-freebsd-aarch64.tar.gz` |
### Web (WebAssembly)
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 19.25H21" stroke-width="1.5" /><rect x="6" y="5" width="4.5" height="12" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="10" width="4.5" height="7" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 19.25H21" stroke-width="1.5" /><rect x="6" y="5" width="4.5" height="12" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="10" width="4.5" height="7" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 427 B

After

Width:  |  Height:  |  Size: 427 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 3V21M3 12H21" stroke-width="1.5" /><rect x="6.5" y="6.5" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 3V21M3 12H21" stroke-width="1.5" /><rect x="6.5" y="6.5" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 336 B

After

Width:  |  Height:  |  Size: 336 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 3V21" stroke-width="1.5" /><rect x="5" y="6" width="14" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="8" y="13.5" width="8" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M12 3V21" stroke-width="1.5" /><rect x="5" y="6" width="14" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="8" y="13.5" width="8" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 423 B

After

Width:  |  Height:  |  Size: 423 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4.75 3V21" stroke-width="1.5" /><rect x="7" y="6" width="12" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="7" y="13.5" width="7" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4.75 3V21" stroke-width="1.5" /><rect x="7" y="6" width="12" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="7" y="13.5" width="7" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M19.25 3V21" stroke-width="1.5" /><rect x="5" y="6" width="12" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10" y="13.5" width="7" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M19.25 3V21" stroke-width="1.5" /><rect x="5" y="6" width="12" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10" y="13.5" width="7" height="4.5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 427 B

After

Width:  |  Height:  |  Size: 427 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 4.75H21" stroke-width="1.5" /><rect x="6" y="7" width="4.5" height="12" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="7" width="4.5" height="7" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 4.75H21" stroke-width="1.5" /><rect x="6" y="7" width="4.5" height="12" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="7" width="4.5" height="7" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H21" stroke-width="1.5" /><rect x="6" y="5" width="4.5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="8" width="4.5" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 12H21" stroke-width="1.5" /><rect x="6" y="5" width="4.5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="8" width="4.5" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 423 B

After

Width:  |  Height:  |  Size: 423 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M7 5H14L18 9V19H7Z" fill="currentColor" fill-opacity="0.85" stroke="none"/><path d="M4 2V6M2 4H6" stroke-width="1.25" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M7 5H14L18 9V19H7Z" fill="currentColor" fill-opacity="0.85" stroke="none"/><path d="M4 2V6M2 4H6" stroke-width="1.25" /></svg>

Before

Width:  |  Height:  |  Size: 318 B

After

Width:  |  Height:  |  Size: 318 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="5" y="5" width="14" height="14" stroke-width="1.25" stroke-dasharray="2 2"/><rect x="9" y="9" width="8" height="8" stroke-width="2.5" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="5" y="5" width="14" height="14" stroke-width="1.25" stroke-dasharray="2 2"/><rect x="9" y="9" width="8" height="8" stroke-width="2.5" /></svg>

Before

Width:  |  Height:  |  Size: 334 B

After

Width:  |  Height:  |  Size: 334 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="5" y="5" width="14" height="14" stroke-width="1.25" stroke-dasharray="2 2"/><rect x="3.5" y="3.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="17.5" y="3.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="3.5" y="17.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="17.5" y="17.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="5" y="5" width="14" height="14" stroke-width="1.25" stroke-dasharray="2 2"/><rect x="3.5" y="3.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="17.5" y="3.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="3.5" y="17.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="17.5" y="17.5" width="3" height="3" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 666 B

After

Width:  |  Height:  |  Size: 666 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 9.25H21" stroke-width="1.5" /><path d="M3 19.25H21" stroke-width="1.5" /><rect x="7" y="4.5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="13.5" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 9.25H21" stroke-width="1.5" /><path d="M3 19.25H21" stroke-width="1.5" /><rect x="7" y="4.5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="13.5" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 467 B

After

Width:  |  Height:  |  Size: 467 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M7 3V21" stroke-width="1.5" /><path d="M16.5 3V21" stroke-width="1.5" /><rect x="5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="14" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M7 3V21" stroke-width="1.5" /><path d="M16.5 3V21" stroke-width="1.5" /><rect x="5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="14" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 459 B

After

Width:  |  Height:  |  Size: 459 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="6" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="16" y="6" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M9.5 3H14.5" stroke-width="1.25" /><path d="M9.5 2V4M14.5 2V4" stroke-width="1.25" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="6" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="16" y="6" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M9.5 3H14.5" stroke-width="1.25" /><path d="M9.5 2V4M14.5 2V4" stroke-width="1.25" /></svg>

Before

Width:  |  Height:  |  Size: 472 B

After

Width:  |  Height:  |  Size: 472 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4.75 3V21" stroke-width="1.5" /><path d="M13.75 3V21" stroke-width="1.5" /><rect x="5.5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="14.5" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4.75 3V21" stroke-width="1.5" /><path d="M13.75 3V21" stroke-width="1.5" /><rect x="5.5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="14.5" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 467 B

After

Width:  |  Height:  |  Size: 467 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M9.25 3V21" stroke-width="1.5" /><path d="M19.25 3V21" stroke-width="1.5" /><rect x="4.5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M9.25 3V21" stroke-width="1.5" /><path d="M19.25 3V21" stroke-width="1.5" /><rect x="4.5" y="7" width="4" height="10" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="13.5" y="5" width="5" height="14" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 467 B

After

Width:  |  Height:  |  Size: 467 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 4.75H21" stroke-width="1.5" /><path d="M3 13.75H21" stroke-width="1.5" /><rect x="7" y="5.5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="14.5" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 4.75H21" stroke-width="1.5" /><path d="M3 13.75H21" stroke-width="1.5" /><rect x="7" y="5.5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="14.5" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 467 B

After

Width:  |  Height:  |  Size: 467 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 7H21" stroke-width="1.5" /><path d="M3 16.5H21" stroke-width="1.5" /><rect x="7" y="5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="14" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 7H21" stroke-width="1.5" /><path d="M3 16.5H21" stroke-width="1.5" /><rect x="7" y="5" width="10" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="5" y="14" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 459 B

After

Width:  |  Height:  |  Size: 459 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="6" y="3" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="6" y="16" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M3 9.5V14.5" stroke-width="1.25" /><path d="M2 9.5H4M2 14.5H4" stroke-width="1.25" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="6" y="3" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="6" y="16" width="14" height="5" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M3 9.5V14.5" stroke-width="1.25" /><path d="M2 9.5H4M2 14.5H4" stroke-width="1.25" /></svg>

Before

Width:  |  Height:  |  Size: 472 B

After

Width:  |  Height:  |  Size: 472 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H10V14H3Z" fill="currentColor" fill-opacity="0.2" stroke="none"/><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1.25" /><rect x="10" y="10" width="4" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H10V14H3Z" fill="currentColor" fill-opacity="0.2" stroke="none"/><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1.25" /><rect x="10" y="10" width="4" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 439 B

After

Width:  |  Height:  |  Size: 439 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10.75" y="10.75" width="3.25" height="3.25" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M14.75 10H21V21H10V14.75H14.75Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10.75" y="10.75" width="3.25" height="3.25" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M14.75 10H21V21H10V14.75H14.75Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 480 B

After

Width:  |  Height:  |  Size: 480 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H21V21H10V14H3Z M10 10H14V14H10Z" fill="currentColor" fill-rule="evenodd" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H21V21H10V14H3Z M10 10H14V14H10Z" fill="currentColor" fill-rule="evenodd" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 297 B

After

Width:  |  Height:  |  Size: 297 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.6" y="3.6" width="9.8" height="9.8" stroke-width="1" /><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1" /><rect x="10" y="10" width="4" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.6" y="3.6" width="9.8" height="9.8" stroke-width="1" /><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1" /><rect x="10" y="10" width="4" height="4" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 418 B

After

Width:  |  Height:  |  Size: 418 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10" y="10" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10" y="10" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 374 B

After

Width:  |  Height:  |  Size: 374 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.6" y="3.6" width="9.8" height="9.8" stroke-width="1.25" /><path d="M14 10H21V21H10V14H14Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.6" y="3.6" width="9.8" height="9.8" stroke-width="1.25" /><path d="M14 10H21V21H10V14H14Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 345 B

After

Width:  |  Height:  |  Size: 345 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H10V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1.25" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H10V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><rect x="10.6" y="10.6" width="9.8" height="9.8" stroke-width="1.25" /></svg>

Before

Width:  |  Height:  |  Size: 344 B

After

Width:  |  Height:  |  Size: 344 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.5" y="3.5" width="10" height="10" stroke-width="1" /><rect x="10.5" y="10.5" width="10" height="10" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3.5" y="3.5" width="10" height="10" stroke-width="1" /><rect x="10.5" y="10.5" width="10" height="10" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 319 B

After

Width:  |  Height:  |  Size: 319 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="0.45" stroke="none"/><rect x="10" y="10" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V9.25H9.25V14H3Z" fill="currentColor" fill-opacity="0.45" stroke="none"/><rect x="10" y="10" width="11" height="11" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 375 B

After

Width:  |  Height:  |  Size: 375 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H21V21H10V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="2 2 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 3H14V10H21V21H10V14H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/></svg>

Before

Width:  |  Height:  |  Size: 279 B

After

Width:  |  Height:  |  Size: 279 B

+1 -22
View File
@@ -304,7 +304,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
warn(&mut warnings, PAST_CLASSIC_RANGE);
}
let bytes = match opts.version {
Version::Hpgl => plain(&by_pen),
Version::Hpgl => craft_plotter::hpgl::write::write_hpgl(&by_pen),
Version::Hpgl2 => encoded(&by_pen, &pens),
};
out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes });
@@ -511,27 +511,6 @@ fn inner_first(left: Vec<(usize, Vec<(i64, i64)>)>, outer: &[Vec<usize>], waitin
paths.extend(held.into_iter().flatten());
}
/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`.
fn plain(by_pen: &[Vec<Vec<(i64, i64)>>]) -> Vec<u8> {
let mut s = String::from("IN;");
for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) {
s.push_str(&format!("PU;SP{};", i + 1));
for path in paths {
let Some(((x, y), rest)) = path.split_first() else { continue };
s.push_str(&format!("PU{x},{y};PD"));
for (k, (x, y)) in rest.iter().enumerate() {
if k > 0 {
s.push(',');
}
s.push_str(&format!("{x},{y}"));
}
s.push(';');
}
}
s.push_str("PU;SP0;");
s.into_bytes()
}
/// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`.
fn encoded(by_pen: &[Vec<Vec<(i64, i64)>>], pens: &[[u8; 3]]) -> Vec<u8> {
let pens: Vec<_> = pens.iter().enumerate().map(|(index, &rgb)| craft_plotter::hpgl::write::Pen { number: index + 1, rgb }).collect();
+15
View File
@@ -112,6 +112,21 @@ fn each_new_color_is_the_next_pen_and_pens_draw_in_turn() {
assert!(!text(&table).contains("SP2"), "{}", text(&table));
}
#[test]
fn classic_hpgl_preserves_explicit_pen_gaps_and_path_order() {
let d = doc_with(|d| {
vec![
stroked(d, line((130.0, 70.0), (140.0, 80.0)), Color::rgb8(0, 0, 255)),
stroked(d, line((10.0, 20.0), (20.0, 40.0)), Color::rgb8(255, 0, 0)),
stroked(d, line((80.0, 60.0), (90.0, 70.0)), Color::rgb8(0, 0, 255)),
]
});
let out =
plot(&d, &HpglOptions { version: Version::Hpgl, origin: Origin::Center, pens: vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], ..opts(&d) });
// The empty green pen must leave the two blue paths on pen three.
assert_eq!(out.bytes, b"IN;PU;SP1;PU-1270,423;PD-1129,141;PU;SP3;PU423,-282;PD564,-423;PU-282,-141;PD-141,-282;PU;SP0;");
}
#[test]
fn a_filled_path_is_its_closed_outline_and_a_stroke_its_line() {
let d = doc_with(|d| {
+9 -35
View File
@@ -32,10 +32,9 @@ impl WidthProfile {
/// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous
/// and monotone between points, so it never overshoots them, a point eases into its neighbours
/// instead of making a corner, and moving one reshapes the curve as far as its neighbours'
/// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope
/// from its first two secants, or the secant when it has only two points, so a two-point
/// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still
/// a step: each run either side ends independently at it.
/// neighbours (their slopes depend on it). The ends of a run take the span's own slope, so a
/// two-point profile stays a straight taper. Two points at one `t` are still a step: each run
/// either side ends independently at it.
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
if p.is_empty() {
return (1.0, 1.0);
@@ -263,27 +262,12 @@ impl AngleProfile {
/// How close two width points' positions are to make a step ([`WidthProfile::around`]).
const STEP: f64 = 1e-7;
/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants.
/// A sign change caps the slope, and a slope that turns back on the first secant is flattened.
/// Runs of only two points use their secant instead (see [`tangent`]).
fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 {
let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);
if !m.is_finite() || m * d0 <= 0.0 {
return 0.0;
}
if d0 * d1 < 0.0 {
return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) };
}
m
}
/// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in
/// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where
/// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the
/// slopes of the spans on either side elsewhere (never more than three times either, so no span
/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their
/// secant when the run has only two points; a step ends the run on each side, so the points either
/// side of it do not see across it.
/// overshoots its points). The ends of a run take their secant; a step ends the run on each
/// side, so the points either side of it do not see across it.
fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 {
let Some(q) = p.get(j) else { return 0.0 };
let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP);
@@ -298,18 +282,8 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f
let (h0, h1) = (q.0 - a.0, b.0 - q.0);
3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1)
}
// The end of a run: its previous two points set a one-sided three-point slope, or its
// secant when the run has only two points (the point before `a` is on the other side of a
// step, or does not exist).
(Some(a), None) => {
let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) };
end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a))
}
// The start of a run, symmetrically.
(None, Some(b)) => {
let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) };
end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next))
}
(Some(a), None) => slope(a, q),
(None, Some(b)) => slope(q, b),
(None, None) => 0.0,
}
}
@@ -464,12 +438,12 @@ mod tests {
#[test]
fn widths_run_smoothly_through_width_points() {
// A swell in the middle: flat at its widest, and a quarter of the way along above the
// straight ramp from 1 to 3 (2) because the end eases out of the first point.
// straight ramp from 1 to 3 (2).
let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] };
let (before, after) = slopes(&swell, 0.5);
assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}");
let (l, r) = swell.at(0.25);
assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}");
assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}");
// Rising on both sides of a point: the slope is the same either side of it.
let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] };
let (before, after) = slopes(&rise, 0.3);
+7 -7
View File
@@ -221,9 +221,9 @@ fn strokes_without_pressure_round_trip_unchanged() {
fn profile_interp() {
let p = WidthProfile::lens();
assert_eq!(p.at(0.5), (1.0, 1.0));
// The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the
// 0.5 a straight taper would give.
assert_eq!(p.at(0.25), (0.75, 0.75));
// Half way up the lens the width curves above the straight ramp (0.5), flattening into its
// widest point.
assert_eq!(p.at(0.25), (0.625, 0.625));
assert_eq!(p.at(2.0), (0.0, 0.0));
}
@@ -259,13 +259,13 @@ fn profile_two_point_runs_are_linear() {
}
}
/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75,
/// above the 0.5 a straight line between its points would give.
/// The lens swells above a straight line between its points: a quarter of the way along it is
/// 0.625, easing flat into its widest point rather than rising at a constant rate.
#[test]
fn profile_lens_is_convex() {
let p = WidthProfile::lens();
assert!((p.at(0.25).0 - 0.75).abs() < 1e-12);
assert!((p.at(0.75).0 - 0.75).abs() < 1e-12);
assert!((p.at(0.25).0 - 0.625).abs() < 1e-12);
assert!((p.at(0.75).0 - 0.625).abs() < 1e-12);
for k in 1..25 {
let t = k as f64 / 100.0;
assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0);
+3 -2
View File
@@ -23,8 +23,9 @@ pub struct Selection {
/// `objects` with no entry here is fully selected; `segments` distinguishes segment picks.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub anchors: BTreeMap<NodeId, BTreeSet<AnchorRef>>,
/// Explicitly selected segments. Their endpoints in `anchors` move with them, but are not
/// selected anchor points: Delete cuts connections and their anchor squares stay hollow.
/// Explicitly selected segments. Their endpoints in `anchors` move with them (the arrow keys
/// bend a curved one instead), but are not selected anchor points: Delete cuts connections and
/// their anchor squares stay hollow.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub segments: BTreeMap<NodeId, BTreeSet<SegmentRef>>,
/// Key object for Align, one object of a selection of two or more. [`Selection::prune`] clears
+6 -4
View File
@@ -232,14 +232,16 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() {
let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3);
assert!(near(plain.area().abs(), 1000.0, 1e-6));
let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3);
// The lens is a parabola between its ends: 2/3 of the full-width band.
assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1));
// Each dash takes its widths from where it sits along the lens (0 → 1 → 0).
// The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714).
assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05));
// Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens
// rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers
// its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192.
let st = stroke(10.0, |s| {
s.profile = Some(WidthProfile::lens());
s.dash = Some(dashed(&[25.0, 25.0], 0.0));
});
assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1));
assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05));
assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty());
}
+3 -4
View File
@@ -169,10 +169,9 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() {
s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false });
});
let o = line_outline(&line(100.0), &st, 10.0, 1e-3);
// The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip,
// where the smooth profile is thinner than a straight ramp (a parabola's first tenth).
// The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip.
assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide");
assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin");
assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin");
assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty");
// Dots too: a round dot near the middle is bigger than one near an end.
let st = stroke(10.0, |s| {
@@ -181,7 +180,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() {
s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false });
});
let o = line_outline(&line(100.0), &st, 10.0, 1e-3);
assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0)));
assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5)));
}
/// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0).
+3 -2
View File
@@ -138,8 +138,9 @@ fn across_runs_from_the_left_edge_to_the_right() {
let mut lens = st.clone();
lens.profile = Some(WidthProfile::lens());
let sl = slices(&line, &lens);
// A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up.
assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05);
// A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is
// 3.125 up.
assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05);
assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02);
}
+155 -51
View File
@@ -53,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil
kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1));
}
if kept.iter().all(|v| *v) {
ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64);
ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0));
continue;
}
cut = true;
@@ -78,14 +78,14 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil
} else if let Some(part) = run.take()
&& part.pts.len() > 1
{
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64);
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total));
}
walked += lengths[i];
}
if let Some(part) = run
&& part.pts.len() > 1
{
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64);
ctx.subpath(&mut out, &part, &segs, false, (from, walked / total));
}
}
cut.then_some(out)
@@ -102,8 +102,7 @@ pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, prof
let flat = flatten(&segs, closed, ctx.tol);
if flat.pts.len() > 1 {
let span = spans.get(i).copied().unwrap_or((0.0, 1.0));
let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1);
ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0));
ctx.subpath(&mut out, &flat, &segs, closed, span);
}
}
out
@@ -215,25 +214,17 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat {
/// Insert samples where the profile has width points and between them, so its smooth curve is
/// drawn as a smooth outline along straight runs too (the two points of a discontinuous point
/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]).
fn densify(
flat: &Flat,
segs: &[PathSeg],
closed: bool,
profile: &WidthProfile,
span: (f64, f64),
density: f64,
) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {
// Two samples per profile segment: the segment end plus its midpoint. The outline is fitted
// with cubics through these points, so a smooth width curve needs far fewer samples than it
// did when every pair of samples became a separate cubic. A profile with a strong bend gets
// one more subdivision; a flat profile draws the same straight pieces as before.
/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]); `bend` is
/// the gap (in width factor) the straight line between samples may leave the curve, the outline
/// tolerance turned into the profile's units (see [`adaptive_samples`]).
fn densify(flat: &Flat, segs: &[PathSeg], closed: bool, profile: &WidthProfile, span: (f64, f64), bend: f64) -> (Vec<Point>, Vec<bool>, Vec<Vec2>) {
// Start at a midpoint per profile segment: the fit through those keeps a gentle taper smooth
// with little path data. A stronger bend measures itself finer (see `adaptive_samples`): the
// straight line between samples must stay within the outline tolerance, as a plain stroke's
// own flattening does, so the profile's shape does not drift from the one a uniform profile
// draws.
const SAMPLES: usize = 2;
const MAX_SAMPLES: usize = 8;
// The gap (in width factor) the straight line between two samples may leave: small enough
// that a sharp peak like the lens' needs one more piece, large enough that a long taper's
// gentle bend does not.
const BEND: f64 = 0.05;
const MAX_SAMPLES: usize = 64;
let total = length(&flat.pts, closed);
let range = span.1 - span.0;
if total <= 1e-12 || range <= 1e-12 {
@@ -250,6 +241,15 @@ fn densify(
// piece the profile's own points are enough; a straight run has only its ends, so it needs
// the extra samples. This keeps curved, profiled art close to a uniform stroke's size.
let mut marks = Vec::with_capacity(ts.len() * SAMPLES);
// Where each flattened point falls on the profile, so a segment can see the points inside it.
let mut at = Vec::with_capacity(flat.pts.len());
let mut walked = 0.0;
for (i, p) in flat.pts.iter().enumerate() {
at.push(span.0 + walked / total * range);
if let Some(next) = flat.pts.get(i + 1) {
walked += p.distance(*next);
}
}
for w in ts.windows(2) {
let (a, b) = (w[0], w[1]);
let samples = if constant {
@@ -259,12 +259,11 @@ fn densify(
// shifted copy has the same shape, so measure its bend on the unshifted segment.
let start = a.rem_euclid(1.0);
let end = start + (b - a);
let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap);
// How many of the flattened path's points already fall in this profile segment.
// `density` is measured on the whole subpath, not on this piece, so outlining only
// the piece near the view picks the same samples as outlining the whole subpath.
let existing = (b - a) * density;
if existing >= want as f64 { 1 } else { want }
let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, bend).min(cap);
// Judge the flattened points inside this profile segment, not the subpath's overall
// density: a long straight run beside a densely flattened curve has few points of its
// own, and only they can tell whether the run already follows the width curve.
if sampled_enough(profile, &at, a, b, bend) { 1 } else { want }
};
for k in 0..samples {
marks.push(a + (b - a) * k as f64 / samples as f64);
@@ -277,22 +276,17 @@ fn densify(
split_at(flat, closed, &marks, segs)
}
/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width
/// curve. A straight taper is already straight; a visible bend gets progressively more samples.
/// How many pieces one profile segment needs so the outline follows the width curve to within
/// `bend` (a gap in width factor; the caller turns the outline tolerance into it). A straight
/// taper is already straight; a visible bend gets progressively more samples, up to `max`.
fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize {
let mut samples = base.max(1);
while samples < max {
// One probe in the middle of each piece: how far the curve leaves the straight line
// between the piece's ends. The more pieces, the closer the line follows the curve, so
// the loop only stops when the pieces it has are fine enough (or at `max`).
let mut dev = 0.0_f64;
for k in 0..samples {
let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64);
let (la, ra) = profile.at(t0 + (t1 - t0) * a);
let (lb, rb) = profile.at(t0 + (t1 - t0) * b);
let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0);
dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs());
}
let step = (t1 - t0) / samples as f64;
let dev = (0..samples).fold(0.0_f64, |dev, k| dev.max(deviation(profile, t0 + step * k as f64, t0 + step * (k + 1) as f64)));
if dev <= bend {
break;
}
@@ -301,6 +295,46 @@ fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max:
samples
}
/// How far the width curve leaves the straight line between two profile positions: the widest of
/// its two sides at the span's middle.
fn deviation(profile: &WidthProfile, t0: f64, t1: f64) -> f64 {
let (la, ra) = profile.at(t0);
let (lb, rb) = profile.at(t1);
let (lm, rm) = profile.at((t0 + t1) / 2.0);
(lm - (la + lb) / 2.0).abs().max((rm - (ra + rb) / 2.0).abs())
}
/// Whether the flattened points inside profile segment `[a, b]` already follow the width curve to
/// within `bend`, so the segment needs no samples of its own. `at` holds each flattened point's
/// profile position. The subpath's overall point density cannot answer this: a long straight run
/// beside a densely flattened curve has few points of its own, and its width must still follow the
/// curve rather than run straight between its ends.
fn sampled_enough(profile: &WidthProfile, at: &[f64], a: f64, b: f64, bend: f64) -> bool {
let first = at.partition_point(|p| *p < a);
let last = at.partition_point(|p| *p <= b);
// A segment whose flattened points only sit on its boundaries is a straight run: one probe in
// the middle cannot see a bend that matches the chord there but leaves it nearer the ends. Let
// `adaptive_samples` measure it.
if !at[first..last].iter().any(|&p| p > a + 1e-9 && p < b - 1e-9) {
return false;
}
// A dash crossing a closed seam has a window past 1 (`[1.0, 1.5]`), where the widths wrap;
// probe the positions `densify` measured its samples at. `at` stays unwrapped for selection.
let shift = a - a.rem_euclid(1.0);
let mut from = a - shift;
for &p in &at[first..last] {
let p = p - shift;
if p <= from {
continue;
}
if deviation(profile, from, p) > bend {
return false;
}
from = p;
}
deviation(profile, from, b - shift) <= bend
}
/// Length of a flattened subpath (see [`flatten`]).
pub(super) fn length(pts: &[Point], closed: bool) -> f64 {
let n = pts.len();
@@ -419,8 +453,11 @@ impl<'a> Ctx<'a> {
}
}
fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) {
let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density);
fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64)) {
// The flattened edge and its cubic fit are already within `tol`, so a width bend that
// strays further would show as a dent or a bulge that the plain stroke does not have.
let bend = self.tol.max(1e-9) / self.half.max(1e-12);
let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, bend);
let n = pts.len();
let seg_count = if closed { n } else { n - 1 };
let seg_dir: Vec<Vec2> = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect();
@@ -803,11 +840,11 @@ fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) {
} else {
(run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2]))
};
// Fit tighter than the flattening tolerance: the fit's error is the whole outline's error,
// and a least-squares fit may sit on one side of the sampled edge, which would otherwise
// shift a profile's area visibly. The points lie on the outline's own curve, so the fit follows
// their curve between them rather than the chords through them.
let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1);
// Fit to the flattening tolerance: the samples lie on the outline's own curve, so the fit
// follows that curve between them rather than the chords through them, and the outline is as
// close to the ideal offset as a plain stroke's flattened edge is. A tighter fit added many
// cubics along a strong width wave without a visible gain.
let cubics = fit_cubics_through(&pts, t0, t1, tol);
if cubics.is_empty() {
out.line_to(run[n - 1]);
return;
@@ -860,12 +897,15 @@ mod tests {
assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6);
}
/// The lens eases up to full width and back down (a parabolic bump averaging two thirds of
/// the width); a one-sided profile keeps its side at zero and stays on the other.
/// The lens eases up to full width and back down (a smooth bump covering seven twelfths of the
/// full width); a one-sided profile keeps its side at zero and stays on the other.
#[test]
fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() {
let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01));
assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}");
// Within a couple of square points over the bump's 200 pt of edge: the sampled chords and
// the cubic fit each stay within the outline tolerance (0.01) of the curve, so about
// 200 × 0.01 of area either side is expected and invisible.
assert!((a - 1000.0 * 7.0 / 12.0).abs() < 2.0, "{a}");
let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] };
let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01);
assert!((area(&o) - 500.0).abs() < 1e-6);
@@ -1099,10 +1139,74 @@ mod tests {
assert!((a - want).abs() / want < 0.01, "{a} vs {want}");
}
/// A long straight run beside a densely flattened curve still follows the profile across the
/// run: the subpath's overall point count must not stand in for the points the run itself has.
#[test]
fn a_long_run_beside_a_dense_curve_keeps_the_profiles_shape() {
// One 200 pt line whose second half is 128 collinear pieces: the same geometry as the
// two-segment line, with most of the flattened points on the second half. The lens peaks
// at the join, so a straight chord across either half would sit at 2.5 pt half way along
// it rather than the 3.125 the profile has there.
let mut dense = BezPath::new();
dense.move_to((0.0, 0.0));
for i in 1..=128 {
dense.line_to((100.0 + 100.0 * i as f64 / 128.0, 0.0));
}
let mut sparse = BezPath::new();
sparse.move_to((0.0, 0.0));
sparse.line_to((200.0, 0.0));
let p = WidthProfile::lens();
let dense = width_outline(&dense, 10.0, &p, &capped(LineCap::Butt), 0.01);
let sparse = width_outline(&sparse, 10.0, &p, &capped(LineCap::Butt), 0.01);
// The extra collinear points may not change the outline.
let (a, b) = (area(&dense), area(&sparse));
assert!((a - b).abs() < 2.0, "{a} vs {b}");
assert!((b - 10.0 * 200.0 * 7.0 / 12.0).abs() < 2.0, "{b}");
// ... and the edge at a quarter of the way along each half sits at the lens's width.
for x in [50.0, 150.0] {
assert!(dense.contains(Point::new(x, -3.0)), "{x}: {dense:?}");
assert!(!dense.contains(Point::new(x, -3.4)), "{x}: no extra samples: {dense:?}");
}
}
/// A profile segment whose flattened points only sit on its boundaries is a straight run: the
/// sampler measures it, rather than accepting it on a midpoint that happens to match the chord.
#[test]
fn a_bend_that_matches_the_chords_midpoint_still_gets_samples() {
// Flat at 1, then a smooth rise to 2, with collinear vertices exactly on the rise's
// boundaries: through the rising segment the curve matches its chord at the middle and
// sits below it at a quarter of the way, so one midpoint probe would leave the edge
// 0.47 pt out at the quarter.
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((25.0, 0.0));
b.line_to((75.0, 0.0));
b.line_to((100.0, 0.0));
let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.75, 2.0, 2.0), (1.0, 2.0, 2.0)] };
let o = width_outline(&b, 10.0, &p, &capped(LineCap::Butt), 0.01);
// At a quarter of the way through the rise the width is 1.15625, so that edge is 5.78 pt
// from the path; a chord from 1 to 2 would put it at 6.25.
assert!(!o.contains(Point::new(37.5, -6.0)), "{o:?}");
assert!(o.contains(Point::new(37.5, -5.5)), "{o:?}");
}
/// A window past the seam of a closed path probes the widths it actually wraps to: the
/// flattened points of a dash tail sit before the seam.
#[test]
fn a_window_past_the_seam_measures_the_wrapped_widths() {
let profile = WidthProfile::lens();
// A dash from 0.9 to 1.1 of the subpath, its flattened points ending at 1.1: `[1.0, 1.5]`
// is the wrapped half of the profile's first segment.
let at = [0.9, 0.95, 1.0, 1.05, 1.1];
assert!(!sampled_enough(&profile, &at, 1.0, 1.5, 0.002), "the wrapped width bends");
}
#[test]
fn profiled_outlines_stay_compact() {
// A smooth profile is fitted with cubics, so it must not turn every profile sample into
// exported path data. Compare it with the same curved path's uniform outline.
// exported path data. The wave genuinely bends four times around this small circle, so it
// takes more cubics than the plain annulus; a fit to every sample would take several times
// as many again.
let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01);
let count = |points| {
let p = WidthProfile { points };
@@ -1112,6 +1216,6 @@ mod tests {
let lens = count(WidthProfile::lens().points);
let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]);
assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}");
assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}");
assert!(wave <= uniform * 3, "wave {wave} vs uniform {uniform}");
}
}
+10 -4
View File
@@ -1687,6 +1687,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let from = index_param(p, "from", C)?;
let contents = p.get("contents").map(|_| index_param(p, "contents", C)).transpose()?;
let mut landed = to;
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
let mut active_landed = None;
// When every object's stack comes out as it was, the document and its undo history stay as they
// are.
let before = s.doc()?.doc.clone();
@@ -1694,6 +1696,9 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
landed = n.appearance.move_item(from, to).ok_or_else(|| bad(C, format!("no item at index {from}")))?;
if active == Some(*id) {
active_landed = Some(landed);
}
if let Some(k) = contents.filter(|_| n.contents_label().is_some()) {
n.appearance.set_contents_at(k);
}
@@ -1703,13 +1708,14 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
let labels = super::graph::capture_label_changes(&before, d, &ids, true, None);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels))
})?;
// The moved row stays the active one; the rows it passed shift by one.
// Track the row in its own object's stack, since other stacks may clamp to a different index.
let at = active_landed.unwrap_or(landed);
s.remap_appearance_item(&ids, |a| {
Some(if a == from {
landed
} else if from < a && a <= landed {
at
} else if from < a && a <= at {
a - 1
} else if landed <= a && a < from {
} else if at <= a && a < from {
a + 1
} else {
a
+6 -4
View File
@@ -88,11 +88,13 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
}
let a = if source.is_none() || p.get("a").is_some() { point(p, "a")? } else { Point::ZERO };
let b = if source.is_none() || p.get("b").is_some() { point(p, "b")? } else { Point::new(1.0, 0.0) };
let vertex = if mode == DimensionMode::Angular && (source.is_none() || matches!(source, Some(DimensionSource::Points { .. }))) {
point(p, "vertex")?
} else {
Point::ZERO
// Resolution supplies a linked vertex. An explicit coordinate is still checked when given.
let read_vertex = match &source {
None => true,
Some(DimensionSource::Points { vertex, .. }) => vertex.is_none() || p.get("vertex").is_some(),
_ => false,
};
let vertex = if mode == DimensionMode::Angular && read_vertex { point(p, "vertex")? } else { Point::ZERO };
let orientation = orientation(p, mode)?.unwrap_or_default();
let mut d = Dimension {
mode,
+19 -1
View File
@@ -131,8 +131,10 @@ fn apply(s: &mut DocSetup, units: &mut vectorcraft_doc::Unit, k: &str, v: &Value
let (name, _, quotes) = LANGUAGES.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(l)).ok_or_else(|| {
bad(C, format!("unknown language `{l}` (one of {})", LANGUAGES.iter().map(|(n, _, _)| *n).collect::<Vec<_>>().join(", ")))
})?;
if !s.language.eq_ignore_ascii_case(name) {
s.quotes = *quotes;
}
s.language = name.to_string();
s.quotes = *quotes;
}
"quotes" => s.quotes = quotes_param(v, s.quotes)?,
"typographersQuotes" => s.typographers_quotes = flag(k, v)?,
@@ -311,3 +313,19 @@ fn restamp_scripts(d: &mut Document) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn setup_round_trip_preserves_custom_quotes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute(C, &json!({"quotes": {"double": "«»", "single": "‹›"}})).unwrap();
let mut fields = s.execute(C, &json!({})).unwrap();
fields["bleed"] = json!(4);
let reply = s.execute(C, &fields).unwrap();
assert_eq!(reply["quotes"], fields["quotes"]);
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+380 -32
View File
@@ -74,13 +74,329 @@ fn stroke_subpath(pts: &[Point], tol: Option<f64>, closed: bool) -> SubPath {
}
}
/// Pencil's Edit Selected Paths in the middle of a path: a stroke from one point of a subpath of
/// `pd` to another, each within `within` of it, replaces the section between them (the shorter
/// way round a closed subpath) with the stroke fitted at `tol` (with no `tol`, unfitted). The
/// subpath's index and its new shape; None when the stroke doesn't start and end on the same
/// subpath, or meets it once.
/// The anchor of `sp` at the point of it nearest to `q`: the one there, else a new one, and
/// whether it was added.
fn anchor_at(sp: &mut SubPath, q: Point) -> Option<(usize, bool)> {
let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?;
let n = sp.anchors.len();
if n == 0 {
return None;
}
Some(if t <= 1e-6 {
(seg % n, false)
} else if t >= 1.0 - 1e-6 {
((seg + 1) % n, false)
} else {
(sp.insert_anchor(seg, t), true)
})
}
/// The direction `sp` leaves anchor `k` going forward (towards the next anchor).
fn forward_at(sp: &SubPath, k: usize) -> Option<kurbo::Vec2> {
let a = sp.anchors.get(k)?;
let n = sp.anchors.len();
let next = if sp.closed || k + 1 < n { sp.anchors.get((k + 1) % n) } else { None };
let toward = if a.h_out != a.p {
a.h_out
} else if let Some(b) = next {
if b.h_in != b.p { b.h_in } else { b.p }
} else {
// The last anchor of an open subpath: forward goes on the way it arrived.
let prev = sp.anchors.get(k.checked_sub(1)?)?;
return Some(a.p - if a.h_in != a.p { a.h_in } else { prev.p });
};
let v = toward - a.p;
(v.hypot() > 1e-9).then_some(v)
}
/// The direction stroke `pts` leaves its first point: towards its first point farther than
/// `reach` from it, or its last point.
fn heading(pts: &[Point], reach: f64) -> Option<kurbo::Vec2> {
let (&p0, rest) = pts.split_first()?;
let to = rest.iter().find(|q| q.distance(p0) > reach).or(rest.last())?;
let v = *to - p0;
(v.hypot() > 1e-9).then_some(v)
}
/// `stroke` (its first point moved onto anchor `a` of the path it leaves) fitted at `tol`: its
/// anchors, the first of which is at `a`.
fn fit_from(a: Point, pts: &[Point], tol: Option<f64>, reach: f64) -> Vec<Anchor> {
let mut stroke = pts.to_vec();
bend_ends(&mut stroke, Some(a), None, reach);
stroke_subpath(&stroke, tol, false).anchors.into_vec()
}
/// Bend the ends of `stroke` onto `a` (its start) and `b` (its end): each end moves all the way
/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths
/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a
/// straight piece. A stroke shorter than `reach` bends over its own length, so each end still
/// lands on its target and the other end's bend doesn't move it off.
fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f64) {
let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return };
// How far along the stroke each point lies, measured before anything moves.
let mut along = Vec::with_capacity(stroke.len());
let mut total = 0.0;
let mut prev = first;
for p in stroke.iter() {
total += prev.distance(*p);
prev = *p;
along.push(total);
}
let reach = reach.min(total);
if !reach.is_finite() || reach <= 0.0 {
// No length to bend over: only the ends move.
if let (Some(a), Some(p)) = (a, stroke.first_mut()) {
*p = a;
}
if let (Some(b), Some(p)) = (b, stroke.last_mut()) {
*p = b;
}
return;
}
let weight = |d: f64| (1.0 - d / reach).max(0.0);
let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last));
for (p, &d) in stroke.iter_mut().zip(&along) {
if let Some(s) = shift_a {
*p += s * weight(d);
}
if let Some(s) = shift_b {
*p += s * weight(total - d);
}
}
}
/// Pencil's Edit Selected Paths for a stroke that starts on a subpath of `pd` (within `within` of
/// it) and ends away from it (#2850 follow-up): the path follows the stroke and ends where the
/// stroke does. A closed subpath opens where the stroke starts and keeps its whole outline, run
/// so that it arrives there heading the stroke's way. An open subpath is cut there and keeps the
/// part behind the stroke: the part the stroke heads along is dropped. The subpath's index and its
/// new shape; None when the stroke doesn't start on `pd`. `runs_up`, when given, says which part of
/// an open subpath the stroke heads along: the part towards its last anchor when true.
fn redraw_extend(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64, runs_up: Option<bool>) -> Option<(usize, SubPath)> {
let first = *pts.first()?;
let (si, _, _, _, d) = pd.nearest(first)?;
if d > within || pts.len() < 2 {
return None;
}
let mut sp = pd.subpaths.get(si)?.clone();
if sp.anchors.len() < 2 {
return None;
}
let (mut k, _) = anchor_at(&mut sp, first)?;
let last = sp.anchors.len() - 1;
// Run the subpath so the stroke goes on from `k` forward; the result runs the subpath's own way
// again below, so a shape's holes stay holes under the non-zero fill rule. A closed subpath
// arrives at `k` heading the stroke's way. An open one drops the part the stroke heads along;
// one it leaves nearly square to it (more than 70° from its direction) drops its shorter
// part, never most of the path. From one of its ends it drops nothing.
let dir = heading(pts, within.max(tol.unwrap_or(0.0) * 2.0))?;
let cos = forward_at(&sp, k).map_or(0.0, |f| f.dot(dir) / (f.hypot() * dir.hypot()).max(1e-12));
let flipped = if sp.closed {
cos < 0.0
} else if k == 0 || k == last {
k == 0
} else if let Some(up) = runs_up {
!up
} else if cos.abs() >= 0.34 {
cos < 0.0
} else {
let len = |i: usize, j: usize| (i..j).map(|s| kurbo::ParamCurveArclen::arclen(&sp.segment(s), 0.01)).sum::<f64>();
len(0, k) < len(k, last)
};
if flipped {
sp.reverse();
k = sp.anchors.len().checked_sub(1 + k)?;
}
let at = *sp.anchors.get(k)?;
let mut anchors: Vec<Anchor> = if sp.closed {
// From `k` all the way round back to `k`: the shape opens there.
let mut v: Vec<Anchor> = sp.anchors.get_range(k..)?.into_iter().chain(sp.anchors.get_range(..k)?).collect();
if let Some(a0) = v.first_mut() {
*a0 = Anchor::with_handles(a0.p, a0.p, a0.h_out);
}
v.push(at);
v
} else {
sp.anchors.get_range(..=k)?
};
let fit = fit_from(at.p, pts, tol, within);
let (f0, rest) = fit.split_first()?;
if let Some(a) = anchors.last_mut() {
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
}
anchors.extend_from_slice(rest);
let mut out = SubPath::new(anchors, false);
if flipped {
out.reverse();
}
Some((si, out))
}
/// A stroke that leaves anchor `k` of `sp` and comes back to it: the stroke is inserted there as a
/// loop out of the path (#2850 follow-up).
fn redraw_loop(mut sp: SubPath, k: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let at = *sp.anchors.get(k)?;
let mut stroke = pts.to_vec();
bend_ends(&mut stroke, Some(at.p), Some(at.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
if fit.len() < 3 {
return None;
}
let inner = fit.get(1..fit.len() - 1)?;
let mut anchors = sp.anchors.get_range(..k)?;
anchors.push(Anchor::with_handles(at.p, at.h_in, f0.h_out));
anchors.extend_from_slice(inner);
anchors.push(Anchor::with_handles(at.p, fl.h_in, at.h_out));
anchors.extend_from_slice(&sp.anchors.get_range(k + 1..)?);
sp.anchors = anchors.into();
Some(sp)
}
/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor
/// `end`) in place of its run from `start` forward to `end`.
fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<Item = Point>) -> f64 {
use kurbo::ParamCurveArea;
let n = sp.anchors.len();
let (Some(from), Some(to)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return 0.0 };
let mut area: f64 = (0..(start + n - end) % n).map(|k| sp.segment((end + k) % n).signed_area()).sum();
let mut at = from.p;
for q in stroke.chain([to.p]) {
area += kurbo::Line::new(at, q).signed_area();
at = q;
}
area.abs()
}
/// Which way a stroke runs along open subpath `sp` where it meets it: `stroke` starts at that end
/// of the stroke. It runs along when its first `within` of length stays within `within` of the
/// path and moves along the path more than away from it: Some(true) towards the subpath's last
/// anchor. None when it goes straight off (or onto) the path.
fn run_along(sp: &SubPath, mut stroke: impl Iterator<Item = Point>, within: f64) -> Option<bool> {
let one = PathData::single(sp.clone());
let p0 = stroke.next()?;
// The point `within` along the stroke, or its other end when it is shorter.
let (mut prev, mut len, mut q) = (p0, 0.0, p0);
for p in stroke {
let step = prev.distance(p);
if len + step >= within && step > 0.0 {
q = prev.lerp(p, (within - len) / step);
break;
}
len += step;
prev = p;
q = p;
}
let (_, s0, t0, on0, _) = one.nearest(p0)?;
let (_, s1, t1, on1, away) = one.nearest(q)?;
if away > within || on0.distance(on1) <= away {
return None;
}
Some(s1 as f64 + t1 > s0 as f64 + t0)
}
/// What a stroke from anchor `from` to anchor `to` of open subpath `sp` does to it.
enum OpenRedraw {
/// Replaces the part between and leaves the path open.
Replace,
/// Keeps the part between, drops the pieces beyond and closes the path with the stroke.
Close,
/// Drops the part it starts along (towards the last anchor when true) and ends where it does.
Extend(bool),
}
/// Pencil's Edit Selected Paths on an open subpath: what a stroke from anchor `from` to anchor `to`
/// of `sp` does, from the way it runs along the path at each end ([`run_along`]; `before` is the
/// subpath before the anchors at `from` and `to` were added). Where it starts, it replaces the part
/// it runs along; where it lands, it joins the part it runs into and the part behind goes. An end
/// that goes straight off or onto the path follows the other end. When both do, it closes only if
/// the shape it makes with the part between goes round both pieces beyond ([`goes_round`]). When
/// the two ends disagree, the start decides and the stroke's end stays where it is lifted.
fn open_redraw(before: &SubPath, sp: &SubPath, from: usize, to: usize, pts: &[Point], within: f64) -> OpenRedraw {
let up = to > from;
// Each end runs towards the last anchor (true) or the first. Running towards the other end
// of the stroke at the start, or on away from it where it lands, replaces the part between;
// the other way keeps the part between and closes the path.
let at_start = run_along(before, pts.iter().copied(), within);
let at_end = run_along(before, pts.iter().rev().copied(), within).map(|back| !back);
match (at_start, at_end) {
(Some(s), Some(e)) if s != e => OpenRedraw::Extend(s),
(Some(r), _) | (None, Some(r)) => {
if r == up {
OpenRedraw::Replace
} else {
OpenRedraw::Close
}
}
(None, None) => {
if goes_round(sp, from, to, pts) {
OpenRedraw::Close
} else {
OpenRedraw::Replace
}
}
}
}
/// Does the shape that stroke `pts` (from anchor `from` to anchor `to` of open subpath `sp`) makes
/// with the part of `sp` between them go round both pieces of `sp` beyond them? A piece counts as
/// inside when more of it lies inside than outside; a piece of no length counts as inside.
fn goes_round(sp: &SubPath, from: usize, to: usize, pts: &[Point]) -> bool {
use kurbo::{ParamCurve, Shape};
let (lo, hi) = (from.min(to), from.max(to));
let Some(middle) = sp.anchors.get_range(lo..=hi) else { return false };
let mut shape = PathData::single(SubPath::new(middle, false)).to_bezpath();
// The stroke runs from `hi` back to `lo` to close the shape.
let back: Vec<Point> = if from == lo { pts.iter().rev().copied().collect() } else { pts.to_vec() };
for p in back {
shape.line_to(p);
}
shape.close_path();
let inside = |segs: std::ops::Range<usize>| {
let (mut yes, mut no) = (0, 0);
for k in segs {
let seg = sp.segment(k);
for t in [0.25, 0.5, 0.75] {
if shape.winding(seg.eval(t)) != 0 { yes += 1 } else { no += 1 }
}
}
yes >= no
};
inside(0..lo) && inside(hi..sp.anchors.len().saturating_sub(1))
}
/// Closes open subpath `sp` with stroke `pts`, which runs from anchor `from` to anchor `to`: the
/// anchors between them stay, the pieces beyond go, and the stroke, its ends bent onto those
/// anchors ([`bend_ends`] over `within`), runs from one back to the other.
fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let (lo, hi) = (from.min(to), from.max(to));
let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?);
let mut stroke = pts.to_vec();
if from == lo {
stroke.reverse();
}
bend_ends(&mut stroke, Some(a_hi.p), Some(a_lo.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
let mut anchors = sp.anchors.get_range(lo..=hi)?;
if let Some(a) = anchors.first_mut() {
*a = Anchor::with_handles(a.p, fl.h_in, a.h_out);
}
if let Some(a) = anchors.last_mut() {
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
}
anchors.extend_from_slice(fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default());
Some(SubPath::new(anchors, true))
}
/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within
/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with
/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the
/// way round that leaves the bigger shape. On an open one the way the stroke runs along the path
/// at its ends decides ([`open_redraw`]): it replaces the part between, keeps the part between and
/// closes the path, or ends where it is lifted. The subpath's index and its new shape; None when
/// the stroke doesn't start and end on the same subpath.
fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -> Option<(usize, SubPath)> {
use kurbo::ParamCurveArclen;
let (first, last) = (*pts.first()?, *pts.last()?);
let (si, _, _, _, d_a) = pd.nearest(first)?;
let (sj, _, _, _, d_b) = pd.nearest(last)?;
@@ -91,35 +407,35 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
if sp.anchors.len() < 2 {
return None;
}
// The anchor nearest to `q`: the one there, else a new one, and whether it was added. Each
// point is looked up on the subpath as it is by then: splitting a straight segment makes two
// new ones, which a `t` along the old one doesn't measure.
let place = |sp: &mut SubPath, q: Point| {
let (_, seg, t, _, _) = PathData::single(sp.clone()).nearest(q)?;
let n = sp.anchors.len();
Some(if t <= 1e-6 {
(seg % n, false)
} else if t >= 1.0 - 1e-6 {
((seg + 1) % n, false)
} else {
(sp.insert_anchor(seg, t), true)
})
};
let (mut from, _) = place(&mut sp, first)?;
let (to, added) = place(&mut sp, last)?;
let before = sp.clone();
// Each point is looked up on the subpath as it is by then: splitting a straight segment makes
// two new ones, which a `t` along the old one doesn't measure.
let (mut from, _) = anchor_at(&mut sp, first)?;
let (to, added) = anchor_at(&mut sp, last)?;
if added && to <= from {
from += 1;
}
if from == to {
return None;
// The stroke starts and ends on the same point: it is a loop out of the path there.
return redraw_loop(sp, from, pts, tol, within).map(|sp| (si, sp));
}
if !sp.closed {
match open_redraw(&before, &sp, from, to, pts, within) {
OpenRedraw::Replace => {}
OpenRedraw::Close => return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp)),
OpenRedraw::Extend(up) => return redraw_extend(pd, pts, tol, within, Some(up)),
}
}
let n = sp.anchors.len();
// The length of the run of segments from anchor i forward to anchor j.
let run = |i: usize, j: usize| (0..(j + n - i) % n).map(|k| sp.segment((i + k) % n).arclen(0.01)).sum::<f64>();
// The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from
// `end` round to `start`, then the stroke's inner anchors follow.
let (start, end, reversed) = if sp.closed {
if run(from, to) <= run(to, from) { (from, to, false) } else { (to, from, true) }
// The bigger of the two shapes the stroke could make stays: carving across a shape replaces
// the part it cuts off, drawing round outside it the part it goes round. Picking the side
// nearer the stroke instead threw away a thin shape under a tall arch over its long side.
let forward = redrawn_area(&sp, from, to, pts.iter().copied());
let backward = redrawn_area(&sp, to, from, pts.iter().rev().copied());
if forward >= backward { (from, to, false) } else { (to, from, true) }
} else if from < to {
(from, to, false)
} else {
@@ -129,10 +445,8 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
if reversed {
stroke.reverse();
}
let (Some(s0), Some(s1)) = (stroke.first_mut(), sp.anchors.get(start)) else { return None };
*s0 = s1.p;
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
*e0 = e1.p;
let (Some(s1), Some(e1)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return None };
bend_ends(&mut stroke, Some(s1.p), Some(e1.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
@@ -212,6 +526,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
let keep_selected = switch_or(p, "keepSelected", true, C)?;
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
// selection as it is: the path being redrawn stays selected until the release redraws it.
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
let filled = switch_or(p, "fill", false, C)?;
let extend = p.get("extend").filter(|v| !v.is_null());
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
@@ -416,7 +733,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// shortcut: a stroke's pressure, tilt, bearing and rotation profiles are left as they
// were, measured along the old path; fit them to the new length if strokes drawn with a
// pen get redrawn.
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
// A stroke that ends back on the path redraws the section between; one that ends away from
// it takes the path with it (it is where the pen is lifted that decides).
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within).or_else(|| redraw_extend(&pd, &pts, fit_tol, within, None)) {
// A member path of a compound path is redrawn in it: the compound path is what is
// selected, and what a brush paints.
let whole = brush_target(&s.doc()?.doc, id);
@@ -461,7 +780,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
}
}
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
if !keep_selected {
if !keep_selected && !leave_selection {
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
// by dropping the earlier selection, it does not keep it (#5752).
s.select(|_, sel| sel.clear())?;
@@ -628,3 +947,32 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "id": keep.0 }))
}
#[cfg(test)]
mod bend_tests {
use super::*;
/// The ends move onto their targets, the stroke behind them less and less, and nothing farther
/// along than `reach`.
#[test]
fn bend_ends_moves_the_ends_and_fades_out_along_the_reach() {
let mut pts: Vec<Point> = (0..=10).map(|i| Point::new(f64::from(i) * 10.0, 0.0)).collect();
bend_ends(&mut pts, Some(Point::new(0.0, 8.0)), Some(Point::new(100.0, -8.0)), 40.0);
assert_eq!(pts[0], Point::new(0.0, 8.0));
assert_eq!(pts[10], Point::new(100.0, -8.0));
assert!((pts[2].y - 8.0 * 0.5).abs() < 1e-9, "halfway along the reach, half the shift: {:?}", pts[2]);
assert!((pts[8].y + 8.0 * 0.5).abs() < 1e-9, "{:?}", pts[8]);
assert_eq!(pts[5], Point::new(50.0, 0.0), "the middle doesn't move");
}
/// A stroke shorter than `reach` still has both ends on their targets: bending one end onto
/// its target doesn't pull the other end off its own.
#[test]
fn bend_ends_keeps_both_ends_on_target_for_a_short_stroke() {
let mut pts = vec![Point::new(40.0, -12.0), Point::new(44.0, -12.0), Point::new(48.0, -12.0)];
bend_ends(&mut pts, Some(Point::new(40.0, 0.0)), Some(Point::new(48.0, 0.0)), 16.0);
assert_eq!(pts[0], Point::new(40.0, 0.0), "{pts:?}");
assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}");
assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}");
}
}
+4 -1
View File
@@ -695,6 +695,7 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
/// goes to the running command's result or the tool's status messages, as the tool's own commit
/// reports it ([`Session::note_settled_warning`]).
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
s.put_back_interaction();
let typing = typing_in_progress(s);
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
Some((cmd, p)) => match s.preview(&cmd, &p) {
@@ -894,8 +895,10 @@ fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.newDocumentFromState";
let created = date_param(p, "created", C)?;
// The row as the panel lists it now, with a drag in progress on show: keeping it below
// changes the rows.
s.put_back_interaction();
let st = s.doc()?;
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
let chosen = match super::index_opt(p, "index", C)? {
None => None,
Some(row) => {
+2 -1
View File
@@ -159,7 +159,8 @@ impl LoadOptions {
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
// The command's opt-out also skips the embedded VectorCraft document.
native: editing_data,
link_pages,
})
}
@@ -53,6 +53,27 @@ fn a_pdf_saved_with_preserve_editing_reopens_as_the_same_document() {
assert!(vectorcraft_pdf::editing(&b64(&v)).is_some_and(|e| e.intact));
}
#[test]
fn opening_a_preserve_editing_pdf_without_editing_data_imports_its_pages() {
let mut s = rich();
assert!(!s.doc().unwrap().doc.symbols.is_empty());
let exported = s.execute("document.exportPdf", &json!({"preserveEditing": true})).unwrap();
let reopened = s
.execute(
"document.open",
&json!({
"name": "rich.pdf",
"dataBase64": exported["dataBase64"],
"cropTo": "media",
"editingData": false,
}),
)
.unwrap();
assert_eq!(reopened["restored"], false, "{reopened}");
assert!(s.doc().unwrap().doc.symbols.is_empty(), "the PDF page has no native symbol definitions");
}
#[test]
fn pages_changed_elsewhere_open_as_artwork_with_a_warning() {
let mut s = rich();
+1 -1
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Nudge",
[],
None,
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
has_selection_or_guides,
nudge
),
+4 -1
View File
@@ -347,7 +347,10 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
if dx == 0.0 && dy == 0.0 {
return ok();
}
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
return crate::cmd::path::nudge_anchors(
s,
&json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }),
);
}
if objects && s.doc()?.selection.is_empty() {
let copy = bool_or(p, "copy", false);
+105 -48
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, SegmentRef, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
@@ -140,7 +140,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Anchor Point",
[],
None,
"{id, subpath?, segment, t: 0..1} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
"{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected",
has_doc,
insert_anchor
),
@@ -244,19 +244,48 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?;
move_selected(s, p, false)
}
/// The arrow keys with direct-selected anchors or segments: as `path.moveAnchors`, except that a
/// selected curved segment bends ([`SubPath::nudge_segment`]).
pub(crate) fn nudge_anchors(s: &mut Session, p: &Value) -> Result<Value> {
move_selected(s, p, true)
}
/// Move the selection by `(dx, dy)`: its direct-selected anchors with their handles, and the
/// objects selected whole. With `bend`, each selected curved segment bends instead and its anchors
/// stay, except an anchor that also ends a selected straight segment, which moves with it.
fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result<Value> {
const C: &str = "path.moveAnchors";
let d = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?);
check_switches(p, &["patterns", "interpolate"], C)?;
// An object selected in a symbol instance's art stays where the symbol puts it.
super::edit::refuse_symbol_part(s)?;
let st = s.doc()?;
let mut sel = st.selection.clone();
let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) };
// Segments that hold their anchors and don't bend, with nothing else to move, change nothing.
if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) {
return ok();
}
// Objects selected whole move as objects, and their pattern tiles move with them when
// `patterns` (default: General › Transform Pattern Tiles) is on.
let whole = s.doc()?.selection.whole();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() };
let interpolate = interpolates_handles(s, p, "path.moveAnchors")?;
transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
// Transform Again repeats a move that moved something; a drag records it when it commits.
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() };
let interpolate = interpolates_handles(s, p, C)?;
s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| {
transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?;
for &(id, si, seg) in &bends {
if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) {
sp.nudge_segment(seg, d);
}
}
Ok(())
})?;
// Transform Again repeats a move that moved something; a drag records it when it commits. A
// move that held segments' anchors is not one move of the selection.
let st = s.doc_mut()?;
if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
if !held && st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) {
let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate });
st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options));
st.last_perspective = None;
@@ -264,6 +293,29 @@ pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Take the anchors of `sel`'s selected curved segments out of its `anchors`, except those that
/// also end a selected straight segment, and list the segments that a bend by `d` changes. Also
/// whether any curved segment is selected.
fn held_segments(doc: &Document, sel: &mut Selection, d: Vec2) -> (bool, Vec<(NodeId, usize, usize)>) {
let (mut held, mut bends) = (false, vec![]);
for (&id, refs) in &sel.segments {
let (Some(path), Some(set)) = (doc.node(id).and_then(Node::path_data), sel.anchors.get_mut(&id)) else { continue };
let ends = |(si, seg): SegmentRef| path.subpaths.get(si).map(|sp| [(si, seg), (si, (seg + 1) % sp.anchors.len())]);
let curved = |&(si, seg): &SegmentRef| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count() && !sp.segment_is_line(seg));
let moved: BTreeSet<AnchorRef> = refs.iter().filter(|r| !curved(r)).filter_map(|&r| ends(r)).flatten().collect();
for &(si, seg) in refs.iter().filter(|r| curved(r)) {
held = true;
for end in ends((si, seg)).into_iter().flatten().filter(|e| !moved.contains(e)) {
set.remove(&end);
}
if path.subpaths.get(si).is_some_and(|sp| sp.nudged_handles(seg, d).is_some()) {
bends.push((id, si, seg));
}
}
}
(held, bends)
}
/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the
/// segments beside them (`interpolate` param, else General › Interpolate Control Points When
/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference
@@ -276,56 +328,59 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res
Ok(on)
}
/// [`transform_selected`] on the active document's selection, as one undo step `label`.
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate))
}
/// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the
/// objects selected whole (those with no entry in the selection's `anchors`). An object inside
/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside
/// another selected object, such as a path in a selected group, moves once, with that object.
/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end
/// are re-mapped ([`move_interpolating_handles`]).
pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let sel = s.doc()?.selection.clone();
let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone());
fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> {
let ids = super::edit::outermost(doc, sel.objects.clone());
let c = xf.as_coeffs();
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
let delta = vectorcraft_geom::Vec2::new(c[4], c[5]);
s.edit(label, |doc, _| {
for id in &ids {
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
for id in &ids {
match sel.anchors.get(id) {
Some(set) => {
let path = path_mut(doc, *id)?;
// Only an exact move takes the interpolating path: a near-identity scale or
// turn still transforms the anchors as asked.
if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] {
move_interpolating_handles(path, set, delta);
} else {
for &(si, ai) in set {
if let Some(a) = path.anchor_mut(si, ai) {
*a = a.transform(xf);
}
}
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
// to the pixel grid again after its anchors move.
let top = compound_or_self(doc, *id);
if let Some(n) = doc.node_mut(top) {
super::object::snap_if_aligned(n);
}
}
None => {
if let Some(n) = doc.node_mut(*id) {
n.transform(xf, sc);
super::object::keep_pixel_aligned(n, sc);
}
super::object::keep_compound_aligned(doc, *id, sc);
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
// to the pixel grid again after its anchors move.
let top = compound_or_self(doc, *id);
if let Some(n) = doc.node_mut(top) {
super::object::snap_if_aligned(n);
}
}
}
if is_translation && (delta.x != 0.0 || delta.y != 0.0) {
for &i in &sel.guides {
doc.edit_ruler_guide(i, |g| *g = g.moved(delta));
None => {
if let Some(n) = doc.node_mut(*id) {
n.transform(xf, sc);
super::object::keep_pixel_aligned(n, sc);
}
super::object::keep_compound_aligned(doc, *id, sc);
}
}
Ok(())
})
}
if is_translation && (delta.x != 0.0 || delta.y != 0.0) {
for &i in &sel.guides {
doc.edit_ruler_guide(i, |g| *g = g.moved(delta));
}
}
Ok(())
}
/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles
@@ -2155,6 +2210,7 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0);
let seg = index_opt(p, "segment", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?;
let idx = s.edit("Add Anchor Point", |d, sel| {
let path = path_mut(d, id)?;
let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?;
@@ -2164,8 +2220,9 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
let idx = sp.insert_anchor(seg, t);
renumber_after_insert(sel, id, si, idx);
// A path that wasn't selected becomes the selection, its new anchor direct-selected, so
// the point added shows and can be edited at once (#4237).
if !sel.contains(id) {
// the point added shows and can be edited at once (#4237). `selectAnchor` does the same
// for a path that is selected.
if select_anchor || !sel.contains(id) {
sel.clear();
sel.add(id);
sel.anchors.entry(id).or_default().insert((si, idx));
+1
View File
@@ -141,6 +141,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool),
p!("doubleClickAddsAnchorPoints", "General", "Options", "Double-Click Adds Anchor Points", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
+1 -1
View File
@@ -1252,7 +1252,7 @@ fn swatch_rename_group(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("a swatch or color group named `{name}` already exists")));
}
// A drag still in progress is a step of its own, so canceling or undoing it leaves the rename.
if !s.previewing && s.batch_stash.is_none() && s.in_interaction() {
if !s.previewing && s.batch_stash.is_none() && (s.in_interaction() || s.holds_interaction()) {
super::settle_interaction(s)?;
}
s.edit("Color Group Options", |d, _| {
+7 -2
View File
@@ -340,11 +340,16 @@ pub struct ColorTable {
type Shift = ([u8; 3], [u8; 3]);
/// The most colours a colour table list holds.
const MAX_TABLE: usize = 256;
pub const MAX_TABLE: usize = 256;
/// The error for a deletion that would leave the color table no color for the pixels.
pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table";
/// The error for a colour table list `what` (`colorTable.<what>`) with more than [`MAX_TABLE`] colours.
pub fn too_many(what: &str) -> String {
format!("colorTable.{what}: at most {MAX_TABLE} colours")
}
impl ColorTable {
/// Whether the table is a Custom one: a color was deleted or the palette is fixed.
pub fn is_custom(&self) -> bool {
@@ -353,7 +358,7 @@ impl ColorTable {
fn colors(list: &[String], what: &str) -> std::result::Result<Vec<[u8; 3]>, String> {
if list.len() > MAX_TABLE {
return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours"));
return Err(too_many(what));
}
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
}
+59
View File
@@ -8,6 +8,10 @@ pub struct Interaction {
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
pub preview: Option<(String, Value)>,
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
/// interaction runs its commands inside it.
pub(crate) tool: bool,
/// A replaced or canceled preview restores these new-art paints from before the interaction.
pub(crate) paint: vectorcraft_tools::PaintDefaults,
/// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put
@@ -41,6 +45,61 @@ pub struct Interaction {
pub keep_on_switch: bool,
}
/// An interaction that a command from outside the tool set aside while it runs
/// ([`crate::Session::outside_interaction`]).
#[derive(Debug)]
pub(crate) struct HeldInteraction {
/// The [`crate::DocState::uid`] of the interaction's document.
pub(crate) uid: u64,
pub(crate) interaction: Interaction,
/// The document and the selection on show when the command began, when a preview had changed
/// them from the interaction's snapshot.
pub(crate) shown: Option<(Arc<Document>, Selection)>,
/// The document's current layer, highlighted Layers panel rows, highlighted variable and
/// isolation when the command began; a cancel puts back the ones it changed as it left them.
pub(crate) state: ViewState,
/// The new-art paints when the command began: a change the command makes to them stays when
/// the interaction's next preview or a cancel puts back the paints it began with.
pub(crate) paint: vectorcraft_tools::PaintDefaults,
}
/// The per-document state an interaction puts back when it is canceled, besides the document and
/// the selection.
#[derive(Debug, PartialEq)]
pub(crate) struct ViewState {
pub(crate) active_layer: Option<NodeId>,
pub(crate) layer_rows: Vec<NodeId>,
pub(crate) variables_highlight: Option<String>,
pub(crate) isolation: Option<NodeId>,
}
impl ViewState {
pub(crate) fn of(st: &crate::DocState) -> Self {
ViewState {
active_layer: st.active_layer,
layer_rows: st.layer_rows.clone(),
variables_highlight: st.variables_highlight.clone(),
isolation: st.isolation,
}
}
/// Give `it` the parts of `now` that differ from `self`, the state before a command.
pub(crate) fn rebase(&self, now: ViewState, it: &mut Interaction) {
if now.active_layer != self.active_layer {
it.active_layer = now.active_layer;
}
if now.layer_rows != self.layer_rows {
it.layer_rows = now.layer_rows;
}
if now.variables_highlight != self.variables_highlight {
it.variables_highlight = now.variables_highlight;
}
if now.isolation != self.isolation {
it.isolation = now.isolation;
}
}
}
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
#[derive(Clone, Debug, PartialEq)]
pub enum LastTransform {
+4 -1
View File
@@ -338,6 +338,9 @@ pub struct Session {
/// The warnings of the previews that settling an interaction applied, while a top-level command
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
settled_warnings: Option<Vec<String>>,
/// The interaction a command from outside the tool set aside while it runs
/// ([`Session::outside_interaction`]).
held_interaction: Option<HeldInteraction>,
/// While [`Session::preview`] runs its command: its edits are the interaction's own.
previewing: bool,
/// The images Remove Background decoded during the interaction's preview steps, emptied when
@@ -456,7 +459,7 @@ pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
pub(crate) use interaction::PreviewCopies;
pub(crate) use interaction::{HeldInteraction, PreviewCopies};
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs};
pub use sanity::TOO_DEEP;
+4
View File
@@ -61,6 +61,9 @@ pub struct Prefs {
/// the curve around each one, instead of deleting them with their segments. Off (the default),
/// Clear opens the path there.
pub delete_keeps_paths_joined: bool,
/// General › Double-Click Adds Anchor Points: on, a plain double-click on a path segment with
/// Direct Selection adds an anchor there. Off (the default), the double-click adds nothing.
pub double_click_adds_anchor_points: bool,
pub use_precise_cursors: bool,
pub show_tool_tips: bool,
/// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the
@@ -486,6 +489,7 @@ impl Default for Prefs {
disable_auto_add_delete: false,
interpolate_control_points: false,
delete_keeps_paths_joined: false,
double_click_adds_anchor_points: false,
use_precise_cursors: false,
show_tool_tips: true,
show_tool_cards: false,
+1
View File
@@ -141,6 +141,7 @@ impl Session {
recovery: Default::default(),
in_tool_actions: false,
settled_warnings: None,
held_interaction: None,
previewing: false,
decoded_images: Default::default(),
envelope_defaults: None,
+350
View File
@@ -287,6 +287,190 @@ impl Session {
(r, settled)
}
/// Run `f`, the top-level command `id` with `params` from outside the tool (a panel, a menu
/// item, an automation client), with the active document's tool drag set aside: the command
/// runs on the document the drag started from and records its own undo step and journal entry.
/// The drag then starts from what the command left, and its preview is applied again, so the
/// next preview, the commit and a cancel keep the command's edit, and Undo takes back the drag's
/// step before the command's. While the command runs, [`Session::in_interaction`] is false, so
/// it updates Recent Colors and converts or remaps the new-art paints at once, as it does with
/// no drag in progress.
///
/// The interaction stays as it is, and the command runs inside it, for an interaction a dialog
/// or a panel began (it builds its preview from commands), for typing in progress
/// ([`Session::edit`] keeps it as a step of its own), for the Quick Pen (an edit made outside
/// it ends the path it draws), and for a copy made with `object.transform` during a drag that
/// copies (it copies the document as the drag's move left it). A command that settles,
/// commits or cancels the interaction, or that hands the active tool actions to apply, gets it
/// back first ([`Session::put_back_interaction`]), as it found it.
pub(crate) fn outside_interaction(&mut self, id: &str, params: &Value, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
if cmd::typing_in_progress(self) || self.tool_id() == vectorcraft_tools::quickpen::ID {
return f(self);
}
let Some(st) = self.active_mut() else { return f(self) };
let Some(it) = st.interaction.as_ref().filter(|it| it.tool) else { return f(self) };
// A drag that copies: its latest preview, applied or held back by Real-time Drawing off, copies.
let copying = it.preview.as_ref().is_some_and(|(c, p)| c == "object.transform" && p.get("copy").and_then(Value::as_bool) == Some(true));
if copying && id == "object.transform" && params.get("copy").and_then(Value::as_bool) == Some(true) {
return f(self);
}
let Some(interaction) = st.interaction.take() else { return f(self) };
// The document and selection on show, when a preview changed them.
let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection;
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
if previewed {
st.doc = interaction.doc.clone();
st.selection.clone_from(&interaction.selection);
st.revision += 1;
cmd::globaledit::follow_history(st);
}
let (uid, state) = (st.uid, crate::interaction::ViewState::of(st));
let paint = self.paint.clone();
self.held_interaction = Some(crate::HeldInteraction { uid, interaction, shown, state, paint });
if previewed {
self.sync_front_profiles();
}
let r = f(self);
self.put_back_interaction();
r
}
/// Put back the interaction [`Session::outside_interaction`] set aside. When the command left
/// the document and the selection as it found them, the preview on show before it is on show
/// again. Otherwise the interaction starts from the document the command left and from its
/// own selection, without the objects the command removed, hid or locked, and the preview that Real-time
/// Drawing showed is applied to it again. The warning or the error of that preview goes to
/// the command's result ([`Session::note_settled_warning`]); a preview that fails leaves the
/// interaction with nothing to commit. An interaction whose document the command closed ends,
/// and so does one with anchors or segments selected on a path the command changed in more
/// than a move. A document
/// the command left an interaction of its own on keeps that one.
pub(crate) fn put_back_interaction(&mut self) {
let Some(crate::HeldInteraction { uid, interaction: mut it, shown, state, paint }) = self.held_interaction.take() else { return };
// A selection command loaded the paints of the selection it made into the fill and stroke
// proxies. The drag goes on with its own selection, so they show its paints again.
if self.paint != paint
&& let Some(st) = self.active_mut().filter(|d| d.uid == uid && d.interaction.is_none())
{
let own = drag_selection(&it.selection, &st.doc);
if st.selection != own {
let made = std::mem::replace(&mut st.selection, own);
self.inherit_new_art();
self.load_selection_paints();
if let Some(st) = self.active_mut() {
st.selection = made;
}
}
}
// A change the command made to the new-art paints stays when the next preview or a cancel
// puts back the paints the interaction began with (the Live Paint Bucket's colors); the
// parts it left alone keep the interaction's. The pattern lists every field, so a field
// added to `PaintDefaults` does not compile until it is handled here.
let vectorcraft_tools::PaintDefaults { fill, stroke, stroke_width, appearance, opacity, blend, style, inherited } = &self.paint;
let start = &mut it.paint;
if *fill != paint.fill {
start.fill.clone_from(fill);
}
if *stroke != paint.stroke {
start.stroke.clone_from(stroke);
}
if *stroke_width != paint.stroke_width {
start.stroke_width = *stroke_width;
}
if *appearance != paint.appearance {
start.appearance.clone_from(appearance);
}
if *opacity != paint.opacity {
start.opacity = *opacity;
}
if *blend != paint.blend {
start.blend = *blend;
}
if *style != paint.style {
start.style.clone_from(style);
}
if *inherited != paint.inherited {
start.inherited = *inherited;
}
let active = self.active().is_some_and(|d| d.uid == uid);
let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { return };
if st.interaction.is_some() {
return;
}
// A change the command made to the current layer, the highlighted rows or variable, or
// isolation stays when the interaction is canceled.
state.rebase(crate::interaction::ViewState::of(st), &mut it);
let previewed = shown.is_some();
if Arc::ptr_eq(&st.doc, &it.doc) && st.selection == *it.selection {
if let Some((doc, selection)) = shown {
st.doc = doc;
st.selection = selection;
st.revision += 1;
cmd::globaledit::follow_history(st);
}
st.interaction = Some(it);
if previewed {
self.sync_front_profiles();
}
return;
}
// The drag's anchors and segments are numbered in the paths it began on. When the command
// changed one of those paths in more than a move, the numbers can name other points, and
// the drag ends without a step.
if renumbered(&it.selection, &it.doc, &st.doc) {
self.clear_deferred_overlay_cache();
return;
}
let began = std::mem::replace(&mut it.doc, st.doc.clone());
// The drag acts on the objects it began with: a selection the command made (a paste, a
// duplicate, Select All) does not change what the drag moves.
it.selection = Arc::new(drag_selection(&it.selection, &st.doc));
// The journal holds the selection the command left. The drag's own selection is journaled
// after it, so the drag and the commands after it replay on the objects they act on.
let reselect = (active && st.selection != *it.selection)
.then(|| selection_steps(&it.selection, &st.selection, &st.doc, st.active_layer, &st.highlighted_rows()));
// The objects the drag's preview names leave out those the command removed, hid or locked.
// A preview left naming none has nothing to apply, and the drag records no step.
if it.preview.as_mut().is_some_and(|(_, p)| !drag_targets(p, &began, &st.doc)) {
it.preview = None;
}
it.copies = None;
it.move_box = std::sync::OnceLock::new();
// With Real-time Drawing off the preview waits for the commit, as it did before the command.
let again = it.preview.clone().filter(|_| previewed && active);
// Without a preview to apply, the drag's own selection is on show, as a preview would leave
// it before it acts.
if again.is_none() && st.selection != *it.selection {
st.selection.clone_from(&it.selection);
st.revision += 1;
}
st.interaction = Some(it);
if let Some(steps) = reselect {
let (from, grouped) = (self.journal.len(), self.undo_group_docs());
for step in steps {
self.journal.push(step);
}
self.journal_in_undo_groups(Some(uid), &grouped, from);
}
self.clear_deferred_overlay_cache();
if let Some((cmd, p)) = again {
match self.preview(&cmd, &p) {
Ok(v) => {
if let Some(w) = v.get("warning").and_then(Value::as_str) {
self.note_settled_warning(w);
}
}
Err(e) => self.note_settled_warning(&e.to_string()),
}
}
}
/// While a command from outside the tool runs: the interaction it set aside
/// ([`Session::outside_interaction`]).
pub(crate) fn holds_interaction(&self) -> bool {
self.held_interaction.is_some()
}
/// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings
/// of the preview that keeping typing in progress applied, for its status bar.
pub fn begin_interaction_warned(&mut self, label: &str) -> Result<Vec<String>> {
@@ -311,6 +495,8 @@ impl Session {
if label != "Typing" && cmd::typing_in_progress(self) {
cmd::settle_interaction(self)?;
}
// A command from outside the tool that begins an interaction during a drag joins the drag's.
self.put_back_interaction();
// An edit the tool computes on another thread (a Shape Builder merge) is applied first too,
// so the snapshot the interaction previews from and goes back to holds it.
if !self.in_interaction() {
@@ -327,6 +513,7 @@ impl Session {
doc: st.doc.clone(),
selection: Arc::new(st.selection.clone()),
preview: None,
tool: false,
paint,
used_defaults_only: false,
preview_paint: None,
@@ -347,6 +534,7 @@ impl Session {
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
self.put_back_interaction();
if self.script_running() {
return Err(EngineError::Busy);
}
@@ -438,6 +626,7 @@ impl Session {
fn commit_interaction_unwatched(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
self.put_back_interaction();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
self.paint = paint;
}
@@ -527,6 +716,7 @@ impl Session {
}
pub fn cancel_interaction(&mut self) -> Result<()> {
self.put_back_interaction();
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
self.pending_paint = None;
@@ -567,3 +757,163 @@ impl Session {
self.active().is_some_and(|d| d.interaction.is_some())
}
}
/// The selection a drag began with, without the objects that a command run during it removed,
/// hid or locked in `doc`.
fn drag_selection(began: &Selection, doc: &Document) -> Selection {
let mut selection = began.clone();
selection.prune(doc);
let editable = doc.editable();
let held: Vec<_> = selection.objects.iter().copied().filter(|&id| !editable(id)).collect();
selection.remove_all(held);
selection
}
/// Take out of the `ids` of a drag's preview `params` the objects that a command run during the
/// drag removed from `doc`, or hid or locked there while they were editable in `began` → false
/// when the preview named objects and none of them is left.
fn drag_targets(params: &mut Value, began: &Document, doc: &Document) -> bool {
let Some(ids) = params.get_mut("ids").and_then(Value::as_array_mut) else { return true };
if ids.is_empty() {
return true;
}
let (was, now) = (began.editable(), doc.editable());
ids.retain(|v| v.as_u64().map(vectorcraft_doc::NodeId).is_none_or(|id| doc.node(id).is_some() && (now(id) || !was(id))));
!ids.is_empty()
}
/// Whether a path with anchors or segments in `selection` is other in `doc` than in `began`, the
/// document a drag began from, in more than a move: its anchors added, removed, put in another
/// order (Reverse Path Direction) or reshaped, or a subpath opened or closed. A path the command
/// moved as a whole keeps its numbers.
fn renumbered(selection: &Selection, began: &Document, doc: &Document) -> bool {
fn path(d: &Document, id: vectorcraft_doc::NodeId) -> Option<&[vectorcraft_geom::SubPath]> {
d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.as_slice())
}
selection.anchors.keys().chain(selection.segments.keys()).any(|&id| match (path(began, id), path(doc, id)) {
(Some(was), Some(now)) => !moved_whole(was, now),
(was, now) => was.is_some() != now.is_some(),
})
}
/// Whether the subpaths `now` are the subpaths `was` moved by one offset: the same number of each,
/// each opened or closed as before, every anchor of the same kind, and every anchor and handle
/// offset alike.
fn moved_whole(was: &[vectorcraft_geom::SubPath], now: &[vectorcraft_geom::SubPath]) -> bool {
if was.len() != now.len() || was.iter().zip(now).any(|(a, b)| a.closed != b.closed || a.anchors.len() != b.anchors.len()) {
return false;
}
let mut pairs = was.iter().zip(now).flat_map(|(a, b)| a.anchors.iter().zip(b.anchors.iter()));
let Some((a0, b0)) = pairs.next() else { return true };
let (dx, dy) = (b0.p.x - a0.p.x, b0.p.y - a0.p.y);
let alike = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| {
(b.x - a.x - dx).abs() <= vectorcraft_geom::EPS && (b.y - a.y - dy).abs() <= vectorcraft_geom::EPS
};
std::iter::once((a0, b0)).chain(pairs).all(|(a, b)| a.kind == b.kind && alike(a.p, b.p) && alike(a.h_in, b.h_in) && alike(a.h_out, b.h_out))
}
/// The journal entries that select `selection` again in `doc` after `made`, the selection a
/// command left with `layer` current and `rows` highlighted in the Layers panel ([`object_steps`]).
/// When selecting the objects would make another layer current, `layer.setCurrent` makes `layer`
/// current again, as the drag leaves it, and `layer.highlight` gives back the highlighted rows.
fn selection_steps(
selection: &Selection,
made: &Selection,
doc: &Document,
layer: Option<vectorcraft_doc::NodeId>,
rows: &[vectorcraft_doc::NodeId],
) -> Vec<(String, Value)> {
let mut steps = object_steps(selection, doc);
// `layer.target` on a layer makes it current; any other change to the selected objects makes
// the layer of the last selected object current.
let targeted = steps.first().is_some_and(|(id, _)| id == "layer.target");
let selects = match selection.target.filter(|t| targeted && doc.node(*t).is_some_and(|n| n.is_layer())) {
Some(t) => Some(t),
None if selection.objects != made.objects => {
selection.objects.last().and_then(|id| doc.layer_containing(*id)).filter(|l| doc.is_editable(*l))
}
None => None,
};
if let Some(layer) = layer.filter(|l| selects.is_some_and(|s| s != *l)) {
steps.push(("layer.setCurrent".into(), serde_json::json!({ "id": layer.0 })));
// `layer.setCurrent` highlights the layer's row. `layer.highlight` sets the rows the command
// left instead; it keeps `layer` current while the last of them is on `layer`, or none is left.
if rows != [layer] && rows.last().is_none_or(|r| doc.layer_containing(*r) == Some(layer)) {
let ids: Vec<u64> = rows.iter().map(|r| r.0).collect();
steps.push(("layer.highlight".into(), serde_json::json!({ "ids": ids, "mode": "set" })));
}
}
steps
}
/// The journal entries that select `selection` in `doc`: the selections made on their own (its
/// slices with `object.slice.select`, its target with `layer.target`, its symbol part with
/// `symbol.instance.selectPart`, its Objects on Path member with
/// `object.objectsOnPath.selectMember`), or its objects in their order (`select.set`), the anchors
/// left out on paths that are not selected whole (`select.anchorsMany`), the anchors of paths with
/// every anchor selected (`select.anchors`) and its segments (`select.segments`); after its objects
/// or its target, its ruler guides (`guide.select`) and its key object, key guide or key anchor
/// (`select.key`).
fn object_steps(selection: &Selection, doc: &Document) -> Vec<(String, Value)> {
use serde_json::json;
if !selection.slices.is_empty() {
let slices: Vec<u64> = selection.slices.iter().map(|id| id.0).collect();
return vec![("object.slice.select".into(), json!({ "slices": slices }))];
}
// A target is selected again only while targeting it selects the same objects: when a command
// added art to a targeted layer, `select.set` selects the drag's objects.
let targets = |t: vectorcraft_doc::NodeId| match doc.node(t) {
Some(n) if n.is_layer() => n.layer_art(true) == selection.objects,
_ => selection.objects == [t],
};
let json_refs = |refs: &mut dyn Iterator<Item = &(usize, usize)>| Value::Array(refs.map(|&(a, b)| json!([a, b])).collect());
// A targeted object keeps the ruler guides and the key selected beside it.
let mut steps = if let Some(t) = selection.target.filter(|&t| targets(t)) {
vec![("layer.target".to_string(), json!({ "id": t.0 }))]
} else if let Some(part) = &selection.symbol_part {
return vec![("symbol.instance.selectPart".into(), json!({ "id": part.instance.0, "path": part.path }))];
} else if let Some(member) = selection.on_path_member {
return vec![("object.objectsOnPath.selectMember".into(), json!({ "member": member.0 }))];
} else {
let ids: Vec<u64> = selection.objects.iter().map(|id| id.0).collect();
let mut steps = vec![("select.set".to_string(), json!({ "ids": ids }))];
// `select.set` selects each path whole: subtracting the anchors that are not selected leaves
// the ones that are, and keeps the order of the objects. A path with every anchor selected
// as anchors gets them back with `select.anchors`, which keeps them all as anchors.
let mut every = Vec::new();
let partial: Vec<Value> = selection
.objects
.iter()
.filter_map(|id| {
let refs = selection.anchors.get(id)?;
let path = doc.node(*id)?.path_data()?;
let out: Vec<(usize, usize)> = path.anchors().map(|(s, i, _)| (s, i)).filter(|r| !refs.contains(r)).collect();
if out.is_empty() {
every.push(("select.anchors".to_string(), json!({ "id": id.0, "anchors": json_refs(&mut refs.iter()), "mode": "add" })));
return None;
}
Some(json!({ "id": id.0, "anchors": json_refs(&mut out.iter()) }))
})
.collect();
if !partial.is_empty() {
steps.push(("select.anchorsMany".into(), json!({ "items": partial, "mode": "subtract" })));
}
steps.extend(every);
for (id, refs) in &selection.segments {
steps.push(("select.segments".into(), json!({ "id": id.0, "segments": json_refs(&mut refs.iter()), "mode": "add" })));
}
steps
};
if !selection.guides.is_empty() {
let indexes = cmd::guide_indexes(doc, &selection.guides);
steps.push(("guide.select".into(), json!({ "indexes": indexes, "toggle": true })));
}
if let Some((id, (s, i))) = selection.key_anchor {
steps.push(("select.key".into(), json!({ "id": id.0, "anchor": [s, i] })));
} else if let Some(g) = selection.key_guide.and_then(|g| cmd::guide_indexes(doc, &[g]).first().copied()) {
steps.push(("select.key".into(), json!({ "guide": g })));
} else if let Some(key) = selection.key {
steps.push(("select.key".into(), json!({ "id": key.0 })));
}
steps
}
+8 -1
View File
@@ -99,10 +99,17 @@ impl Session {
self.finish_tool_edit_later()?;
}
let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
// A command from outside the tool, while the tool's drag is in progress, is a step of its
// own before the drag's ([`Session::outside_interaction`]). Find Objects with `select` is
// journaled (`Session::journal_query`), so it is one too.
let find_selects = id == "document.find" && params.get("select").and_then(Value::as_bool) == Some(true);
let outside = (spec.journal || find_selects) && !self.previewing && !self.in_tool_actions;
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
// before Undo) reports its warning in the command's result.
let r = if self.depth == 0 {
let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params));
let (r, settled) = self.collect_settled_warnings(|s| {
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
});
r.map(|v| with_settled_warnings(v, &settled))
} else {
self.execute_spec(spec, id, params)
+3
View File
@@ -54,6 +54,7 @@ mod distort;
mod docsetup;
mod document_close;
mod document_move;
mod double_click_adds_anchor;
mod draw2;
mod dynamic_symbols;
mod dynamic_text;
@@ -88,6 +89,7 @@ mod history_document;
mod history_mem;
mod ids_without_selection;
mod inline;
mod interaction_commands;
mod interactivity;
mod interpolate_handles;
mod intertwine;
@@ -180,6 +182,7 @@ mod script_include;
mod script_io;
mod script_run;
mod scripts;
mod segment_nudge;
mod select_effects;
mod select_ids_first;
mod shaper;
+17
View File
@@ -145,6 +145,23 @@ fn item_rows_follow_remove_and_move() {
assert_eq!(s.appearance_item(), None);
}
#[test]
fn moving_a_single_row_keeps_the_active_objects_landing() {
let mut s = session();
let short = rect(&mut s, 50.0);
let long = rect(&mut s, 200.0);
run(&mut s, "appearance.addFill", json!({}));
run(&mut s, "select.set", json!({"ids": [short.0, long.0]}));
run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
let moved = run(&mut s, "appearance.moveItem", json!({"ids": [short.0, long.0], "from": 0, "to": 2}));
assert_eq!(moved["index"], 2, "the command still reports the last target's landing");
assert!(matches!(node(&s, short).appearance.items[1], AppearanceItem::Fill(_)));
assert!(matches!(node(&s, long).appearance.items[0], AppearanceItem::Stroke(_)));
assert_eq!(s.appearance_item(), Some(1), "the active row follows its own object's landing");
}
#[test]
fn transparency_goes_to_the_targeted_item() {
let mut s = session();
+4 -1
View File
@@ -1357,7 +1357,10 @@ fn brush_freehand_refuses_unknown_keys() {
let spec = crate::cmd::find_command("brush.freehand").unwrap();
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
keys.sort_unstable();
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "redraw", "style"]);
assert_eq!(
keys,
["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"]
);
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[a]);
@@ -0,0 +1,124 @@
//! General › Double-Click Adds Anchor Points (`doubleClickAddsAnchorPoints`). With it on, a
//! Direct Selection double-click on a path segment adds an anchor there. Off (the default), the
//! double-click adds nothing.
use serde_json::json;
use vectorcraft_geom::kurbo::ParamCurveNearest;
use vectorcraft_geom::{ParamCurve, PathData, Point};
use vectorcraft_tools::{PointerEvent, PointerKind};
use super::history;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn set_pref(s: &mut Session, key: &str, on: bool) {
s.execute("prefs.set", &json!({"key": key, "value": on})).unwrap();
}
fn path_of(s: &Session, id: NodeId) -> Option<PathData> {
s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned())
}
fn points(s: &Session, id: NodeId) -> Vec<Point> {
path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect()
}
/// Two clicks and the double-click that follows them, with Direct Selection, at `at`. On a segment
/// the clicks select it, so the double-click finds its path selected.
fn double_click(s: &mut Session, at: Point) {
let v = ViewInfo::default();
s.select_tool("directSelection", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, at.x, at.y), v).unwrap();
}
}
/// An open curve from (100, 300) to (300, 300) whose middle, at t = 0.5, is (200, 225).
fn arch(s: &mut Session) -> NodeId {
let anchors = json!([{"x": 100, "y": 300, "out": [100, 200]}, {"x": 300, "y": 300, "in": [300, 200]}]);
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": false })).unwrap()["id"].as_u64().unwrap())
}
#[test]
fn off_by_default() {
let s = session();
assert!(!s.prefs.double_click_adds_anchor_points);
}
#[test]
fn with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_in_one_undo_step() {
// The clicks before the double-click select the segment either way; an unselected path at the
// double-click is covered by the tools crate's tests.
for selected in [true, false] {
let mut s = session();
set_pref(&mut s, "doubleClickAddsAnchorPoints", true);
let id = arch(&mut s);
if !selected {
s.execute("select.none", &json!({})).unwrap();
}
let curve = path_of(&s, id).unwrap().subpaths[0].segment(0);
let before = history(&s).0;
double_click(&mut s, Point::new(200.0, 225.0));
assert_eq!(history(&s).0, before + 1, "one undo step (selected before the clicks: {selected})");
assert_eq!(points(&s, id).len(), 3, "an anchor is added (selected before the clicks: {selected})");
assert!(points(&s, id)[1].distance(Point::new(200.0, 225.0)) < 0.5, "at the clicked point: {:?}", points(&s, id));
let halves = path_of(&s, id).unwrap().subpaths[0].clone();
for seg in 0..2 {
for t in [0.25, 0.5, 0.75] {
let q = ParamCurve::eval(&halves.segment(seg), t);
let d = ParamCurveNearest::nearest(&curve, q, 1e-9).distance_sq;
assert!(d < 1e-6, "the curve keeps its shape at {q:?}");
}
}
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, vec![id]);
assert_eq!(st.selection.anchors.get(&id), Some(&[(0, 1)].into()), "only the new anchor is selected (selected before the clicks: {selected})");
assert!(st.selection.segments.get(&id).is_none_or(|s| s.is_empty()), "no segment stays selected");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(points(&s, id).len(), 2, "undo removes it");
}
}
#[test]
fn with_the_preference_off_a_double_click_on_a_segment_adds_nothing() {
let mut s = session();
let id = arch(&mut s);
let before = history(&s).0;
double_click(&mut s, Point::new(200.0, 225.0));
assert_eq!(history(&s).0, before);
assert_eq!(points(&s, id).len(), 2);
}
/// The two General preferences are separate: Delete Removes Anchor Points and Keeps Paths Joined
/// does not turn on the double-click, and the double-click preference does not change Delete.
#[test]
fn the_double_click_and_delete_preferences_are_separate() {
let mut s = session();
set_pref(&mut s, "deleteKeepsPathsJoined", true);
let id = arch(&mut s);
let before = history(&s).0;
double_click(&mut s, Point::new(200.0, 225.0));
assert_eq!(history(&s).0, before, "deleteKeepsPathsJoined alone adds no anchor");
assert_eq!(points(&s, id).len(), 2);
let mut s = session();
set_pref(&mut s, "doubleClickAddsAnchorPoints", true);
let anchors = json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]);
let id = NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap());
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "Delete still opens the path");
}
#[test]
fn the_select_anchor_param_must_be_a_boolean() {
let mut s = session();
let id = arch(&mut s);
assert!(s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "selectAnchor": "yes"})).is_err());
assert_eq!(points(&s, id).len(), 2, "a refused call changes nothing");
}
+389 -5
View File
@@ -198,6 +198,12 @@ fn near(a: Point, b: Point) -> bool {
a.distance(b) < 1e-6
}
/// Whether open subpath `sp`'s two ends are at `a` and `b`, in either order (within `tol`).
fn ends_at(sp: &vectorcraft_geom::SubPath, a: Point, b: Point, tol: f64) -> bool {
let (Some(f), Some(l)) = (sp.anchors.first(), sp.anchors.last()) else { return false };
(f.p.distance(a) < tol && l.p.distance(b) < tol) || (f.p.distance(b) < tol && l.p.distance(a) < tol)
}
fn area(pd: &PathData) -> f64 {
vectorcraft_pathops::area(pd, FillRule::NonZero)
}
@@ -519,7 +525,8 @@ fn pencil_redraws_the_section_of_a_selected_path_between_its_ends() {
}
/// On a closed path the stroke replaces the shorter way between where it starts and ends, and the
/// path stays closed; a stroke that doesn't end on the path draws a new one.
/// path stays closed; a stroke that doesn't end on the path opens it where the stroke starts and
/// ends where the stroke does (no new path).
#[test]
fn pencil_redraws_the_shorter_way_round_a_closed_path() {
let mut s = session();
@@ -536,11 +543,12 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() {
}
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
assert!(top < -20.0, "the dip: top {top}");
// Not ending on the path: a new path, the rectangle as it was.
let before = path(&s, id);
// Not ending on the path: the rectangle opens at (50, 100) and follows the stroke out.
s.execute("path.freehand", &json!({"points": [[50, 100], [80, 150], [120, 160]], "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 2);
assert_eq!(path(&s, id), before);
assert_eq!(paths(&s).len(), 1, "no new path");
let sp = &path(&s, id).subpaths[0];
assert!(!sp.closed, "the rectangle opened");
assert!(ends_at(sp, Point::new(50.0, 100.0), Point::new(120.0, 160.0), 1e-6), "from the opening to the stroke's end: {sp:?}");
assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err());
}
@@ -7037,6 +7045,382 @@ fn pencil_redraws_a_selected_compound_path() {
assert!(members(&s)[1] != before[1], "the hole is redrawn");
}
/// A Pencil stroke that starts on a selected closed shape and is lifted away from it takes the
/// shape with it: the shape opens where the stroke started, keeps its whole outline, fill and
/// selection, and ends where the pen was lifted. While the stroke is drawn the shape stays as it
/// was and the selection with it (the preview shows the stroke on its own); the release leaves no
/// new path.
#[test]
fn a_stroke_lifted_away_from_a_closed_shape_opens_it_and_follows_the_stroke() {
let mut s = session();
s.execute("select.none", &json!({})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().clone();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.set_tool_option_cmd(&json!({"tool": "pencil", "values": {"editWithin": 12}})).unwrap();
let v = view();
s.select_tool("pencil", v).unwrap();
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
let shape = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone();
let before = shape(&s);
// From the right edge, a little hook up and out to the right.
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 150.0), v).unwrap();
for (x, y) in [(303.0, 140.0), (308.0, 128.0), (316.0, 118.0), (326.0, 112.0), (338.0, 110.0)] {
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
assert!(shape(&s) == before, "the shape stays as it was while the stroke is drawn");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "and stays selected");
}
s.pointer(&PointerEvent::new(PointerKind::Up, 338.0, 110.0), v).unwrap();
assert_eq!(count(&s), 1, "no new path");
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "the shape stays selected");
let n = s.doc().unwrap().doc.node(id).unwrap();
assert_eq!(n.appearance.fill_paint(), fill, "the fill stays");
let sp = &n.path_data().unwrap().subpaths[0];
assert!(!sp.closed, "the shape opened");
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
for corner in [(100.0, 100.0), (300.0, 100.0), (300.0, 200.0), (100.0, 200.0)] {
assert!(ps.iter().any(|p| near(*p, Point::new(corner.0, corner.1))), "{corner:?} kept: {ps:?}");
}
assert!(ends_at(sp, Point::new(300.0, 150.0), Point::new(338.0, 110.0), 0.5), "from the opening to where the pen was lifted: {ps:?}");
// The outline joins the stroke heading up, the stroke's way: next to the anchor where the
// stroke leaves the opening is the bottom right corner.
let last = ps.len() - 1;
let k = (1..last).find(|&i| ps[i].distance(Point::new(300.0, 150.0)) < 0.5).unwrap();
assert!(near(ps[k - 1], Point::new(300.0, 200.0)) || near(ps[k + 1], Point::new(300.0, 200.0)), "joins from below: {ps:?}");
}
/// On an open path, a stroke from its middle lifted away from it cuts the path there and drops the
/// part the stroke heads along; the part behind stays and ends where the pen was lifted.
#[test]
fn a_stroke_lifted_away_from_an_open_path_drops_the_part_it_heads_along() {
for (towards_end, kept) in [(true, Point::new(100.0, 100.0)), (false, Point::new(300.0, 100.0))] {
let mut s = session();
let id = line(&mut s, 100.0, 100.0, 300.0, 100.0);
let dx = if towards_end { 1.0 } else { -1.0 };
let pts: Vec<_> = (0..8).map(|i| json!([200.0 + dx * 4.0 * f64::from(i), 100.0 - 5.0 * f64::from(i)])).collect();
s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 1, "no new path");
let sp = &path(&s, id).subpaths[0];
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
assert!(
ends_at(sp, kept, Point::new(200.0 + dx * 28.0, 65.0), 0.5),
"towards the end {towards_end}: the part behind stays and ends where the pen was lifted: {ps:?}"
);
let dropped = Point::new(if towards_end { 300.0 } else { 100.0 }, 100.0);
assert!(!ps.iter().any(|p| p.distance(dropped) < 1.0), "the part ahead is dropped: {ps:?}");
}
}
/// A stroke that leaves a selected path and comes back to the same point adds a loop there; the
/// path stays closed and keeps its corners.
#[test]
fn a_stroke_back_to_where_it_started_adds_a_loop() {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
let before = path(&s, id).subpaths[0].anchors.len();
let loop_pts = json!([[100, 0], [90, -15], [95, -35], [110, -38], [120, -20], [108, -8], [100, 0]]);
s.execute("path.freehand", &json!({"points": loop_pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 1, "no new path");
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed && sp.anchors.len() > before, "{sp:?}");
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
assert!(top < -30.0, "the loop: top {top}");
for corner in [(0.0, 0.0), (200.0, 0.0), (200.0, 100.0), (0.0, 100.0)] {
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "{corner:?} kept");
}
}
/// On a closed path the stroke replaces the way round it heads from its start, even when that is
/// the longer way: the shape doesn't flip to the other side as the stroke goes on.
#[test]
fn a_redraw_of_a_closed_path_goes_the_way_the_stroke_heads() {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
// From (20, 0) out to the left, round below the rectangle and up its right side to (180, 0).
let pts = json!([[20, 0], [10, -15], [-20, -10], [-25, 50], [-20, 120], [100, 125], [220, 120], [225, 50], [210, -10], [190, -12], [180, 0]]);
s.execute("path.freehand", &json!({"points": pts, "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 1);
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed);
let ps: Vec<Point> = sp.anchors.iter().map(|a| a.p).collect();
// The rectangle's left, bottom and right sides went with the stroke; its top between 20 and
// 180 stays.
for corner in [(0.0, 0.0), (0.0, 100.0), (200.0, 100.0), (200.0, 0.0)] {
assert!(!ps.iter().any(|p| p.distance(Point::new(corner.0, corner.1)) < 1.0), "{corner:?} replaced: {ps:?}");
}
let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(b.y1 > 115.0 && b.x0 < -15.0, "the stroke's way round: {b:?}");
}
/// A stroke lifted farther from the path than Edit selected paths within takes the path with it;
/// one lifted within that distance joins it again, its end bent smoothly onto it.
#[test]
fn a_stroke_lifted_beyond_the_edit_distance_takes_the_path_along() {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
// A hook out of the right side that ends 8 pt from it.
let hook = json!([[200, 50], [210, 40], [222, 38], [226, 46], [222, 56], [208, 58]]);
s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": id.0, "within": 4}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(!sp.closed, "8 pt away with 4 pt to edit within: the shape opened");
let ends = [sp.anchors.first().unwrap().p, sp.anchors.last().unwrap().p];
assert!(ends.iter().any(|p| p.distance(Point::new(208.0, 58.0)) < 0.5), "it ends where the pen was lifted: {ends:?}");
}
/// A shape with a hole that opens keeps its outline running its own way, so the hole stays a hole.
#[test]
fn opening_a_shape_with_a_hole_keeps_the_hole() {
for heads_back in [false, true] {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
let hole = rect(&mut s, 50.0, 50.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [outer.0, hole.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.doc().unwrap().selection.objects[0];
let member = |s: &Session, i: usize| s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[i].clone();
let (outer_id, sign) = {
let m = member(&s, 0);
(m.id, m.path_data().unwrap().subpaths[0].signed_area().signum())
};
// A hook out of the top edge, heading one way or the other along it.
let dx = if heads_back { -1.0 } else { 1.0 };
let hook: Vec<_> = (0..6).map(|i| json!([100.0 + dx * 6.0 * f64::from(i), -5.0 * f64::from(i)])).collect();
s.execute("path.freehand", &json!({"points": hook, "redraw": {"id": outer_id.0, "within": 4}})).unwrap();
let sp = member(&s, 0).path_data().unwrap().subpaths[0].clone();
assert!(!sp.closed, "heads back {heads_back}: opened");
assert_eq!(sp.signed_area().signum(), sign, "heads back {heads_back}: the outline runs its own way, the hole stays a hole");
}
}
/// A stroke across a shape from one point of its outline to another carves off the part it cuts
/// across, the lobe on that side, and keeps the rest, whichever way it is drawn.
#[test]
fn a_stroke_across_a_shape_carves_off_the_part_it_cuts() {
for reversed in [false, true] {
let mut s = session();
// A wide shape with a lobe on top between x = 80 and x = 120.
let shape = json!([[0, 0], [80, 0], [80, -60], [120, -60], [120, 0], [300, 0], [300, 100], [0, 100]]);
let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "closed": true, "fidelity": 0.01})).unwrap()["id"].as_u64().unwrap());
// Across the lobe's base, a little inside the shape.
let mut cut = vec![json!([70, 0]), json!([85, 8]), json!([100, 10]), json!([115, 8]), json!([130, 0])];
if reversed {
cut.reverse();
}
s.execute("path.freehand", &json!({"points": cut, "redraw": {"id": id.0, "within": 4}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}");
let b = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(b.y0 > -20.0, "reversed {reversed}: the lobe (up to y = -60) is carved off: {b:?}");
assert!(b.x1 > 295.0 && b.y1 > 95.0, "reversed {reversed}: the rest stays: {b:?}");
}
}
/// A stroke leaving an open path across it (no direction along it) drops the nearer, short side,
/// not most of the path.
#[test]
fn a_stroke_leaving_an_open_path_across_it_drops_the_side_it_is_near() {
let mut s = session();
let id = line(&mut s, 100.0, 100.0, 300.0, 100.0);
// Straight up from x = 280, then bending towards the near end.
let up = json!([[280, 100], [280, 90], [281, 75], [284, 60], [290, 50]]);
s.execute("path.freehand", &json!({"points": up, "redraw": {"id": id.0, "within": 4}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(ends_at(sp, Point::new(100.0, 100.0), Point::new(290.0, 50.0), 0.5), "the long side stays: {sp:?}");
}
/// A stroke drawn over an open shape's open ends, from near one end to near the other, redraws
/// those ends along the stroke and closes the shape, whichever way it is drawn; the shape's body
/// between stays.
#[test]
fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() {
for reversed in [false, true] {
let mut s = session();
// A C open on the right: from the top right round the left to the bottom right.
let c: Vec<_> = (0..=30)
.map(|i| {
let a = (40.0 + 280.0 * f64::from(i) / 30.0).to_radians();
json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()])
})
.collect();
let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap());
let on = |deg: f64| {
let a = deg.to_radians();
(200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin())
};
// From the C near its top end, out round the open side, back onto it near the bottom end.
let (a, b) = (on(60.0), on(300.0));
let mut stroke = vec![json!([a.0, a.1]), json!([290.0, 150.0]), json!([315.0, 200.0]), json!([290.0, 250.0]), json!([b.0, b.1])];
if reversed {
stroke.reverse();
}
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 1, "reversed {reversed}: no new path");
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}: the shape closed");
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(bb.x1 > 310.0 && bb.x0 < 105.0, "reversed {reversed}: closed along the stroke, the body kept: {bb:?}");
// The old ends (at 40° and 320°) are gone.
for deg in [40.0, 320.0] {
let e = on(deg);
assert!(!sp.anchors.iter().any(|q| q.p.distance(Point::new(e.0, e.1)) < 1.0), "reversed {reversed}: the end at {deg}° is redrawn");
}
}
}
/// A stroke that starts and ends on an open path decides by the way it runs along the path at its
/// ends: where it starts it replaces the part it runs along, where it lands it joins the part it runs
/// into, an end that goes straight off or onto the path follows the other end, and when both do it
/// closes only round both pieces beyond. A stroke lifted away from the path ends there. The path is
/// an L whose bottom arm turns up and back over to a hook near the upright arm.
#[test]
fn a_redraw_on_an_open_path_follows_the_way_its_ends_run() {
// From the upright arm's top (100, 0) down, along the bottom, up the right side, back along the
// top to the hook, which ends at (160, 60).
let shape = [[100.0, 0.0], [100.0, 300.0], [400.0, 300.0], [400.0, 100.0], [160.0, 100.0], [160.0, 60.0]];
// A stroke through `pts`, a point every 2 pt, as a hand draws it.
let dense = |pts: &[[f64; 2]]| {
let mut out = vec![json!(pts[0])];
for w in pts.windows(2) {
let (a, b) = (Point::new(w[0][0], w[0][1]), Point::new(w[1][0], w[1][1]));
let n = (a.distance(b) / 2.0).ceil().max(1.0) as usize;
out.extend((1..=n).map(|i| {
let q = a.lerp(b, i as f64 / n as f64);
json!([q.x, q.y])
}));
}
out
};
let has = |sp: &vectorcraft_geom::SubPath, x: f64, y: f64| sp.anchors.iter().any(|a| a.p.distance(Point::new(x, y)) < 1.0);
// Over the loop above the path, from the top edge round to the left of the upright arm.
let over = [[250.0, 40.0], [200.0, -30.0], [100.0, -40.0], [40.0, 0.0]];
// Each: its name, the stroke, and whether the path is closed and keeps the bottom right corner,
// the upright arm's top and the hook's end.
let cases = [
// Runs along the top towards the hook, then up the upright arm: the hook goes, the end is
// left where the pen is lifted, on the arm, and the rest of the path stays.
(
"towards the hook, landing up the arm",
vec![[250.0, 100.0], [165.0, 100.0], [130.0, 95.0], [100.0, 90.0], [100.0, 40.0]],
[false, true, true, false],
),
// Runs along the top away from the hook, then lands running up the arm: the part between
// is replaced, both ends stay.
(
"away from the hook, landing up the arm",
vec![[250.0, 100.0], [300.0, 100.0], [320.0, 60.0], [250.0, 30.0], [140.0, 40.0], [100.0, 90.0], [100.0, 60.0]],
[false, false, true, true],
),
// Straight up off the top, over the arm's top, landing running down the arm: the arm's top and
// the hook go and the path closes round the rest.
(
"straight off, landing down the arm",
[&[[250.0, 100.0]][..], &over, &[[40.0, 120.0], [85.0, 140.0], [100.0, 150.0], [100.0, 180.0]]].concat(),
[true, true, false, false],
),
// Straight off and straight onto the arm, round both the arm's top and the hook: it closes.
("straight off and on, round both", [&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0]]].concat(), [true, true, false, false]),
// The same loop carried on across the arm and lifted inside: the path ends there; the hook,
// the shorter side, goes.
(
"across the arm, lifted away",
[&[[250.0, 100.0]][..], &over, &[[40.0, 150.0], [100.0, 150.0], [200.0, 160.0]]].concat(),
[false, true, true, false],
),
];
for (name, stroke, [closed, body, top, hook]) in cases {
let mut s = session();
let id = NodeId(s.execute("path.freehand", &json!({"points": shape, "fit": false})).unwrap()["id"].as_u64().unwrap());
s.execute("path.freehand", &json!({"points": dense(&stroke), "redraw": {"id": id.0, "within": 12}})).unwrap();
assert_eq!(paths(&s).len(), 1, "{name}: no new path");
let sp = &path(&s, id).subpaths[0];
assert_eq!(sp.closed, closed, "{name}: closed: {sp:?}");
assert_eq!(has(sp, 400.0, 300.0), body, "{name}: the bottom right corner: {sp:?}");
assert_eq!(has(sp, 100.0, 0.0), top, "{name}: the upright arm's top: {sp:?}");
assert_eq!(has(sp, 160.0, 60.0), hook, "{name}: the hook's end: {sp:?}");
}
}
/// A stroke that starts on an open C's upper arm running towards its end, goes round the opening
/// and lands on the lower arm running back into the C closes it into a ring.
#[test]
fn a_stroke_run_over_both_arms_of_a_c_closes_it() {
let mut s = session();
let on = |deg: f64| {
let a = deg.to_radians();
json!([200.0 + 100.0 * a.cos(), 200.0 - 100.0 * a.sin()])
};
let c: Vec<_> = (0..=28).map(|i| on(40.0 + 10.0 * f64::from(i))).collect();
let id = NodeId(s.execute("path.freehand", &json!({"points": c, "fidelity": 0.5})).unwrap()["id"].as_u64().unwrap());
let mut stroke: Vec<_> = (0..=8).map(|i| on(56.0 - 2.0 * f64::from(i))).collect();
stroke.extend([json!([300.0, 160.0]), json!([310.0, 200.0]), json!([300.0, 240.0])]);
stroke.extend((0..=8).map(|i| on(324.0 - 2.0 * f64::from(i))));
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "a ring: {sp:?}");
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(bb.x0 < 105.0 && bb.x1 > 300.0, "the C's body and the stroke: {bb:?}");
}
/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and
/// the line stays open.
#[test]
fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() {
for reversed in [false, true] {
let mut s = session();
let id = line(&mut s, 100.0, 300.0, 700.0, 300.0);
let mut bump =
vec![json!([200, 300]), json!([250, 226]), json!([325, 148]), json!([400, 120]), json!([475, 148]), json!([550, 226]), json!([600, 300])];
if reversed {
bump.reverse();
}
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(!sp.closed, "reversed {reversed}: still open");
assert!(ends_at(sp, Point::new(100.0, 300.0), Point::new(700.0, 300.0), 1e-6), "reversed {reversed}: both ends stay: {sp:?}");
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 135.0, "reversed {reversed}: the bump");
}
}
/// A tall arch over one long side of a thin closed shape replaces that side: the result is the
/// bigger of the two shapes the stroke could make, not the arch alone.
#[test]
fn a_tall_arch_over_a_thin_shapes_side_keeps_the_shape() {
for reversed in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 300.0, 600.0, 60.0);
let mut arch =
vec![json!([130, 300]), json!([197, 216]), json!([265, 144]), json!([400, 80]), json!([535, 144]), json!([603, 216]), json!([670, 300])];
if reversed {
arch.reverse();
}
s.execute("path.freehand", &json!({"points": arch, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}");
for corner in [(100.0, 300.0), (700.0, 300.0), (700.0, 360.0), (100.0, 360.0)] {
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "reversed {reversed}: {corner:?} kept: {sp:?}");
}
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 95.0, "reversed {reversed}: the arch");
}
}
/// A stroke that comes back near the path, within Edit selected paths within but not on it, joins
/// it again: the shape stays one closed path, and the stroke's end bends onto it, so no anchor
/// lies off the stroke's way back.
#[test]
fn a_stroke_back_near_the_path_joins_it_smoothly() {
let mut s = session();
let id = rect(&mut s, 0.0, 0.0, 200.0, 100.0);
// A bump out of the top edge that comes back down to 10 pt above it.
let bump = json!([[40, 0], [45, -20], [60, -40], [80, -45], [100, -40], [115, -25], [120, -10]]);
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 20}})).unwrap();
assert_eq!(paths(&s).len(), 1);
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "joined again: still closed");
let top = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0;
assert!(top < -35.0, "the bump: top {top}");
}
/// With the Pencil's Live preview off, nothing is added to the document while a filled stroke is
/// drawn; the release draws the path with its fill, as one undo step.
#[test]
@@ -0,0 +1,829 @@
//! A command run from outside the tool (a panel, a menu item, an automation client) while a tool's drag is
//! in progress is a step of its own, before the drag's: the drag's next preview, its release and
//! Escape keep the command's edit, and the release still draws what the drag drew, with Real-time
//! Drawing on and off.
use serde_json::json;
use vectorcraft_geom::Rect;
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
use crate::*;
/// The view the gestures run in: page coordinates, with Smart Guides off so nothing snaps.
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
/// Feed the pointer event `(kind, x, y)` to the active tool.
fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) {
s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap();
}
/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding one 20 × 20 pt rectangle
/// (returned), nothing selected, and the Rectangle tool chosen.
fn session(real_time: bool) -> (Session, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
s.execute("select.none", &json!({})).unwrap();
s.select_tool("rectangle", view()).unwrap();
(s, other)
}
fn visible(s: &Session, id: NodeId) -> bool {
s.doc().unwrap().doc.node(id).expect("the object is in the document").visible
}
/// The objects of the document's first layer.
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers[0].children().map_or(0, Vec::len)
}
/// The commands journaled from entry `start` on.
fn journaled(s: &Session, start: usize) -> Vec<String> {
s.journal.iter().skip(start).map(|(id, _)| id.clone()).collect()
}
#[test]
fn a_command_during_a_drag_is_a_step_of_its_own_before_the_drag() {
for real_time in [true, false] {
let (mut s, other) = session(real_time);
let (steps, start) = (s.doc().unwrap().history.undo.len(), s.journal.len());
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
assert!(!visible(&s, other), "real time {real_time}: the command hides the object at once");
pointer(&mut s, PointerKind::Drag, 200.0, 180.0);
assert!(!visible(&s, other), "real time {real_time}: the drag's next preview keeps the command's edit");
pointer(&mut s, PointerKind::Up, 200.0, 180.0);
assert!(!visible(&s, other), "real time {real_time}: the release keeps the command's edit");
assert_eq!(objects(&s), 2, "real time {real_time}: the release draws the rectangle");
let drawn = s.doc().unwrap().selection.objects[0];
assert_ne!(drawn, other);
assert_eq!(s.doc().unwrap().doc.bounds_of(&[drawn], false), Some(Rect::new(100.0, 100.0, 200.0, 180.0)), "real time {real_time}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the command and the drag are a step each");
assert_eq!(journaled(&s, start), ["object.hide", "shape.rectangle"], "real time {real_time}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(objects(&s), 1, "real time {real_time}: Undo takes back the drawn rectangle");
assert!(!visible(&s, other), "real time {real_time}: and leaves the command's edit");
s.execute("edit.undo", &json!({})).unwrap();
assert!(visible(&s, other), "real time {real_time}: the next Undo takes back the command's edit");
}
}
#[test]
fn escape_after_a_command_during_a_drag_keeps_the_command() {
for real_time in [true, false] {
let (mut s, other) = session(real_time);
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
assert!(!visible(&s, other), "real time {real_time}: Escape takes back only the drag");
assert_eq!(objects(&s), 1, "real time {real_time}: nothing is drawn");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(visible(&s, other), "real time {real_time}");
}
}
/// Every object of the first layer but `other`, as the document has it.
fn others(s: &Session, other: NodeId) -> Vec<vectorcraft_doc::Node> {
let d = &s.doc().unwrap().doc;
d.layers[0].children().map_or_else(Vec::new, |c| c.iter().filter(|n| n.id != other).map(|n| (**n).clone()).collect())
}
/// A new 400 × 400 pt document with Real-time Drawing `real_time`, holding a 40 × 40 pt square at
/// (100, 100) and a 20 × 20 pt one at (10, 10) → the session, the larger square (selected) and the
/// smaller one.
fn two_squares(real_time: bool) -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
let target = s.doc().unwrap().selection.objects[0];
(s, target, other)
}
/// A press at the first point of `pts`, drags to the others and a release at the last, with
/// `mid` run after the first drag.
fn drag_with(s: &mut Session, pts: &[(f64, f64)], mid: impl FnOnce(&mut Session)) {
let (&(x0, y0), rest) = pts.split_first().expect("a press");
pointer(s, PointerKind::Down, x0, y0);
let mut mid = Some(mid);
for &(x, y) in rest {
pointer(s, PointerKind::Drag, x, y);
if let Some(f) = mid.take() {
f(s);
}
}
let &(x, y) = pts.last().expect("a release");
pointer(s, PointerKind::Up, x, y);
}
/// Is `id` filled red?
fn red(s: &Session, id: NodeId) -> bool {
s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill_paint().color()).is_some_and(|c| c.to_hex() == "#ff0000")
}
/// The Selection tool's move, the Scale and Rotate tools and the Pen, each with a command that
/// fills another object red during the drag: the release keeps both, as two undo steps, and Undo
/// takes back the drag first.
#[test]
fn the_move_scale_rotate_and_pen_drags_keep_a_command_run_during_them() {
let drags: [(&str, &[(f64, f64)]); 4] = [
("selection", &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)]),
("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]),
("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]),
("pen", &[(300.0, 300.0), (320.0, 300.0), (350.0, 320.0)]),
];
for (tool, pts) in drags {
for real_time in [true, false] {
let at = format!("{tool}, real time {real_time}");
let (mut s, _, other) = two_squares(real_time);
if tool == "pen" {
s.execute("select.none", &json!({})).unwrap();
}
s.select_tool(tool, view()).unwrap();
let (before, steps) = (others(&s, other), s.doc().unwrap().history.undo.len());
drag_with(&mut s, pts, |s| {
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#ff0000"})).unwrap();
});
assert!(!s.in_interaction(), "{at}");
assert!(red(&s, other), "{at}: the release keeps the command's edit");
assert_ne!(others(&s, other), before, "{at}: the release keeps the drag's edit");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(others(&s, other), before, "{at}: Undo takes back the drag");
assert!(red(&s, other), "{at}: and leaves the command's edit");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!red(&s, other), "{at}: the next Undo takes back the command's edit");
}
}
}
/// A command that changes the object being moved: the move applies to the changed object.
#[test]
fn a_move_drag_moves_the_object_as_a_command_during_it_changed_it() {
for real_time in [true, false] {
let (mut s, target, _) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let fill = |s: &Session| s.doc().unwrap().doc.node(target).unwrap().appearance.fill_paint().color().map(|c| c.to_hex());
let was = fill(&s);
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap();
});
let moved = s.doc().unwrap().doc.bounds_of(&[target], false);
assert_eq!(moved, Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}");
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "real time {real_time}: the fill is a step of its own");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fill(&s), was, "real time {real_time}");
}
}
/// A command that deletes the object being moved: the drag goes on and ends without an edit of
/// its own, on release and on Escape, and the deletion stays.
#[test]
fn a_move_drag_of_an_object_a_command_deleted_ends_without_an_edit() {
for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] {
let at = format!("real time {real_time}, Escape {escape}");
let (mut s, target, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap();
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}");
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
if escape {
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
}
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
assert!(!s.in_interaction(), "{at}");
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays");
assert_eq!(others(&s, other), [], "{at}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}");
}
}
/// A command that hides or locks the object being moved: the object stays where it was and
/// unselected, and the drag ends without an edit of its own.
#[test]
fn a_move_drag_of_an_object_a_command_hid_or_locked_leaves_it_alone() {
for command in ["object.hide", "object.lock"] {
for real_time in [true, false] {
let at = format!("{command}, real time {real_time}");
let (mut s, target, _) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute(command, &json!({"ids": [target.0]})).unwrap();
});
assert!(!s.in_interaction(), "{at}");
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: not moved");
assert!(!s.doc().unwrap().selection.objects.contains(&target), "{at}: not selected");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step");
}
}
}
/// The commands that end a drag first still do: Undo during a drag keeps the drag as a step and
/// takes it back, and `command.batch` and `swatch.renameGroup` keep it as a step before their own.
#[test]
fn undo_and_a_batch_during_a_drag_still_keep_the_drag_first() {
for real_time in [true, false] {
let (mut s, target, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.in_interaction(), "real time {real_time}");
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "real time {real_time}");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
let (mut s, target, other2) = two_squares(real_time);
assert_eq!(other, other2);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
s.execute("command.batch", &json!({"commands": [{"command": "object.hide", "params": {"ids": [other.0]}}]})).unwrap();
assert!(!s.in_interaction(), "real time {real_time}: the batch keeps the drag first");
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(visible(&s, other), "real time {real_time}: Undo takes back the batch first");
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
// A color group renamed during the drag keeps the drag as a step before the rename.
let (mut s, target, _) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
s.execute("swatch.renameGroup", &json!({"group": "Brights", "name": "Vivid"})).unwrap();
assert!(!s.in_interaction(), "real time {real_time}: the rename keeps the drag first");
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch_groups.iter().any(|g| g.name == "Brights"), "real time {real_time}: Undo takes back the rename");
assert_eq!(s.doc().unwrap().doc.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "real time {real_time}");
}
}
/// A copy made with `object.transform` during an Alt-drag runs inside the drag, with Real-time
/// Drawing on and off: the release records one step that holds both.
#[test]
fn a_copy_during_an_alt_drag_is_part_of_the_drag() {
for real_time in [true, false] {
let (mut s, target, _) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
let alt = Mods { alt: true, ..Mods::default() };
for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 170.0, 150.0)] {
s.pointer(&PointerEvent::new(kind, x, y).with_mods(alt), view()).unwrap();
}
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(alt), view()).unwrap();
assert!(!s.in_interaction(), "real time {real_time}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "real time {real_time}: one step for the drag and the copy");
// With Alt let go during the drag, the drag moves again, and the copy is a step of its own.
let (mut s, target, _) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 120.0).with_mods(alt), view()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 140.0).with_mods(alt), view()).unwrap();
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 60], "copy": true, "ids": [target.0]})).unwrap();
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "real time {real_time}: the copy and the move");
}
}
/// A command that changes only the current layer during a drag keeps its change through Escape.
#[test]
fn escape_keeps_a_current_layer_set_during_a_drag() {
for real_time in [true, false] {
let (mut s, _) = session(real_time);
let first = s.doc().unwrap().active_layer;
let second = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let first = first.expect("a current layer");
s.execute("layer.setCurrent", &json!({"id": first.0})).unwrap();
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
s.execute("layer.setCurrent", &json!({"id": second.0})).unwrap();
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
assert_eq!(s.doc().unwrap().active_layer, Some(second), "real time {real_time}");
}
}
/// With Real-time Drawing on, the drag's preview is on show again right after the command.
#[test]
fn the_drag_preview_shows_again_after_the_command() {
let (mut s, other) = session(true);
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
assert_eq!(objects(&s), 2, "the preview draws the rectangle");
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
assert_eq!(objects(&s), 2, "the preview is on show after the command");
s.execute("object.showAll", &json!({})).unwrap();
assert_eq!(objects(&s), 2, "and after a second one");
assert!(visible(&s, other));
assert!(s.in_interaction());
pointer(&mut s, PointerKind::Up, 150.0, 150.0);
assert_eq!(objects(&s), 2);
assert!(visible(&s, other));
}
/// A command that changes the selection during a move drag (Select All, Deselect, a duplicate)
/// leaves the drag moving the object it began with.
#[test]
fn a_selection_made_during_a_move_drag_leaves_the_drag_moving_its_object() {
for command in ["select.all", "select.none", "edit.duplicate"] {
for real_time in [true, false] {
let at = format!("{command}, real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute(command, &json!({})).unwrap();
});
let d = &s.doc().unwrap().doc;
assert_eq!(d.bounds_of(&[target], false), Some(Rect::new(150.0, 130.0, 190.0, 170.0)), "{at}: the drag moves its object");
assert_eq!(d.bounds_of(&[other], false), Some(Rect::new(10.0, 10.0, 30.0, 30.0)), "{at}: and nothing else");
if command == "edit.duplicate" {
let copies = others(&s, other).into_iter().filter(|n| n.id != target).map(|n| n.id).collect::<Vec<_>>();
assert_eq!(copies.len(), 1, "{at}");
assert_eq!(d.bounds_of(&copies, false), Some(Rect::new(100.0, 100.0, 140.0, 140.0)), "{at}: the copy stays where it was made");
}
}
}
}
/// A command that selects another object during a move drag: the drag's object stays selected,
/// and the fill and stroke proxies keep showing its paints.
#[test]
fn a_selection_made_during_a_move_drag_leaves_the_paints_of_the_drag_object() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.execute("paint.setFill", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#0000ff"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.select_tool("selection", view()).unwrap();
let fill = |s: &Session| s.paint.fill.color().map(|c| c.to_hex());
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}");
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}");
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the command");
pointer(&mut s, PointerKind::Drag, 170.0, 150.0);
pointer(&mut s, PointerKind::Up, 170.0, 150.0);
assert_eq!(s.doc().unwrap().selection.objects, [target], "{at}");
assert_eq!(fill(&s).as_deref(), Some("#ff0000"), "{at}: after the release");
}
}
/// Replay the journal of `s` from `start` on `replayed`.
fn replay_from(s: &Session, start: usize, replayed: &mut Session) {
for (id, p) in s.journal.iter().skip(start) {
replayed.replay(id, p).unwrap();
}
}
/// The journal of a move drag with a selection command run during it replays as the drag went:
/// the drag moves its own object, not the one the command selected.
#[test]
fn a_move_drag_after_a_selection_command_replays_on_its_own_object() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let bounds = |s: &Session| {
let d = &s.doc().unwrap().doc;
(d.bounds_of(&[target], false), d.bounds_of(&[other], false))
};
assert_eq!(bounds(&s), (Some(Rect::new(150.0, 130.0, 190.0, 170.0)), Some(Rect::new(10.0, 10.0, 30.0, 30.0))), "{at}");
let (mut replayed, _, _) = two_squares(real_time);
replay_from(&s, start, &mut replayed);
assert_eq!(bounds(&replayed), bounds(&s), "{at}: {:?}", journaled(&s, start));
assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}");
assert_eq!(replayed.doc().unwrap().active_layer, s.doc().unwrap().active_layer, "{at}");
}
}
/// Find Objects with `select` during a drag is a step of its own, as it is journaled: it finds and
/// selects only the objects outside the drag's preview, as its replay before the drag does.
#[test]
fn find_objects_with_select_during_a_drag_skips_the_drag_preview() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, other) = session(real_time);
let start = s.journal.len();
let find = json!({"intersects": [0, 0, 400, 400], "select": true});
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 150.0);
let r = s.execute("document.find", &find).unwrap();
assert_eq!(r["total"], 1, "{at}: {r}");
assert_eq!(r["matches"][0]["id"], other.0, "{at}: {r}");
pointer(&mut s, PointerKind::Up, 200.0, 180.0);
assert_eq!(objects(&s), 2, "{at}: the release draws the rectangle");
// The drag's own selection is journaled after the find, so the release replays on it.
assert_eq!(journaled(&s, start), ["document.find", "select.set", "shape.rectangle"], "{at}");
let (mut replayed, _) = session(real_time);
replay_from(&s, start, &mut replayed);
assert_eq!(objects(&replayed), 2, "{at}");
assert_eq!(replayed.doc().unwrap().selection.objects, s.doc().unwrap().selection.objects, "{at}");
}
}
/// A square on a second layer selected with a ruler guide, and a square on the first layer →
/// the session (with Real-time Drawing `real_time`) and the square on the first layer.
fn square_and_guide(real_time: bool) -> (Session, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
s.execute("layer.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
let target = s.doc().unwrap().selection.objects[0];
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
(s, other)
}
/// The journal of a move drag of a square and a ruler guide, with a command during it that
/// selects an object on another layer, replays with the drag's selection, guide included, with
/// the layer the command made current and with the Layers panel rows the command left highlighted.
#[test]
fn a_move_drag_of_a_guide_after_a_selection_command_replays_its_selection_and_layer() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, other) = square_and_guide(real_time);
s.select_tool("selection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let (mut replayed, _) = square_and_guide(real_time);
replay_from(&s, start, &mut replayed);
let state = |s: &mut Session| {
let d = s.doc().unwrap();
let state = (
d.selection.objects.clone(),
d.selection.guides.clone(),
d.active_layer,
d.highlighted_rows(),
d.doc.bounds_of(&d.selection.objects, false),
);
(state, s.execute("guide.list", &json!({})).unwrap())
};
assert_eq!(state(&mut replayed), state(&mut s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted square, with a command during it that selects another
/// square, replays with the square targeted, as the drag leaves it.
#[test]
fn a_move_drag_of_a_targeted_object_after_a_selection_command_replays_its_target() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("layer.target", &json!({"id": target.0})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, other)
};
let (mut s, other) = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let (mut replayed, _) = setup();
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.selection.target, d.doc.bounds_of(&d.selection.objects, false))
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted square and a ruler guide, with a command during it
/// that selects another square, replays with the square targeted and the guide selected.
#[test]
fn a_move_drag_of_a_targeted_object_and_a_guide_after_a_selection_command_replays_both() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
s.execute("layer.target", &json!({"id": target.0})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, target, other)
};
let (mut s, target, other) = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let state = |s: &mut Session| {
let d = s.doc().unwrap();
let state = (d.selection.objects.clone(), d.selection.target, d.selection.guides.clone(), d.doc.bounds_of(&d.selection.objects, false));
(state, s.execute("guide.list", &json!({})).unwrap())
};
let live = state(&mut s);
assert_eq!((live.0.1, live.0.2.len()), (Some(target), 1), "{at}: the drag leaves the square targeted and the guide selected");
let (mut replayed, _, _) = setup();
replay_from(&s, start, &mut replayed);
assert_eq!(state(&mut replayed), live, "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a path with every anchor selected as anchor points, with a
/// command during it that selects another square, replays with those anchors selected.
#[test]
fn a_move_drag_of_every_anchor_of_a_path_after_a_selection_command_replays_its_anchors() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, target, other) = two_squares(real_time);
s.execute("select.set", &json!({"ids": [target.0]})).unwrap();
s.execute("select.anchors", &json!({"id": target.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
s.select_tool("selection", view()).unwrap();
(s, target, other)
};
let (mut s, target, other) = setup();
let every = s.doc().unwrap().selection.anchors.get(&target).cloned();
assert!(every.as_ref().is_some_and(|a| a.len() > 1), "{at}: {every:?}");
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.selection.anchors.clone(), d.doc.bounds_of(&d.selection.objects, false))
};
assert_eq!(state(&s).1.get(&target), every.as_ref(), "{at}: the drag leaves every anchor selected as anchors");
let (mut replayed, _, _) = setup();
replay_from(&s, start, &mut replayed);
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// The journal of a move drag of a targeted layer's art, with a duplicate made on that layer
/// during it, replays with the drag moving its own objects, not the duplicates.
#[test]
fn a_move_drag_of_a_targeted_layer_after_a_duplicate_replays_its_objects() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let setup = || {
let (mut s, _, _) = two_squares(real_time);
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
s.select_tool("selection", view()).unwrap();
s
};
let mut s = setup();
let start = s.journal.len();
drag_with(&mut s, &[(120.0, 120.0), (140.0, 130.0), (170.0, 150.0)], |s| {
s.execute("edit.duplicate", &json!({})).unwrap();
});
let mut replayed = setup();
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let d = s.doc().unwrap();
(d.selection.objects.clone(), d.doc.bounds_of(&d.selection.objects, false), objects(s))
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// A selected user slice and a square → the session (with Real-time Drawing `real_time`), the
/// slice and the square.
fn slice_and_square(real_time: bool) -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.prefs.real_time_drawing = real_time;
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let other = s.doc().unwrap().selection.objects[0];
let slice = s.execute("object.slice.create", &json!({"x": 200, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("object.slice.select", &json!({"slices": [slice]})).unwrap();
(s, NodeId(slice), other)
}
/// The journal of a Slice Selection drag, with a command during it that selects an object,
/// replays with the slice selected, as the drag leaves it.
#[test]
fn a_slice_drag_after_a_selection_command_replays_its_slice_selection() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, slice, other) = slice_and_square(real_time);
s.select_tool("sliceSelection", view()).unwrap();
let start = s.journal.len();
drag_with(&mut s, &[(220.0, 220.0), (230.0, 230.0), (240.0, 240.0)], |s| {
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
});
assert_eq!(s.doc().unwrap().selection.slices, [slice], "{at}");
let (mut replayed, _, _) = slice_and_square(real_time);
replay_from(&s, start, &mut replayed);
let state = |s: &Session| {
let sel = &s.doc().unwrap().selection;
(sel.objects.clone(), sel.slices.clone())
};
assert_eq!(state(&replayed), state(&s), "{at}: {:?}", journaled(&s, start));
}
}
/// A Warp stroke over two selected squares, with a command that deletes one of them during the
/// stroke: the release still warps the other square, and the stroke's journal entry names it.
#[test]
fn a_warp_stroke_over_an_object_a_command_deleted_still_warps_the_others() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, other) = two_squares(real_time);
s.execute("select.all", &json!({})).unwrap();
s.select_tool("warp", view()).unwrap();
let before = s.doc().unwrap().doc.node(target).cloned();
let steps = s.doc().unwrap().history.undo.len();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 135.0, 125.0);
let r = s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap();
assert!(r.get("warning").is_none(), "{at}: {r}");
pointer(&mut s, PointerKind::Up, 135.0, 125.0);
assert!(!s.in_interaction(), "{at}");
assert!(s.doc().unwrap().doc.node(other).is_none(), "{at}: the deletion stays");
assert_ne!(s.doc().unwrap().doc.node(target).cloned(), before, "{at}: the release warps the other square");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the deletion and the stroke are a step each");
let (id, p) = s.journal.last().unwrap();
assert_eq!((id.as_str(), &p["ids"]), ("object.liquify", &json!([target.0])), "{at}");
}
}
/// The Scale and Rotate tools and the Pen adding to a path, with a command that deletes the
/// object they act on during the drag: the drag ends without an edit of its own and the deletion
/// stays.
#[test]
fn a_scale_rotate_or_pen_drag_of_an_object_a_command_deleted_ends_without_an_edit() {
let drags: [(&str, &[(f64, f64)]); 3] = [
("scale", &[(150.0, 150.0), (170.0, 170.0), (190.0, 190.0)]),
("rotate", &[(160.0, 120.0), (150.0, 150.0), (120.0, 160.0)]),
("pen", &[(350.0, 350.0), (370.0, 360.0), (380.0, 380.0)]),
];
for (tool, pts) in drags {
for real_time in [true, false] {
let at = format!("{tool}, real time {real_time}");
let (mut s, target, _) = two_squares(real_time);
s.select_tool(tool, view()).unwrap();
let target = if tool == "pen" {
s.execute("select.none", &json!({})).unwrap();
for (x, y) in [(300.0, 300.0), (350.0, 300.0)] {
pointer(&mut s, PointerKind::Down, x, y);
pointer(&mut s, PointerKind::Up, x, y);
}
s.doc().unwrap().selection.objects[0]
} else {
target
};
let before = s.doc().unwrap().doc.clone();
let steps = s.doc().unwrap().history.undo.len();
drag_with(&mut s, pts, |s| {
s.execute("edit.clear", &json!({"ids": [target.0]})).unwrap();
});
assert!(!s.in_interaction(), "{at}");
assert!(s.doc().unwrap().doc.node(target).is_none(), "{at}: the deletion stays");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the deletion is a step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *before, "{at}: Undo brings the object back as it was");
}
}
}
/// A Direct Selection drag of an anchor, with a command during it that numbers the path's anchors
/// anew (Add Anchor Point before the dragged one, Reverse Path Direction): the command's edit
/// stays, the drag ends without an edit of its own and moves no other anchor of the path.
#[test]
fn an_anchor_drag_after_a_command_renumbers_its_anchors_moves_no_other_anchor() {
let commands = [("path.insertAnchor", json!({"segment": 0, "t": 0.5}), 1), ("path.reverse", json!({}), 0)];
for ((id, params, added), real_time) in commands.iter().flat_map(|c| [(c, true), (c, false)]) {
let at = format!("{id}, real time {real_time}");
let (mut s, target, _) = two_squares(real_time);
s.execute("select.none", &json!({})).unwrap();
s.select_tool("directSelection", view()).unwrap();
let points = |s: &Session| -> Vec<(f64, f64)> {
let doc = &s.doc().unwrap().doc;
let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path");
path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
};
let before = points(&s);
let &(x, y) = before.last().expect("the square has anchors");
let steps = s.doc().unwrap().history.undo.len();
let mut params = params.clone();
params["id"] = json!(target.0);
drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| {
s.execute(id, &params).unwrap();
});
assert!(!s.in_interaction(), "{at}");
let after = points(&s);
assert_eq!(after.len(), before.len() + added, "{at}: the command's edit stays");
assert!(before.iter().all(|p| after.contains(p)), "{at}: no anchor of the square moved: {before:?} → {after:?}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{at}: only the command is a step");
}
}
/// A Direct Selection drag of an anchor, with a command during it that moves the path: the drag
/// goes on and moves the same anchor of the moved path.
#[test]
fn an_anchor_drag_after_a_command_moves_its_path_moves_the_same_anchor() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, target, _) = two_squares(real_time);
s.execute("select.none", &json!({})).unwrap();
s.select_tool("directSelection", view()).unwrap();
let points = |s: &Session| -> Vec<(f64, f64)> {
let doc = &s.doc().unwrap().doc;
let path = doc.node(target).and_then(|n| n.path_data()).expect("the square is a path");
path.anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
};
let before = points(&s);
let &(x, y) = before.last().expect("the square has anchors");
let steps = s.doc().unwrap().history.undo.len();
drag_with(&mut s, &[(x, y), (x + 10.0, y + 10.0), (x + 30.0, y + 20.0)], |s| {
s.execute("object.move", &json!({"ids": [target.0], "dx": 0, "dy": 50})).unwrap();
});
let after = points(&s);
let last = before.len() - 1;
let moved: Vec<(f64, f64)> =
before.iter().enumerate().map(|(i, &(px, py))| if i == last { (px + 30.0, py + 70.0) } else { (px, py + 50.0) }).collect();
assert_eq!(after, moved, "{at}: the drag moves the same anchor of the moved square");
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{at}: the move and the drag are a step each");
}
}
/// With the Live Paint Bucket's Selection tool (Cmd+drag), a fill chosen during the drag stays the
/// new-art fill after the release and after Escape, though the drag puts back the bucket's colors
/// it began with.
#[test]
fn a_fill_chosen_during_a_bucket_drag_stays() {
for (real_time, escape) in [(true, false), (false, false), (true, true), (false, true)] {
let at = format!("real time {real_time}, Escape {escape}");
let (mut s, _, _) = two_squares(real_time);
s.select_tool("livePaintBucket", view()).unwrap();
let cmd = Mods { cmd: true, ..Mods::default() };
for (kind, x, y) in [(PointerKind::Down, 120.0, 120.0), (PointerKind::Drag, 140.0, 130.0)] {
s.pointer(&PointerEvent::new(kind, x, y).with_mods(cmd), view()).unwrap();
}
assert!(s.in_interaction(), "{at}: the lent Selection tool drags the square");
s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": []})).unwrap();
let green = s.paint.fill.clone();
s.pointer(&PointerEvent::new(PointerKind::Drag, 170.0, 150.0).with_mods(cmd), view()).unwrap();
if escape {
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 150.0).with_mods(cmd), view()).unwrap();
assert_eq!(s.paint.fill, green, "{at}");
}
}
/// A command run during a Quick Pen press still runs inside the press, so it records no undo
/// step of its own while the press is held.
#[test]
fn a_command_during_a_quick_pen_press_runs_inside_it() {
for real_time in [true, false] {
let at = format!("real time {real_time}");
let (mut s, other) = session(real_time);
s.select_tool(vectorcraft_tools::quickpen::ID, view()).unwrap();
pointer(&mut s, PointerKind::Down, 50.0, 50.0);
pointer(&mut s, PointerKind::Up, 50.0, 50.0);
pointer(&mut s, PointerKind::Down, 100.0, 100.0);
pointer(&mut s, PointerKind::Drag, 150.0, 120.0);
assert!(s.in_interaction(), "{at}: the press drags a piece");
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.hide", &json!({"ids": [other.0]})).unwrap();
assert!(s.in_interaction(), "{at}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press");
}
}
+4 -3
View File
@@ -73,13 +73,14 @@ fn arrowheads_are_part_of_the_outline() {
assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape");
}
/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle.
/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle.
#[test]
fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() {
fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() {
let mut s = session();
line(&mut s, json!({"weight": 10, "profile": "lens"}));
let n = outline(&mut s);
assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
// Each half of the lens swells on a cubic, flat at the middle (#5714).
assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n));
}
#[test]
+160
View File
@@ -0,0 +1,160 @@
//! The arrow keys with a curved segment selected bend it: its anchors stay, its handles keep their
//! directions, and the middle of the curve moves toward the arrow.
use std::sync::Arc;
use serde_json::json;
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Anchor, ParamCurve, PathData, Point, SubPath, Vec2};
use crate::*;
/// A session with one open path of one segment from (100, 300) to (400, 300), with the handles
/// `out` at its start and `in` at its end, and that segment selected with Direct Selection.
fn selected_segment(out: Point, h_in: Point) -> (Session, NodeId) {
let (p0, p1) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0));
let (s, id) = session_with(vec![Anchor::with_handles(p0, p0, out), Anchor::with_handles(p1, h_in, p1)]);
(select(s, id, &[0]), id)
}
/// A session with one open path through `anchors`.
fn session_with(anchors: Vec<Anchor>) -> (Session, NodeId) {
let mut d = Document::new(1000.0, 1000.0);
let id = d.alloc_id();
let node = Node::path(id, PathData::single(SubPath::new(anchors, false)), Appearance::default_art());
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
ch.push(Arc::new(node));
}
let mut s = Session::new();
s.add_document(d, None);
(s, id)
}
/// `s` with segments `segments` of path `id` selected with Direct Selection.
fn select(mut s: Session, id: NodeId, segments: &[usize]) -> Session {
let refs: Vec<_> = segments.iter().map(|&seg| [0, seg]).collect();
s.execute("select.segments", &json!({"id": id.0, "segments": refs})).unwrap();
s
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn segment(s: &Session, id: NodeId) -> SubPath {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone()
}
/// Each handle as a vector from its anchor: the outgoing one at the start, the incoming one at
/// the end.
fn handles(sp: &SubPath) -> (Vec2, Vec2) {
(sp.anchors[0].h_out - sp.anchors[0].p, sp.anchors[1].h_in - sp.anchors[1].p)
}
fn middle(sp: &SubPath) -> Point {
sp.segment(0).eval(0.5)
}
#[test]
fn arrows_bend_a_selected_curved_segment_and_keep_its_anchors() {
// The handle at the start points up, the one at the end left.
let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(300.0, 300.0));
let step = s.prefs.keyboard_increment;
let before = segment(&s, id);
let (up, left) = handles(&before);
// Up: the upward handle grows, the one across the arrow stays.
s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap();
let after = segment(&s, id);
let (up2, left2) = handles(&after);
assert_eq!((after.anchors[0].p, after.anchors[1].p), (before.anchors[0].p, before.anchors[1].p), "the anchors stay");
assert!(up2.hypot() > up.hypot() && up2.cross(up).abs() < 1e-9 && up2.dot(up) > 0.0, "the upward handle grows in its direction: {up2:?}");
assert_eq!(left2, left, "the handle across the arrow stays");
assert!((middle(&after) - middle(&before) - Vec2::new(0.0, -step)).hypot() < 1e-9, "the middle moves one step up");
// Right: the handle pointing left shrinks, the upward one stays.
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
let last = segment(&s, id);
let (up3, left3) = handles(&last);
assert_eq!(up3, up2, "the handle across the arrow stays");
assert!(left3.hypot() < left2.hypot() && left3.cross(left2).abs() < 1e-9 && left3.dot(left2) > 0.0, "the leftward handle shrinks: {left3:?}");
assert!((middle(&last) - middle(&after) - Vec2::new(step, 0.0)).hypot() < 1e-9, "the middle moves one step right");
}
#[test]
fn arrows_move_a_selected_straight_segment_whole() {
let (mut s, id) = selected_segment(Point::new(100.0, 300.0), Point::new(400.0, 300.0));
let step = s.prefs.keyboard_increment;
let before = segment(&s, id);
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
let after = segment(&s, id);
for (a, b) in before.anchors.iter().zip(&after.anchors) {
assert_eq!(b.p - a.p, Vec2::new(0.0, step));
}
}
#[test]
fn a_selected_straight_segment_beside_a_curved_one_moves_whole() {
let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(600.0, 300.0));
let (s, id) = session_with(vec![
Anchor::with_handles(p0, p0, Point::new(100.0, 150.0)),
Anchor::with_handles(p1, Point::new(300.0, 300.0), p1),
Anchor::corner(p2),
]);
let mut s = select(s, id, &[0, 1]);
let step = s.prefs.keyboard_increment;
let before = segment(&s, id);
s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap();
let after = segment(&s, id);
assert_eq!(after.anchors[0].p, before.anchors[0].p, "the curved segment's other anchor stays");
for i in [1, 2] {
assert_eq!(after.anchors[i].p - before.anchors[i].p, Vec2::new(0.0, -step), "the straight segment's anchor {i} moves");
}
}
#[test]
fn a_segment_whose_handles_lie_across_the_arrow_records_no_undo_step() {
// Both handles point up: ← and → bend nothing.
let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(400.0, 150.0));
let (before, steps) = (segment(&s, id), undo_steps(&s));
s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap();
assert_eq!(segment(&s, id), before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn a_handle_bent_through_a_smooth_anchor_leaves_the_next_segment_as_it_is() {
// A smooth anchor between the selected segment, whose handle there is short and points up,
// and the next one.
let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(700.0, 300.0));
let smooth = Anchor::with_handles(p0, Point::new(100.0, 310.0), Point::new(100.0, 299.5));
let (s, id) = session_with(vec![
Anchor::corner(Point::new(-200.0, 300.0)),
smooth,
Anchor::with_handles(p1, Point::new(300.0, 300.0), p1),
Anchor::corner(p2),
]);
assert_eq!(smooth.kind, vectorcraft_geom::AnchorKind::Smooth);
let mut s = select(s, id, &[1]);
let h_in = segment(&s, id).anchors[1].h_in;
// ↓ shrinks the upward handle through its anchor.
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
let after = segment(&s, id).anchors[1];
assert!(after.h_out.y > p0.y, "the handle comes out pointing down: {:?}", after.h_out);
assert_eq!(after.h_in, h_in, "the next segment's handle stays");
}
#[test]
fn a_retracted_handle_the_arrow_leaves_keeps_its_smooth_anchor_smooth() {
// A smooth anchor whose outgoing handle is retracted, so it points toward the other handle's
// end, level with it and across ↓; only the other handle, pointing up, changes.
let (p0, p1) = (Point::new(100.0, 300.0), Point::new(200.0, 400.0));
let smooth = Anchor { p: p0, h_in: Point::new(0.0, 300.0), h_out: p0, kind: vectorcraft_geom::AnchorKind::Smooth };
let (s, id) = session_with(vec![Anchor::corner(Point::new(-200.0, 300.0)), smooth, Anchor::with_handles(p1, Point::new(200.0, 300.0), p1)]);
let mut s = select(s, id, &[1]);
let before = segment(&s, id);
s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap();
let after = segment(&s, id);
assert_ne!(after.anchors[2].h_in, before.anchors[2].h_in, "the upward handle changes");
assert_eq!(after.anchors[1], before.anchors[1], "the smooth anchor stays as it was");
}
+15 -1
View File
@@ -618,6 +618,7 @@ impl Session {
path_only: self.prefs.object_selection_by_path_only,
type_path_only: self.prefs.type_selection_by_path_only,
double_click_isolate: self.prefs.double_click_to_isolate,
double_click_adds_anchor: self.prefs.double_click_adds_anchor_points,
select_behind: self.prefs.ctrl_click_selects_behind,
highlight_anchors: self.prefs.highlight_anchors_on_hover,
snap_tolerance: self.prefs.snap_to_point_tolerance,
@@ -1727,6 +1728,10 @@ impl Session {
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
// The tool acts on its own interaction, which a command from outside it may have set aside.
if !acts.is_empty() {
self.put_back_interaction();
}
let outer = std::mem::replace(&mut self.in_tool_actions, true);
let outer_bucket = self.back_to_bucket;
// The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket.
@@ -1752,7 +1757,16 @@ impl Session {
let mut ui = vec![];
for a in acts {
match a {
Action::Begin(label) => self.begin_interaction(&label)?,
Action::Begin(label) => {
// The snapshot of the interaction open before, which the tool's drag then joins.
let open = self.active().and_then(|st| st.interaction.as_ref()).map(|it| std::sync::Arc::as_ptr(&it.doc));
self.begin_interaction(&label)?;
if let Some(it) = self.active_mut().and_then(|st| st.interaction.as_mut())
&& open != Some(std::sync::Arc::as_ptr(&it.doc))
{
it.tool = true;
}
}
Action::Preview(cmd, p) => {
// Performance › Real-time Drawing and Editing (#394): off, remember the latest
// params and apply them once on Commit instead of every move. A ruler guide
+22
View File
@@ -225,6 +225,28 @@ fn dimension_angles_circles_arcs_and_curves() {
assert_eq!(text(&s, id), "100 pt");
}
#[test]
fn an_angular_dimension_can_take_its_vertex_from_an_anchor() {
let mut s = session();
let line = edge(&mut s);
let request = json!({
"mode": "angular", "a": [172, 100], "b": [100, 172], "options": {"precision": 1},
"source": {"kind": "points", "vertex": {"node": line, "subpath": 0, "anchor": 0}}
});
let id = run(&mut s, "dimension.create", request.clone())["id"].as_u64().unwrap();
assert_eq!(text(&s, id), "90.0°");
run(&mut s, "select.set", json!({"ids": [line]}));
run(&mut s, "object.move", json!({"dx": 18, "dy": 0}));
assert!(near(recipe(&s, id).vertex, vectorcraft_geom::Point::new(118.0, 100.0)));
let mut invalid = request.clone();
invalid["vertex"] = json!("bad point");
assert!(s.execute("dimension.create", &invalid).is_err());
let mut missing = request;
missing["source"]["vertex"] = Value::Null;
assert!(s.execute("dimension.create", &missing).is_err());
}
#[test]
fn dimension_rejects_bad_input_without_mutation() {
let mut s = session();
+33 -14
View File
@@ -39,6 +39,7 @@ mod ai;
mod ate;
mod cid;
mod data;
mod file_fonts;
mod graphics;
mod interp;
mod lex;
@@ -113,6 +114,10 @@ const MAX_SIDE: f64 = 1e5;
/// The start of the warning that type was set in fonts that aren't available, before ": " and
/// their families: PDF import's words, as type in those fonts comes in the same way.
pub(crate) const MISSING_FONTS_NOTE: &str = "fonts that aren't available show in the fallback font until they are";
/// The start of the warning that type in fonts that aren't available is drawn in the fonts the
/// file carries (see `file_fonts`), before ": " and their families: PDF import's words.
pub(crate) const CARRIED_FONTS_NOTE: &str =
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font)";
/// Most families named in that warning.
const MAX_MISSING_FONTS: usize = 64;
@@ -304,30 +309,41 @@ pub fn import_ai(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncod
/// [`import_names`] (a `.ai` when `ai_file`, see [`import_ai`]).
fn read_checked(bytes: &[u8], editing_data: bool, trust: bool, names: NameEncoding, ai_file: bool) -> Result<Imported, String> {
let mut r = read_names(bytes, editing_data, trust, names, ai_file)?;
let missing = missing_fonts(&r.document);
if !missing.is_empty() {
r.warnings.push(format!("{MISSING_FONTS_NOTE}: {}", missing.join(", ")));
r.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut r.document));
let (carried, missing) = missing_fonts(&r.document);
for (note, families) in [(CARRIED_FONTS_NOTE, carried), (MISSING_FONTS_NOTE, missing)] {
if !families.is_empty() {
r.warnings.push(format!("{note}: {}", families.join(", ")));
}
}
Ok(r)
}
/// The families of the type in `d` (its layers and its symbols) that aren't available, each once
/// in the order the type comes, at most [`MAX_MISSING_FONTS`]: the document's, whether its type
/// came from the page or from an editing copy, and none for type only measured or outlined.
fn missing_fonts(d: &Document) -> Vec<String> {
/// in the order the type comes, at most [`MAX_MISSING_FONTS`] a list: the document's, whether its
/// type came from the page or from an editing copy, and none for type only measured or outlined.
/// The first list holds those of type drawn in fonts the file carries (bound to that type), the
/// second those of type in the fallback font; a family both happen to is in both.
fn missing_fonts(d: &Document) -> (Vec<String>, Vec<String>) {
let db = vectorcraft_text::FontDb::global();
let mut checked: HashSet<String> = HashSet::new();
let mut missing: Vec<String> = Vec::new();
let (mut carried, mut missing): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
let mut add = |n: &Node| {
let NodeKind::Text(t) = &n.kind else { return };
// The families and styles this type is drawn in from fonts the file carries.
let bound: Vec<(&str, &str)> = t
.file_fonts_in_use()
.iter()
.filter(|font| t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some())
.map(|font| (font.family.as_str(), font.style.as_str()))
.collect();
for run in &t.runs {
let family = run.style.font_family.as_str();
if missing.len() >= MAX_MISSING_FONTS || family.is_empty() || checked.contains(family) {
let (family, style) = (run.style.font_family.as_str(), run.style.font_style.as_str());
if family.is_empty() {
continue;
}
checked.insert(family.to_string());
if db.find_family(family).is_none() {
missing.push(family.to_string());
let list = if bound.contains(&(family, style)) { &mut carried } else { &mut missing };
if list.len() < MAX_MISSING_FONTS && !list.iter().any(|f| f == family) && db.find_family(family).is_none() {
list.push(family.to_string());
}
}
};
@@ -335,7 +351,7 @@ fn missing_fonts(d: &Document) -> Vec<String> {
for s in &d.symbols {
s.art.walk(&mut add);
}
missing
(carried, missing)
}
/// [`import_names`] before the type's fonts are checked (a `.ai` when `ai_file`, see [`import_ai`]).
@@ -406,6 +422,9 @@ fn finish(mut out: Out) -> Imported {
if !out.shadings.is_empty() {
graphics::collapse(&mut children, &out.shadings);
}
// The fonts made of the glyphs of fonts the file carries, for their type.
let kept = std::mem::take(&mut out.file_glyphs).keep(&mut out.doc.images);
file_fonts::keep_file_fonts(&mut children, &kept, &out.doc.images);
let mut layer = Node::layer(out.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
if let Some(c) = layer.children_mut() {
*c = children;
+85 -7
View File
@@ -76,14 +76,28 @@ fn flate(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
/// LZW data (`EarlyChange` 1) decoded, and how many bytes of `raw` it took.
fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
let mut out = vec![];
let used = lzw_into(raw, &mut |bytes| {
out.extend_from_slice(bytes);
if out.len() > MAX_DATA {
return Err(PsError::Limit("decoded data is too large"));
}
Ok(())
})?;
Ok((out, used))
}
/// LZW data (`EarlyChange` 1) decoded into `sink` as it goes, and how many bytes of `raw` it
/// took.
fn lzw_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res<usize> {
let mut table: Vec<Vec<u8>> = (0..=255u8).map(|b| vec![b]).collect();
table.push(vec![]);
table.push(vec![]);
let (mut out, mut prev): (Vec<u8>, Option<Vec<u8>>) = (vec![], None);
let mut prev: Option<Vec<u8>> = None;
let (mut acc, mut bits, mut width, mut i) = (0u32, 0u32, 9u32, 0usize);
loop {
while bits < width {
let Some(&b) = raw.get(i) else { return Ok((out, i)) };
let Some(&b) = raw.get(i) else { return Ok(i) };
i += 1;
acc = (acc << 8) | u32::from(b);
bits += 8;
@@ -96,7 +110,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
width = 9;
prev = None;
}
257 => return Ok((out, i)),
257 => return Ok(i),
_ => {
let entry = match (table.get(code), &prev) {
(Some(e), _) if !e.is_empty() => e.clone(),
@@ -107,7 +121,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
}
_ => return io("LZWDecode"),
};
out.extend_from_slice(&entry);
sink(&entry)?;
if let Some(mut p) = prev.take()
&& table.len() < 4096
{
@@ -121,14 +135,78 @@ fn lzw(raw: &[u8]) -> Res<(Vec<u8>, usize)> {
_ => 9,
};
prev = Some(entry);
if out.len() > MAX_DATA {
return Err(PsError::Limit("decoded data is too large"));
}
}
}
}
}
/// zlib data inflated into `sink` as it goes (64 KiB at a time), and how many bytes of `raw` it
/// took.
fn flate_into(raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Res<usize> {
let mut z = flate2::Decompress::new(true);
let mut scratch = vec![0u8; 64 * 1024];
loop {
let before = (z.total_in(), z.total_out());
let input = raw.get(usize::try_from(z.total_in()).unwrap_or(usize::MAX)..).unwrap_or_default();
let status = z.decompress(input, &mut scratch, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?;
let made = usize::try_from(z.total_out() - before.1).unwrap_or(0);
sink(scratch.get(..made).unwrap_or_default())?;
match status {
flate2::Status::StreamEnd => break,
_ if (z.total_in(), z.total_out()) == before => break,
_ => {}
}
}
Ok(usize::try_from(z.total_in()).unwrap_or(raw.len()))
}
/// Data compressed with filter `f` (`FlateDecode` or `LZWDecode` without a predictor) decoded
/// into `sink` as it goes, and how many bytes of `raw` it took; `None` for other filters.
pub(super) fn decode_into(f: &Filter, raw: &[u8], sink: &mut dyn FnMut(&[u8]) -> Res) -> Option<Res<usize>> {
match &*f.name {
_ if f.predictor.is_some() => None,
"FlateDecode" => Some(flate_into(raw, sink)),
"LZWDecode" => Some(lzw_into(raw, sink)),
_ => None,
}
}
/// How many bytes of `raw` filter `f` would read, found without keeping what it decodes, for
/// data whose decoded form is too large to hold: compressed data (`FlateDecode`, `LZWDecode`,
/// `RunLengthDecode`) is decoded and dropped as it goes, a JPEG ends at its end-of-image
/// marker, as [`dct`] reads it. `None` for other filters, data that can't be decoded, or data
/// that decodes to more than `most` bytes (what the caller's operation budget still pays for).
/// With it, how many bytes were decoded on the way, for the caller to charge: measuring costs
/// the work of decoding, so a program that measures the same data in a loop has to end.
pub(super) fn encoded_len(f: &Filter, raw: &[u8], most: usize) -> (Option<usize>, usize) {
let mut decoded = 0usize;
let mut count = |bytes: &[u8]| -> Res {
decoded = decoded.saturating_add(bytes.len());
if decoded > most {
return Err(PsError::Limit("the program runs too long"));
}
Ok(())
};
let used = match &*f.name {
"FlateDecode" => flate_into(raw, &mut count).ok(),
"LZWDecode" => lzw_into(raw, &mut count).ok(),
"RunLengthDecode" => {
let mut i = 0usize;
while let Some(&n) = raw.get(i) {
i += match n {
128 => return (Some(i + 1), 0),
0..=127 => 2 + usize::from(n),
_ => 2,
};
}
Some(raw.len())
}
"DCTDecode" => Some(find(raw, &[0xFF, 0xD9]).map_or(raw.len(), |e| e + 2)),
_ => None,
};
(used, decoded)
}
/// Most pixels a DCTDecode JPEG may have: twice the most an image is read with, so every image that
/// was read before is still read.
const MAX_DCT_PIXELS: u64 = 1 << 27;
+278 -48
View File
@@ -1,4 +1,4 @@
use super::filters::{Filter, Predictor, Stream, decode, fax_settings, io};
use super::filters::{Filter, Predictor, Stream, decode, decode_into, encoded_len, fax_settings, io};
use super::pixels::{Pixels, Spec, by_rows, by_samples, masked, source};
use super::{
Affine, Color, DictRef, HashMap, ImageBlob, ImageObject, Inks, Interp, Key, Lexer, Node, NodeId, NodeKind, Obj, Op, OpacityMask, Paint, PsError,
@@ -18,6 +18,8 @@ const MAX_PIXELS: usize = 1 << 26;
/// Why an image is missing.
const TOO_LARGE: &str = "images too large to read were left out";
/// Why an image is at a lower resolution than the file's.
const REDUCED: &str = "images of more than 67 million pixels were read at a lower resolution";
/// Most distinct colours an image converts through a tint transform.
const MAX_TINTS: usize = 1 << 16;
@@ -479,25 +481,184 @@ impl Interp<'_> {
/// their own end without decompressing (`ASCIIHexDecode`, `ASCII85Decode`, `SubFileDecode`)
/// read the file up to it, the way the image reading all its data would leave it; the
/// filters over them, which would only decode what those pass, aren't run. When the first
/// filter decompresses, it is run alone, and a failure (data too large to hold) leaves the
/// data where it was, as before.
fn skip_data(&mut self, src: &Source) {
/// filter decompresses, it is run alone; when it can't hold what it decompresses, it measures
/// its data instead. Unfiltered data is read past by its `n` bytes. A failure that read
/// nothing leaves the data where it was; one after a filter read its data leaves the file
/// past it, with nothing more to read.
fn skip_data(&mut self, src: &Source, n: usize) {
// A procedure (`{ currentfile buf readhexstring pop }`) reads the data itself: it is
// called, and what it gives dropped, until it has given the image's `n` bytes or ends.
if let Source::Proc(p) = src {
let mut given = 0usize;
while given < n {
let Ok(len) = self.call(p.clone()).and_then(|()| self.pop_str()).map(|s| s.len()) else { return };
if len == 0 {
return;
}
given = given.saturating_add(len);
}
return;
}
let Source::File(f) = src else { return };
let (chain, from) = match &*f.borrow() {
let (chain, from) = match &mut *f.borrow_mut() {
Stream::Pending { chain, from } => (chain.clone(), from.clone()),
_ => return,
// The data unfiltered: its `n` bytes are read past, as reading them would.
Stream::Current => {
let k = n.min(self.lex.data().len());
self.lex.advance(k);
return;
}
Stream::Buf { data, pos, .. } => {
*pos = pos.saturating_add(n).min(data.len());
return;
}
};
let delimited = chain.iter().take_while(|c| matches!(&*c.name, "ASCIIHexDecode" | "ASCII85Decode" | "SubFileDecode")).count();
let head = chain.get(..delimited.max(1)).unwrap_or_default().to_vec();
*f.borrow_mut() = Stream::Pending { chain: head, from: from.clone() };
// A failure leaves the file as it was; the import goes on without the image either way.
// How much of the file the filters are over is left.
let left = |me: &mut Self| match &from {
None => Some(me.lex.data().len()),
Some(r) => match &*r.borrow() {
Stream::Buf { data, pos, .. } => Some(data.len().saturating_sub(*pos)),
Stream::Current => Some(me.lex.data().len()),
Stream::Pending { .. } => None,
},
};
let before = left(self);
if self.materialize(f).is_err() {
*f.borrow_mut() = Stream::Pending { chain, from };
return;
// A filter that read its data before a later one failed has the file past that data,
// where reading the image would leave it: the file is empty from there.
if left(self) != before {
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
return;
}
// Decompressed data too large to hold: the first filter only measures it instead,
// and the file is read past it. Data that can't be decoded at all leaves the file as
// it was; the import goes on without the image either way.
let Some(first) = chain.first() else { return };
// Measuring decompresses the data, which is charged by the bytes decoded (one operation
// per 256, as `spend_bytes` charges) and stops at what the budget still pays for:
// data measured again and again (a reusable stream reset in a loop) runs out of the
// budget instead of being decoded in full on every pass.
let most = usize::try_from(self.ops_left().saturating_mul(256)).unwrap_or(usize::MAX);
let (used, decoded) = match &from {
Some(r) => match &*r.borrow() {
Stream::Buf { data, pos, .. } => encoded_len(first, data.get(*pos..).unwrap_or_default(), most),
_ => (None, 0),
},
None => encoded_len(first, self.lex.data(), most),
};
let paid = self.spend_bytes(decoded).is_ok();
let Some(used) = used.filter(|_| paid) else {
*f.borrow_mut() = Stream::Pending { chain, from };
return;
};
match &from {
Some(r) => {
if let Stream::Buf { pos, .. } = &mut *r.borrow_mut() {
*pos = pos.saturating_add(used);
}
}
None => self.lex.advance(used),
}
}
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
}
/// The rows image `s` reads at `step` (rows of `row` bytes), when its one source is the
/// program's data with Flate or LZW last among its filters (and no predictor): the filters
/// before it are decoded as usual, and it decodes into the rows read alone, dropping the
/// others as it goes. `None` (nothing read) for other data, or rows read that would still be
/// more than the reader holds.
fn read_rows(&mut self, s: &Spec, row: usize, step: usize) -> Res<Option<Vec<u8>>> {
let ([Source::File(f)], oh) = (s.sources.as_slice(), s.h.div_ceil(step)) else { return Ok(None) };
let (chain, from) = match &*f.borrow() {
Stream::Pending { chain, from } => (chain.clone(), from.clone()),
_ => return Ok(None),
};
let Some((last, head)) = chain.split_last() else { return Ok(None) };
if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") {
return Ok(None);
}
let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) };
self.alloc(kept)?;
// The compressed data: what the filters before the last one decode, or the file itself.
let compressed = if head.is_empty() {
None
} else {
*f.borrow_mut() = Stream::Pending { chain: head.to_vec(), from: from.clone() };
if let Err(e) = self.materialize(f) {
*f.borrow_mut() = Stream::Pending { chain, from };
return Err(e);
}
match std::mem::replace(&mut *f.borrow_mut(), Stream::Buf { data: vec![], pos: 0, rgb: None }) {
Stream::Buf { data, pos, .. } => Some(data.get(pos..).unwrap_or_default().to_vec()),
_ => Some(vec![]),
}
};
let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize);
// Past the image's data and as much again the data is not an image's: it stops there.
let most = row.saturating_mul(s.h).saturating_add(MAX_DATA);
let mut sink = |mut chunk: &[u8]| -> Res {
while !chunk.is_empty() {
let (r, off) = (seen / row.max(1), seen % row.max(1));
let take = (row - off).min(chunk.len());
if r < s.h && picked(r / step, step, s.h) == r {
rows.extend_from_slice(chunk.get(..take).unwrap_or_default());
}
seen += take;
chunk = chunk.get(take..).unwrap_or_default();
}
if seen > most {
return Err(PsError::Limit("decoded data is too large"));
}
Ok(())
};
let used = match &compressed {
Some(data) => decode_into(last, data, &mut sink),
None => match &from {
Some(r) => {
let b = r.borrow();
let Stream::Buf { data, pos, .. } = &*b else { return io("filter") };
let used = decode_into(last, data.get(*pos..).unwrap_or_default(), &mut sink);
drop(b);
if let (Some(Ok(n)), Stream::Buf { pos, .. }) = (&used, &mut *r.borrow_mut()) {
*pos = pos.saturating_add(*n);
}
used
}
None => {
let used = decode_into(last, self.lex.data(), &mut sink);
if let Some(Ok(n)) = &used {
self.lex.advance(*n);
}
used
}
},
};
drop(sink);
let Some(used) = used else { return Ok(None) };
// What was decoded is charged whether or not the data decoded to its end.
self.spend_bytes(seen)?;
used?;
*f.borrow_mut() = Stream::Buf { data: vec![], pos: 0, rgb: None };
rows.resize(kept, 0);
Ok(Some(rows))
}
/// Leave out image `s` (too large to read), skipping its data: `None`, the image it gives.
fn leave_out(&mut self, s: &Spec) -> Option<Pixels> {
self.out.warn(TOO_LARGE);
let n = if s.stencil.is_some() { 1 } else { s.space.n() };
let per_source = if s.sources.len() > 1 { 1 } else { n };
let bytes = (s.w.saturating_mul(per_source).saturating_mul(usize::from(s.bpc))).div_ceil(8).saturating_mul(s.h);
for src in &s.sources {
self.skip_data(src, bytes);
}
None
}
/// The bytes a data procedure gives, called until it gives an empty string or `n` bytes.
fn gather(&mut self, p: &Obj, n: usize) -> Res<Vec<u8>> {
Ok(self.read_sources(&[Source::Proc(p.clone())], n, n)?.pop().unwrap_or_default())
@@ -640,13 +801,6 @@ impl Interp<'_> {
let mut stencil = self.image_dict(&mask, false)?;
stencil.space = Space::Gray;
let n = image.space.n();
if image.w.saturating_mul(image.h) > MAX_PIXELS || stencil.w.saturating_mul(stencil.h) > MAX_PIXELS {
self.out.warn(TOO_LARGE);
for src in image.sources.iter().chain(&stencil.sources) {
self.skip_data(src);
}
return Ok(None);
}
// Interleaved data is read into this decoder's own buffers, split into the two images'
// samples: those stop counting once both are decoded (their pixels still count).
let mut charged = 0;
@@ -655,18 +809,19 @@ impl Interp<'_> {
let (pixels, samples) = if interleave == 2.0 {
let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n));
let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h));
self.alloc(total)?;
charged = total;
let raw = self.source_bytes(&src, total.min(MAX_DATA))?;
// What is read: an image past the pixel cap is reduced from the samples read.
charged = total.min(MAX_DATA);
self.alloc(charged)?;
let raw = self.source_bytes(&src, charged)?;
by_rows(&raw, (mrow, stencil.h), (drow, image.h))
} else {
// Each sample: the mask's value, then the colour's, as many bits each.
stencil.bpc = image.bpc;
(stencil.w, stencil.h) = (image.w, image.h);
let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8);
charged = row.saturating_mul(image.h);
charged = row.saturating_mul(image.h).min(MAX_DATA);
self.alloc(charged)?;
let raw = self.source_bytes(&src, charged.min(MAX_DATA))?;
let raw = self.source_bytes(&src, charged)?;
by_samples(&raw, image.w, image.h, n, image.bpc)
};
stencil.sources = vec![Source::Str(pixels)];
@@ -674,7 +829,12 @@ impl Interp<'_> {
}
let decoded = match self.decode_image(image) {
Ok(Some(img)) => self.decode_image(stencil).map(|m| Some((img, m))),
other => other.map(|_| None),
Ok(None) => {
// The mask's own data (`InterleaveType` 3) is skipped with the image's.
let _ = self.leave_out(&stencil);
Ok(None)
}
Err(e) => Err(e),
};
self.unalloc(charged);
let Some((mut img, m)) = decoded? else { return Ok(None) };
@@ -755,25 +915,53 @@ impl Interp<'_> {
Ok(Spec { w, h, bpc, space, decode: vec![], matrix, sources, mask_color: None, stencil })
}
/// Decode the filters image source `f` waits to run. `false` when the decoded data is past
/// what the reader holds and the image is `reduced` (read at a lower resolution): a decode that
/// fails leaves the file empty (`materialize`), but such an image is left out with its data
/// still to skip, so its filters are put back for that.
fn decode_source(&mut self, f: &Rc<RefCell<Stream>>, reduced: bool) -> Res<bool> {
let pending = match &*f.borrow() {
Stream::Pending { chain, from } => Some((chain.clone(), from.clone())),
_ => None,
};
match self.materialize(f) {
Ok(()) => Ok(true),
Err(PsError::Limit(_)) if reduced => {
if let Some((chain, from)) = pending {
*f.borrow_mut() = Stream::Pending { chain, from };
}
Ok(false)
}
Err(e) => Err(e),
}
}
/// The image's pixels, straight RGBA, rows from the first one read, and a CMYK image's ink
/// amounts.
fn decode_image(&mut self, s: Spec) -> Res<Option<Pixels>> {
if !matches!(s.bpc, 1 | 2 | 4 | 8 | 12 | 16) {
return ps_err("rangecheck", "BitsPerComponent");
}
if s.w.saturating_mul(s.h) > MAX_PIXELS {
self.out.warn(TOO_LARGE);
for src in &s.sources {
self.skip_data(src);
}
return Ok(None);
}
self.alloc(s.w * s.h * 4)?;
// An image of more pixels than the cap is read at a lower resolution: every `step`th
// sample of every `step`th row (the middle one of each `step` × `step` block).
let step = reduction(s.w, s.h);
let (ow, oh) = (s.w.div_ceil(step), s.h.div_ceil(step));
let n = if s.stencil.is_some() { 1 } else { s.space.n() };
let bpc = usize::from(s.bpc);
for src in &s.sources {
if let Source::File(f) = src {
self.materialize(f)?;
// A reduced image compressed last with Flate or LZW keeps only the rows it reads, as they
// are decoded: its whole data can be more than the reader holds.
let streamed = match if step > 1 { self.read_rows(&s, (s.w * n * bpc).div_ceil(8), step) } else { Ok(None) } {
Ok(rows) => rows,
Err(PsError::Limit(_)) => return Ok(self.leave_out(&s)),
Err(e) => return Err(e),
};
for src in s.sources.iter().filter(|_| streamed.is_none()) {
// Decoded data past the cap: a reduced image is left out (its data skipped) rather
// than failing the file, as an image too large to read at all is.
if let Source::File(f) = src
&& !self.decode_source(f, step > 1)?
{
return Ok(self.leave_out(&s));
}
}
// A decoded JPEG gives 8-bit gray, RGB or CMYK samples whatever the color space says.
@@ -798,15 +986,39 @@ impl Interp<'_> {
if sources.len() > n {
return ps_err("rangecheck", "DataSource");
}
let plane = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA).ok_or(PsError::Limit("decoded data is too large"))?;
// The sample planes are this decoder's own and live only while the image is decoded: they
// stop counting once it is (the pixels made from them still count). What the data source
// procedures allocate is the program's and stays counted.
let plane_bytes = plane.saturating_mul(sources.len());
self.alloc(plane_bytes)?;
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
for p in &mut planes {
p.resize(row * s.h, 0);
// With only the rows read kept, row `i` of the plane is the `i`th row read.
let rows_kept = streamed.is_some();
// The sample planes (or the rows kept) are this decoder's own and live only while the
// image is decoded: they stop counting once it is (the pixels made from them still
// count). What the data source procedures allocate is the program's and stays counted.
let (planes, plane_bytes) = match streamed {
Some(rows) => {
let kept = rows.len();
(vec![rows], kept)
}
None => {
// More samples than the reader holds: a reduced image is left out (its data
// skipped), while one within the pixel cap whose samples are still too much data
// (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane
// is refused).
let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else {
if step > 1 {
return Ok(self.leave_out(&s));
}
return Err(PsError::Limit("decoded data is too large"));
};
let plane_bytes = plane.saturating_mul(sources.len());
self.alloc(plane_bytes)?;
let mut planes = self.read_sources(sources, row * s.h, if multi { row } else { row * s.h })?;
for p in &mut planes {
p.resize(row * s.h, 0);
}
(planes, plane_bytes)
}
};
self.alloc(ow * oh * 4)?;
if step > 1 {
self.out.warn(REDUCED);
}
let max = ((1u32 << bpc.min(16)) - 1) as f64;
let sample = |plane: &[u8], y: usize, i: usize| -> u32 {
@@ -830,19 +1042,19 @@ impl Interp<'_> {
// with the default Decode array.
let decode = if s.decode.len() >= 2 * n && jpeg.is_none_or(|c| c == 4) { s.decode.clone() } else { default_decode };
let paint = self.g.paint.color().map(|c| c.to_rgba8(1.0));
let mut rgba = Vec::with_capacity(s.w * s.h * 4);
let mut rgba = Vec::with_capacity(ow * oh * 4);
// CMYK samples keep their ink amounts, as the Decode array reads them.
let mut inks = if matches!(space, Space::Cmyk) && s.stencil.is_none() {
self.alloc(s.w * s.h * 4)?;
Some(Vec::with_capacity(s.w * s.h * 4))
self.alloc(ow * oh * 4)?;
Some(Vec::with_capacity(ow * oh * 4))
} else {
None
};
let mut cache: HashMap<Vec<u32>, [u8; 3]> = HashMap::new();
let mut raw = vec![0u32; n];
let mut comps = vec![0f64; n];
for y in 0..s.h {
for x in 0..s.w {
for y in (0..oh).map(|y| if rows_kept { y } else { picked(y, step, s.h) }) {
for x in (0..ow).map(|x| picked(x, step, s.w)) {
for (c, slot) in raw.iter_mut().enumerate() {
*slot = match planes.as_slice() {
[one] => sample(one, y, x * n + c),
@@ -882,7 +1094,9 @@ impl Interp<'_> {
}
drop(planes);
self.unalloc(plane_bytes);
Ok(Some(Pixels { w: s.w as u32, h: s.h as u32, rgba, inks, matrix: s.matrix }))
// The reduced samples cover the image's area: image space scaled to them.
let matrix = Affine::scale_non_uniform(ow as f64 / s.w as f64, oh as f64 / s.h as f64) * s.matrix;
Ok(Some(Pixels { w: ow as u32, h: oh as u32, rgba, inks, matrix }))
}
/// One pixel's colour in `space` as display RGB.
@@ -959,3 +1173,19 @@ impl Interp<'_> {
Some(OpacityMask::new(Node::new(self.out.doc.alloc_id(), NodeKind::Image(Box::new(im))), true))
}
}
/// The sample (or row) of `len` a reduced image reads as its `i`th at `step`: the middle one of
/// its block of `step`, the last one in a short last block.
fn picked(i: usize, step: usize, len: usize) -> usize {
(i * step + step / 2).min(len.saturating_sub(1))
}
/// The step [`Interp::decode_image`] reads a `w` × `h` image at: 1 (every sample) within
/// [`MAX_PIXELS`], else the least that brings the samples it reads within it.
fn reduction(w: usize, h: usize) -> usize {
let mut step = 1;
while w.div_ceil(step).saturating_mul(h.div_ceil(step)) > MAX_PIXELS {
step += 1;
}
step
}
+192
View File
@@ -0,0 +1,192 @@
//! The fonts an EPS carries (embeds) for type whose fonts aren't available here, kept with the
//! document as PDF import keeps a PDF's (#4568): the glyphs its type is shown in, gathered as the
//! program runs, become one font per family and style ([`vectorcraft_text::build_file_font`]),
//! which draws that type as the file draws it until its text is edited
//! ([`vectorcraft_doc::FileFonts`]).
//!
//! Each glyph comes from the font program the file carries (a Type 1 font's charstrings, a Type 42
//! font's TrueType glyph): its outline and advance, for the character its code shows. The first
//! glyph of each character is kept; a string that uses a different glyph for a character is drawn
//! as outlines instead.
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind};
use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font};
/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes).
const MAX_GLYPHS: usize = 200_000;
/// The glyphs gathered so far.
#[derive(Default)]
pub(crate) struct FileFontGlyphs {
fonts: Vec<Gathered>,
/// Each font (family and style) by its index in `fonts`.
index: HashMap<(String, String), usize>,
/// Glyphs gathered, in all.
count: usize,
}
/// The glyphs of one family and style.
struct Gathered {
family: String,
style: String,
info: FileFontInfo,
glyphs: Vec<FileGlyph>,
/// Each character's glyph, by its index in `glyphs`.
chars: HashMap<char, usize>,
}
impl FileFontGlyphs {
/// The font of `family` and `style` (made with `info` the first time): its index.
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) {
return i;
}
let i = self.fonts.len();
self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() });
self.index.insert((family.to_string(), style.to_string()), i);
i
}
/// Can `glyphs` all be drawn in font `font`: no character among them has a glyph there, or
/// earlier in `glyphs`, that differs in outline or advance (a font keeps one glyph per
/// character), and the font has room for the characters it doesn't have yet? Each glyph is
/// compared with the one its character has, once, as PDF import does.
pub fn fits(&self, font: usize, glyphs: &[FileGlyph]) -> bool {
let Some(f) = self.fonts.get(font) else { return false };
let mut new: HashMap<char, &FileGlyph> = HashMap::new();
for g in glyphs {
let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied());
match kept {
Some(k) if k.outline != g.outline || k.advance != g.advance => return false,
Some(_) => {}
None => {
new.insert(g.ch, g);
}
}
}
f.glyphs.len().saturating_add(new.len()) <= MAX_FILE_GLYPHS && self.count.saturating_add(new.len()) <= MAX_GLYPHS
}
/// Gather `glyph` for font `font`, unless it already has one for its character or is full.
pub fn add(&mut self, font: usize, glyph: FileGlyph) {
if self.count >= MAX_GLYPHS {
return;
}
if let Some(f) = self.fonts.get_mut(font)
&& f.glyphs.len() < MAX_FILE_GLYPHS
&& !f.chars.contains_key(&glyph.ch)
{
f.chars.insert(glyph.ch, f.glyphs.len());
f.glyphs.push(glyph);
self.count += 1;
}
}
/// The fonts built from the glyphs gathered, stored in `images` under their content keys:
/// family and style → the font's key.
pub fn keep(self, images: &mut BTreeMap<String, ImageBlob>) -> HashMap<(String, String), String> {
let mut kept = HashMap::new();
for f in self.fonts {
let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue };
let blob = ImageBlob::new(FILE_FONT_MIME, bytes);
let base = blob.content_key();
let mut key = base.clone();
let mut suffix = 1;
while images.get(&key).is_some_and(|held| held != &blob) {
key = format!("{base}-{suffix}");
suffix += 1;
}
images.entry(key.clone()).or_insert(blob);
kept.insert((f.family, f.style), key);
}
kept
}
}
/// The type among `nodes` (and in their groups) shown in fonts the file carries ([`mark`]), in the
/// families and styles `kept` holds fonts for (family and style → the font's blob in `images`):
/// drawn in them while its text is the file's, and laid out again for its bounds. Type in a font
/// the file only names keeps the fallback font, also where its family and style are the same.
pub(crate) fn keep_file_fonts(nodes: &mut [Arc<Node>], kept: &HashMap<(String, String), String>, images: &BTreeMap<String, ImageBlob>) {
if kept.is_empty() {
return;
}
let db = vectorcraft_text::FontDb::global();
for n in nodes.iter_mut() {
if n.children().is_some_and(|c| !c.is_empty())
&& let Some(children) = Arc::make_mut(n).children_mut()
{
keep_file_fonts(children, kept, images);
}
let NodeKind::Text(t) = &n.kind else { continue };
if t.file_fonts.is_none() {
continue;
}
let mut fonts: Vec<FileFont> = vec![];
for r in &t.runs {
let (family, style) = (&r.style.font_family, &r.style.font_style);
if let Some(key) = kept.get(&(family.clone(), style.clone()))
&& !fonts.iter().any(|f| f.family == *family && f.style == *style)
{
fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() });
}
}
if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind {
if fonts.is_empty() {
t.file_fonts = None;
continue;
}
t.file_fonts = Some(Box::new(FileFonts::new(fonts, &t.plain_text())));
db.bind_file_fonts(t, |key| images.get(key));
t.cached_bounds = Some(vectorcraft_text::layout(db, t).bounds);
}
}
}
/// Mark type `t` as shown in a font the file carries, so that [`keep_file_fonts`] gives it the font
/// kept for its family and style (the key is filled in then).
pub(crate) fn mark(t: &mut vectorcraft_doc::TextObject) {
let fonts = t.runs.first().map(|r| FileFont { family: r.style.font_family.clone(), style: r.style.font_style.clone(), key: String::new() });
t.file_fonts = Some(Box::new(FileFonts::new(fonts.into_iter().collect(), &t.plain_text())));
}
#[cfg(test)]
mod tests {
use super::*;
use kurbo::Shape;
fn glyph(ch: char) -> FileGlyph {
FileGlyph { ch, outline: kurbo::Rect::new(0.0, 0.0, 400.0, 500.0).to_path(0.1), advance: 600.0 }
}
/// A font full of glyphs takes no new character, so a string that needs one doesn't fit (it
/// comes in as outlines rather than as type the kept font can't draw); its own characters
/// still fit.
#[test]
fn a_full_font_takes_no_new_character() {
let mut g = FileFontGlyphs::default();
let f = g.font("F", "Regular", FileFontInfo::default);
let chars: Vec<char> = (0x10000u32..).filter_map(char::from_u32).take(MAX_FILE_GLYPHS).collect();
for &c in &chars {
g.add(f, glyph(c));
}
assert!(g.fits(f, &[glyph(chars[0]), glyph(chars[1])]));
assert!(!g.fits(f, &[glyph(chars[0]), glyph('A')]));
}
/// A long string of one character compares each glyph with that character's once, not with
/// every one before it: a quarter of a million of them fit at once.
#[test]
fn a_long_string_of_one_character_fits_in_linear_time() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut g = FileFontGlyphs::default();
let f = g.font("F", "Regular", FileFontInfo::default);
tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok();
});
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true));
}
}
+4
View File
@@ -152,6 +152,9 @@ pub(crate) struct Out {
pub(super) tilings: HashMap<u64, Vec<Tiling>>,
/// How deep art drawn apart (a pattern's cell, a Type 3 glyph) is nested.
pub apart: u32,
/// The glyphs of fonts the file carries for families that aren't available, gathered for the
/// fonts kept with the document (see `file_fonts`).
pub file_glyphs: super::super::file_fonts::FileFontGlyphs,
}
fn sane(r: Rect) -> bool {
@@ -201,6 +204,7 @@ impl Out {
shadings: HashSet::new(),
tilings: HashMap::new(),
apart: 0,
file_glyphs: Default::default(),
}
}
+1 -1
View File
@@ -936,7 +936,7 @@ fn device_settings_are_accepted_and_change_nothing() {
/// `warnings` without the note naming fonts that aren't available: which those are depends on the
/// fonts installed where the tests run, not on the program.
pub(super) fn program_warnings(warnings: &[String]) -> Vec<&String> {
warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE)).collect()
warnings.iter().filter(|w| !w.starts_with(super::MISSING_FONTS_NOTE) && !w.starts_with(super::CARRIED_FONTS_NOTE)).collect()
}
fn blue(body: &str) {
+135 -11
View File
@@ -552,29 +552,153 @@ fn tiff_predicted_rows_at_every_depth() {
assert!(wrong.is_empty(), "{wrong:#?}");
}
/// An image too large to read is left out, and its data is skipped, as reading it would leave
/// the program: the art after it is read, not the data as PostScript. Here the data ends at its
/// `~>` (an inline image of a content stream run as a file, as PDF-reading prologs write it), at
/// a `SubFileDecode` end string, and at the end of compressed data that is read whole.
/// An image over the reader's pixel cap is read at a lower resolution, or when its data is too
/// large to hold left out with its data skipped; either way the program goes on after the data,
/// as reading the whole image would leave it: the art after it is read, not the data as
/// PostScript. Here the data ends at its `~>` (an inline image of a content stream run as a file,
/// as PDF-reading prologs write it), at a `SubFileDecode` end string, and at the end of
/// compressed data that is read whole.
#[test]
fn the_data_of_an_image_too_large_to_read_is_skipped() {
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
let packed = crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64]));
for program in [
format!(
"/ID {{ << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] \
/DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /LZWDecode filter >> \
/DataSource currentfile 0 (~>) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter >> \
/DeviceRGB setcolorspace image }} def\n\
currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\nJ1_V7fG\"r'\"b]2#:hXAd)~>\n{after}\nendstream\n"
currentfile 0 (endstream) /SubFileDecode filter cvx exec\nID\n{packed}\n{after}\nendstream\n"
),
format!("10000 10000 8 [1 0 0 1 0 0] currentfile /ASCIIHexDecode filter false 3 colorimage\n0a1b 2c3d 4e5f>\n{after}"),
format!(
"10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /FlateDecode filter image\n\
x\u{9c}garbage\n%%EndData\n{after}"
"10000 10000 8 [1 0 0 1 0 0] currentfile 0 (%%EndData) /SubFileDecode filter /ASCII85Decode filter /FlateDecode filter image\n\
{packed}\n%%EndData\n{after}"
),
format!("10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{packed}\n{after}"),
] {
let r = read(&program);
assert!(r.warnings.iter().any(|w| w.contains("too large to read") || w.contains("lower resolution")), "{program}: {:?}", r.warnings);
let o = super::tests::objects(&r.document);
let last = o.last().expect("the art after the image");
assert_eq!(super::tests::fill(last), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{program}");
}
}
/// An image of more pixels than the reader's cap (2^26) is read at a lower resolution, every
/// second sample of every second row here, over the same area, with a note; not left out.
#[test]
fn an_image_over_the_pixel_cap_is_read_at_a_lower_resolution() {
// 9000 × 8000 one-bit samples, every row the same: its left half ones, painted.
let row = format!("{}{}", "ff".repeat(563), "00".repeat(562));
let r = read(&format!("0 0 1 setrgbcolor 90 80 scale 9000 8000 true [9000 0 0 -8000 0 8000] <{row}> imagemask"));
assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings);
let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else {
panic!("an image")
};
assert_eq!((im.width, im.height), (4500, 4000));
// Its 4500 × 4000 pixels cover the 90 × 80 points the image does.
let corner = im.xf * kurbo::Point::new(4500.0, 4000.0);
let origin = im.xf * kurbo::Point::ZERO;
assert!(((corner - origin).x.abs() - 90.0).abs() < 1e-6 && ((corner - origin).y.abs() - 80.0).abs() < 1e-6, "{:?}", im.xf);
// Left half painted, right half clear.
assert_eq!(pixel(&r.document, 100, 2000)[3], 255);
assert_eq!(pixel(&r.document, 4400, 2000)[3], 0);
}
/// An image over the pixel cap whose samples are more data than the reader holds (9500 × 9500
/// RGB is 270 MB) is read at a lower resolution too when Flate or LZW compresses it last: only
/// the rows it reads are kept as they are decoded.
#[test]
fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() {
let (w, h) = (9500usize, 9500usize);
let mut samples = Vec::with_capacity(w * h * 3);
for y in 0..h {
let px: [u8; 3] = if y < h / 2 { [255, 0, 0] } else { [0, 0, 255] };
samples.extend(std::iter::repeat_n(px, w).flatten());
}
let data = crate::ps::ascii85(&crate::ps::deflate(&samples));
drop(samples);
let r = read(&format!(
"95 95 scale {w} {h} 8 [{w} 0 0 -{h} 0 {h}] currentfile /ASCII85Decode filter /FlateDecode filter false 3 colorimage\n{data}\n\
0 1 0 setrgbcolor 0 0 0.1 0.1 rectfill"
));
assert!(r.warnings.iter().any(|w| w.contains("lower resolution")), "{:?}", r.warnings);
let NodeKind::Image(im) = &all(&r.document).into_iter().find(|n| matches!(n.kind, NodeKind::Image(_))).expect("an image").kind else {
panic!("an image")
};
assert_eq!((im.width, im.height), (4750, 4750));
// The rows read from the top half are red, from the bottom half blue.
assert_eq!(pixel(&r.document, 10, 10), [255, 0, 0, 255]);
assert_eq!(pixel(&r.document, 10, 4740), [0, 0, 255, 255]);
// The art after the data is read.
assert_eq!(super::tests::objects(&r.document).len(), 2);
}
/// An image too large to read even at a lower resolution (its samples are more data than the
/// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure
/// is called until the data ends; when its first filter decompresses to more than the reader
/// holds (and can't be read a row at a time), the compressed data is measured without keeping it.
#[test]
fn the_data_of_an_image_too_large_to_hold_is_skipped() {
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]);
// Predicted rows aren't decoded a row at a time: such an image is left out.
let mut flate =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
flate.extend(&zeros);
flate.extend(format!("\n{after}").as_bytes());
for program in [
format!(
"10000 10000 true [1 0 0 1 0 0] currentfile /ASCII85Decode filter imagemask\n{}\n{after}",
crate::ps::ascii85(&crate::ps::deflate(&[0u8; 64]))
),
"/F currentfile 0 (%%EndData) /SubFileDecode filter def \
10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}"
)
.into_bytes(),
flate,
] {
let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned();
let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
file.extend(&program);
file.extend(b"\nshowpage\n%%EOF\n");
let r = import(&file).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings);
let o = super::tests::objects(&r.document);
assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings);
assert_eq!(super::tests::fill(&o[0]), Some(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))), "{text}");
}
}
/// Measuring the data of an image too large to hold decompresses it, and that is charged to the
/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed
/// zeros is left out and measured again each time a loop runs the stream from its start, runs out
/// of the budget.
#[test]
fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() {
let mut program =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
program.extend(crate::ps::deflate(&vec![0u8; 300 << 20]));
let hex: String = program.iter().map(|b| format!("{b:02x}")).collect();
super::tests::runs_out_of_budget(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"));
}
/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is
/// skipped too: unfiltered from the program's own file by its byte count, and through a filter
/// shared with later reads, which then find the file past the data (here the second filter fails
/// on what the first decoded) rather than decoding the program after it.
#[test]
fn the_mask_data_of_an_image_left_out_is_skipped() {
let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill";
let masked = |source: &str| {
format!(
"<< /ImageType 3 /InterleaveType 3 /DataDict << /ImageType 1 /Width 10000 /Height 10000 /BitsPerComponent 8 \
/Decode [0 1 0 1 0 1] /ImageMatrix [1 0 0 1 0 0] /DataSource (x) >> \
/MaskDict << /ImageType 1 /Width 10 /Height 10 /BitsPerComponent 1 /Decode [0 1] /ImageMatrix [1 0 0 1 0 0] \
/DataSource {source} >> >> /DeviceRGB setcolorspace image"
)
};
for program in [
// 10 rows of 2 bytes, not PostScript.
format!("{}\n{}\n{after}", masked("currentfile"), "@".repeat(20)),
format!("/F currentfile /ASCIIHexDecode filter /ASCII85Decode filter def {}\n7676>\nF read {{ pop }} if {after}", masked("F")),
] {
let r = read(&program);
assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{program}: {:?}", r.warnings);
+130 -2
View File
@@ -138,8 +138,136 @@ fn type_in_fonts_that_arent_available_is_named_in_a_warning() {
/Nowhere-Bold 12 selectfont 10 80 moveto (x) show /Inter-Regular 12 selectfont 10 90 moveto (y) show",
);
assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_family.as_str()).collect::<Vec<_>>(), ["Test One", "Test One", "Nowhere", "Inter"]);
// PDF import's words.
assert_eq!(r.warnings, ["fonts that aren't available show in the fallback font until they are: Test One, Nowhere"]);
// PDF import's words: the font the file carries draws its type, the one it only names doesn't.
assert_eq!(
r.warnings,
[
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One",
"fonts that aren't available show in the fallback font until they are: Nowhere",
]
);
// A font found by name keeps no glyphs of the file's: it shows in the fallback font, as before.
assert!(texts(&r).iter().filter(|t| t.runs[0].style.font_family != "Test One").all(|t| t.file_fonts.is_none()));
}
/// The glyphs of type laid out in the document's fonts: each one's outline (text space) and origin,
/// and whether a font the file carries draws it.
fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
vectorcraft_text::layout(db, t).glyphs.iter().map(|g| (g.outline.bounding_box(), g.origin.x, db.is_file_font(g.font_id))).collect()
}
/// Type in a Type 1 font the file carries, whose family isn't available, is drawn with the file's
/// glyphs, as PDF import keeps a PDF's fonts (#4568): A the square and B the triangle, at the
/// font's own advances (no tracking makes up for a stand-in's), not in the fallback font.
#[test]
fn embedded_type1_type_draws_with_the_files_glyphs() {
let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show");
let t = &texts(&r)[0];
assert!(t.file_fonts.is_some(), "{:?}", r.warnings);
let glyphs = laid_out(t);
assert_eq!(glyphs.len(), 2);
assert!(glyphs.iter().all(|g| g.2), "every glyph the file's: {glyphs:?}");
// The square is 400 by 500 units, the triangle 500 by 400, at 50 points an em.
let (a, b) = (glyphs[0].0, glyphs[1].0);
assert!((a.width() - 20.0).abs() < 0.05 && (a.height() - 25.0).abs() < 0.05, "{a:?}");
assert!((b.width() - 25.0).abs() < 0.05 && (b.height() - 20.0).abs() < 0.05, "{b:?}");
// B starts where A's 600 units end, with no tracking.
assert!((glyphs[1].1 - glyphs[0].1 - 30.0).abs() < 0.05, "{glyphs:?}");
assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs);
}
/// A family whose regular style the file carries but whose bold it only names: the regular is
/// drawn in the kept font and the bold in the fallback font, and the warning says both.
#[test]
fn a_carried_style_leaves_a_named_style_of_its_family_in_the_fallback_warning() {
let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Bold 12 selectfont 10 80 moveto (x) show");
assert_eq!(texts(&r).iter().map(|t| t.runs[0].style.font_style.as_str()).collect::<Vec<_>>(), ["Regular", "Bold"]);
assert_eq!(
r.warnings,
[
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One",
"fonts that aren't available show in the fallback font until they are: Test One",
]
);
}
/// Type in a font the file only names keeps the fallback font, and the spacing set for it, also
/// when its family and style are those of a font the file carries (`TestOne-Roman` beside the
/// embedded `TestOne`): only type shown in the carried font gets the font kept from it.
#[test]
fn a_named_font_in_a_carried_family_and_style_keeps_the_fallback_font() {
let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show /TestOne-Roman 50 selectfont 10 60 moveto (AA) show");
let t = texts(&r);
assert_eq!(t.len(), 2, "{:?}", all(&r.document));
assert_eq!((t[1].runs[0].style.font_family.as_str(), t[1].runs[0].style.font_style.as_str()), ("Test One", "Regular"));
assert!(t[0].file_fonts.is_some());
assert!(t[1].file_fonts.is_none(), "the named font's type isn't drawn in the carried font");
// The warning says so for each: one drawn as the file draws it, one in the fallback font.
assert_eq!(
r.warnings,
[
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): Test One",
"fonts that aren't available show in the fallback font until they are: Test One",
]
);
}
/// A character the file draws with a different glyph from the one the kept font already has for
/// it (here a second font of the same name whose A is a narrower square) can't go in that font:
/// that string comes in as outlines, the first stays type in the file's glyphs.
#[test]
fn a_second_glyph_for_a_character_keeps_its_type_as_outlines() {
let narrow = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[200, 0], 5), (&[0, 500], 5), (&[-200, 0], 5), (&[], 9), (&[], 14)]);
let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
let file = [
head,
font(OWN, false),
b"/TestOne findfont 50 scalefont setfont 10 20 moveto (A) show\n".to_vec(),
font_with(OWN, false, &[], Some(narrow)),
b"/TestOne findfont 50 scalefont setfont 10 60 moveto (A) show\nshowpage\n%%EOF\n".to_vec(),
]
.concat();
let r = import(&file).unwrap();
let t = texts(&r);
assert_eq!(t.len(), 1, "{:?}", all(&r.document));
assert!(laid_out(&t[0]).iter().all(|g| g.2));
let paths: Vec<_> = all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).map(|n| bounds(n)).collect();
assert!(paths.iter().any(|b| (b.width() - 10.0).abs() < 0.05 && (b.height() - 25.0).abs() < 0.05), "the narrow A as outlines: {paths:?}");
}
/// The type opened in the app keeps the file's glyphs through a save and a reopen, takes the
/// fallback font once its text is edited, and gets the file's glyphs back on undo, as PDF type in
/// a font the file carries does.
#[test]
fn kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited() {
use vectorcraft_testkit::{Session, json};
let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec();
let file = [head, font(OWN, false), b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec()].concat();
let mut s = Session::new();
let opened = s.execute("document.open", &json!({"name": "kept.eps", "dataBase64": vectorcraft_testkit::format::base64_encode(&file)})).unwrap();
assert!(opened["warnings"].to_string().contains("until their text is edited"), "{opened}");
let carried = |s: &Session| {
let (mut glyphs, mut id) = (vec![], None);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
glyphs.extend(laid_out(t).into_iter().map(|g| g.2));
id = Some(n.id);
}
});
(glyphs, id)
};
let (glyphs, id) = carried(&s);
assert_eq!(glyphs, [true, true]);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(carried(&s).0, [true, true], "saved and opened again");
let id = carried(&s).1.or(id).unwrap();
s.execute("text.setText", &json!({"id": id, "text": "ABA"})).unwrap();
assert!(carried(&s).0.iter().all(|g| !g), "edited: the fallback font");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(carried(&s).0, [true, true], "undone: the file's glyphs again");
}
#[test]
+16
View File
@@ -111,6 +111,22 @@ fn the_fonts_own_widths_space_its_type_and_move_the_point() {
check("newpath 10 20 moveto (\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into());
}
/// Type in a Type 42 font the file carries, whose family (Plain42) isn't available, is drawn
/// with the file's glyphs kept with the document, spaced by their own widths, as a Type 1 font's
/// is (see `tests_type1`).
#[test]
fn type_in_a_carried_type42_font_draws_with_the_files_glyphs() {
let (h, wh) = glyph('H');
let (i, _) = glyph('I');
let r = read(&format!("{} /Plain42 findfont 50 scalefont setfont 10 20 moveto (\\001\\002) show", font(&[h, i])));
let t = &texts(&r)[0];
assert!(t.file_fonts.is_some(), "{:?}", r.warnings);
let db = vectorcraft_text::FontDb::global();
assert!(vectorcraft_text::layout(db, t).glyphs.iter().all(|g| db.is_file_font(g.font_id)));
let o = origins(t);
assert!((o[1] - o[0] - 50.0 * wh).abs() < 0.05, "{o:?}");
}
/// `xshow` and `ashow` put each character where they say: the type's tracking makes up the
/// difference from its font's advances.
#[test]
+86 -5
View File
@@ -9,7 +9,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::TextLayout;
use vectorcraft_text::{FileFontInfo, FileGlyph, TextLayout};
use super::cid::Base;
use super::graphics::MAX_APART;
@@ -675,6 +675,17 @@ impl Interp<'_> {
{
return self.show_type42_outlines(data, glyphs, s, spacing, at, f1);
}
// Type in a font the file carries whose family isn't available is drawn in a font made of
// the file's glyphs (see `file_fonts`), spaced by their own advances. A character whose
// glyph differs from the one that font has for it keeps the string as outlines.
let kept = match &plain {
Some((data, glyphs)) => match self.keep_file_glyphs(data, glyphs)? {
Some(true) => true,
Some(false) => return self.show_type42_outlines(data, glyphs, s, spacing, at, f1),
None => false,
},
None => false,
};
// Each code's character, if it has one that shows (control codes don't).
let chars = match &plain {
Some((_, glyphs)) => glyphs.iter().map(|g| g.ch).collect::<Vec<_>>(),
@@ -685,7 +696,49 @@ impl Interp<'_> {
codes.push(u32::from(code), c.filter(|c| !c.is_control()));
}
let widths: Option<Vec<f64>> = plain.map(|(_, glyphs)| glyphs.iter().map(|g| g.width).collect());
self.show_codes(&codes, widths.as_deref(), spacing, false, s, Draw::Fill)
self.show_codes(&codes, widths.as_deref().map(|of| Widths { of, kept }), spacing, false, s, Draw::Fill)
}
/// The glyphs of codes `glyphs` in font program `data` (the current font's) gathered for the
/// font kept from the file for their family and style, when that family isn't available and
/// the type shows: `Some(true)` gathered, `Some(false)` a character's glyph differs from the
/// one that font has for it, `None` not kept (the family is available, the type draws nothing
/// or is drawn apart, or a glyph can't be read).
fn keep_file_glyphs(&mut self, data: &Embedded, glyphs: &[Plain]) -> Res<Option<bool>> {
if self.g.paint.is_none() || self.g.null || self.out.apart > 0 {
return Ok(None);
}
let (name, _) = self.font()?;
let (family, style) = family_style(&name);
if family.is_empty() || vectorcraft_text::FontDb::global().find_family(&family).is_some() {
return Ok(None);
}
let mut file = Vec::with_capacity(glyphs.len());
for g in glyphs {
let Some(ch) = g.ch.filter(|c| !c.is_control()) else { continue };
let Some((outline, advance)) = data.glyph(g.gid) else { return Ok(None) };
self.spend(data.take_work())?;
// Ems, y up, onto thousandths of an em.
file.push(FileGlyph { ch, outline: Affine::scale(1000.0) * outline, advance: advance * 1000.0 });
}
if file.is_empty() {
return Ok(None);
}
let postscript = match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest.to_string(),
_ => name.clone(),
};
let (fs_type, metrics) = data.facts();
let (ascent, descent) = metrics.unwrap_or_default();
let info = || FileFontInfo { family: family.clone(), style: style.clone(), postscript, ascent, descent, fs_type };
let font = self.out.file_glyphs.font(&family, &style, info);
if !self.out.file_glyphs.fits(font, &file) {
return Ok(Some(false));
}
for g in file {
self.out.file_glyphs.add(font, g);
}
Ok(Some(true))
}
/// The codes `codes` (each standing for some of its characters, or none) shown in the current
@@ -698,12 +751,14 @@ impl Interp<'_> {
fn show_codes<C: Copy + Into<i64>>(
&mut self,
codes: &Decoded,
widths: Option<&[f64]>,
widths: Option<Widths>,
spacing: &Spacing,
vertical: bool,
kern: &[C],
draw: Draw,
) -> Res {
let kept = widths.is_some_and(|w| w.kept);
let widths = widths.map(|w| w.of);
let at = self.user_point()?;
let (_, f1) = self.font()?;
let text = &codes.text;
@@ -717,6 +772,17 @@ impl Interp<'_> {
*n += g.advance;
}
}
if kept && let Some(widths) = widths {
let mut k = 0;
for (i, &(_, n)) in codes.codes.iter().enumerate() {
if n == 1
&& let Some(slot) = natural.get_mut(k)
{
*slot = widths.get(i).copied().unwrap_or(0.0) * size;
}
k += n;
}
}
// Each code's move (user space) and that move in text space, along the baseline (down the
// column) and across.
let em = |x: f64| f1 * if vertical { Point::new(0.0, -x) } else { Point::new(x, 0.0) } - f1 * Point::ZERO;
@@ -757,10 +823,13 @@ impl Interp<'_> {
for ((d, ..), &(_, n)) in moves.iter().zip(&codes.codes) {
let c: String = chars.by_ref().take(n).collect();
if painted && !c.trim().is_empty() {
let (t, ..) = self.set_text_in(&c, pen, vertical)?;
let (mut t, ..) = self.set_text_in(&c, pen, vertical)?;
if draw == Draw::Path {
self.type_path(&t)?;
} else {
if kept {
super::file_fonts::mark(&mut t);
}
let clips = self.g.clips.clone();
self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips);
}
@@ -814,6 +883,9 @@ impl Interp<'_> {
if draw == Draw::Path {
self.type_path(&t)?;
} else {
if kept {
super::file_fonts::mark(&mut t);
}
let clips = self.g.clips.clone();
if self.out.push(Node::new(NodeId(0), NodeKind::Text(Box::new(t))), &clips).is_some()
&& let Some(after) = self.out.drawn.get_mut(start..)
@@ -1328,7 +1400,7 @@ impl Interp<'_> {
};
let saved = self.g.font.replace(named.font.clone());
let before = std::mem::replace(&mut self.kshow_font, saved.clone());
let r = self.show_codes(&named.codes, widths.as_deref(), spacing, named.vertical, &kern, draw);
let r = self.show_codes(&named.codes, widths.as_deref().map(|of| Widths { of, kept: false }), spacing, named.vertical, &kern, draw);
self.kshow_font = before;
self.g.font = saved;
r
@@ -1675,6 +1747,15 @@ impl Interp<'_> {
}
}
/// The widths of the codes [`Interp::show_codes`] shows (glyph space, one unit an em). With
/// `kept`, the type is drawn in a font kept from the file whose glyphs are that wide (see
/// `file_fonts`), so they are its characters' advances, not the layout's.
#[derive(Clone, Copy)]
struct Widths<'a> {
of: &'a [f64],
kept: bool,
}
/// A character code of a font carrying its program: the character it stands for (`None` when
/// neither its glyph name nor the font says), its glyph and the glyph's width (ems).
struct Plain {
+15
View File
@@ -51,6 +51,21 @@ impl Embedded {
}
}
/// What the font program says of its licence (OS/2 `fsType`) and its ascent and descent
/// (thousandths of an em, the descent negative): a TrueType font's tables. A Type 1 font
/// says neither.
pub fn facts(&self) -> (Option<u16>, Option<(f64, f64)>) {
use skrifa::MetadataProvider;
use skrifa::raw::TableProvider;
let Self::TrueType(f) = self else { return (None, None) };
let Ok(font) = skrifa::FontRef::new(&f.data) else { return (None, None) };
let fs_type = font.os2().ok().map(|o| o.fs_type());
let m = font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
let k = 1000.0 / f64::from(m.units_per_em.max(1));
let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k);
(fs_type, (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent)))
}
/// The character glyph `gid` stands for, when the font says (a TrueType font's character
/// map or `post` names; a Type 1 glyph's name).
pub fn char_of(&self, gid: u32) -> Option<char> {
+53
View File
@@ -444,6 +444,59 @@ impl SubPath {
}
true
}
/// Bend segment `seg` as the arrow keys do: its anchors stay and its handles go where
/// [`Self::nudged_handles`] puts them. A handle that keeps its direction leaves a smooth anchor
/// smooth; one that flips or grows out of its anchor makes it a corner, so the segment beside
/// it stays as it is. False, with nothing changed, when the bend changes nothing.
pub fn nudge_segment(&mut self, seg: usize, dv: kurbo::Vec2) -> bool {
let Some((h_out, h_in)) = self.nudged_handles(seg, dv) else { return false };
let n = self.anchors.len();
// Turned when the new handle doesn't point the way the old one did.
let turned = |a: &Anchor, old: Point, new: Point| (old - a.p).dot(new - a.p) <= 0.0;
if let Some(a) = self.anchors.get_mut(seg % n)
&& h_out != a.h_out
{
let independent = turned(a, a.h_out, h_out);
a.set_handle(true, h_out, independent);
}
if let Some(b) = self.anchors.get_mut((seg + 1) % n)
&& h_in != b.h_in
{
let independent = turned(b, b.h_in, h_in);
b.set_handle(false, h_in, independent);
}
true
}
/// The outgoing handle at the start and the incoming one at the end that segment `seg` gets
/// from the arrow keys' step `dv`. Each handle keeps its direction and changes length in
/// proportion to `dv` projected onto that direction, so the curve bulges toward `dv`: the
/// middle of the curve moves by `dv`'s length along `dv`, or less when the handles point
/// mostly across it. A handle can shrink through its anchor and come out the other way. A
/// retracted handle takes the direction from its anchor to the other handle's end. `None` when
/// there is no such segment, it is a straight line, or both handles are at right angles to
/// `dv`, so nothing changes.
pub fn nudged_handles(&self, seg: usize, dv: kurbo::Vec2) -> Option<(Point, Point)> {
if seg >= self.segment_count() || self.segment_is_line(seg) {
return None;
}
let c = self.segment(seg);
let direction = |anchor: Point, handle: Point, other: Point| {
let dir = if handle.distance(anchor) > EPS { handle - anchor } else { other - anchor };
let len = dir.hypot();
if len > EPS { dir / len } else { kurbo::Vec2::ZERO }
};
let (u0, u1) = (direction(c.p0, c.p1, c.p2), direction(c.p3, c.p2, c.p1));
let (d0, d1) = (dv.dot(u0), dv.dot(u1));
// Handles that change by k·d0 and k·d1 move the middle B(1/2) by 3/8·k·(d0·u0 + d1·u1),
// whose part along dv is 3/8·k·(d0² + d1²)/|dv|: one |dv| for k = 8/3·|dv|²/(d0² + d1²),
// kept to at most 8/3 so that handles nearly across dv don't grow without bound.
let sum = d0 * d0 + d1 * d1;
if sum <= EPS * EPS {
return None;
}
let k = 8.0 / 3.0 * (dv.hypot2() / sum).min(1.0);
Some((c.p1 + u0 * (k * d0), c.p2 + u1 * (k * d1)))
}
/// Split segment `seg` at parameter `t`, inserting a new anchor. Returns the new anchor index.
pub fn insert_anchor(&mut self, seg: usize, t: f64) -> usize {
+8 -7
View File
@@ -293,7 +293,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return };
let n = callee.text;
if is(h1, ".") {
let file = self.file_receiver(h2, h3);
let held = self.held_file(h2, h3);
// A Folder object whatever the path names has no File-only function: the call does not
// reach the file system.
if held == Some(true) && catalog::FILE_ONLY.contains(&n) {
return;
}
let file = held.is_some();
if n == catalog::MENU_COMMAND {
self.pending = Pending::Menu(line);
} else if n == catalog::OPEN && file {
@@ -329,12 +335,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
/// (not a property of the same name), or a File or Folder object made in place or held in
/// grouping parentheses ([`Sig::file`]).
fn file_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
self.held_file(receiver, before).is_some()
}
/// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names
/// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names
/// ([`Sig::folder`], [`Analyzer::folder`]), unless the file gives names values the analysis
/// doesn't read ([`Analyzer::unsure`]), `Some(false)` for an object that may be a File object, and
/// `None` for anything else.
+2
View File
@@ -38,6 +38,8 @@ pub(crate) const FILE_SETTERS: &[&str] = &["length", "hidden", "readonly"];
pub(crate) const FILE_DIALOGS: &[&str] = &["openDialog", "saveDialog"];
pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"];
pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"];
/// The functions of a File object that a Folder object does not have.
pub(crate) const FILE_ONLY: &[&str] = &["open", "read", "readch", "readln", "write", "writeln", "copy", "createAlias", "openDlg", "saveDlg"];
pub(crate) const FOLDER_PLACES: &[&str] =
&["appData", "appPackage", "commonFiles", "current", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"];
/// The `Folder` place a script can assign.
+26
View File
@@ -593,6 +593,32 @@ fn setting_a_folders_length_or_flags_does_not_write() {
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 9, 11, 13, 14, 15, 16][..]));
}
/// A Folder object has none of the File object's `open`, `read`, `readch`, `readln`, `write`,
/// `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, so calling them on `new Folder(…)`, a
/// `Folder` place or a variable holding one reads, writes and asks nothing. On `Folder(…)`, which
/// gives a File object when the path names a file, and on `Folder.current` they still count, and the
/// Folder object's own `create`, `remove`, `getFiles` and `selectDlg` count on any of them.
#[test]
fn file_only_calls_on_a_folder_do_nothing() {
let r = report(concat!(
"var d = new Folder(p);\n",
"d.write(s); d.writeln(s); d.copy(q); d.createAlias(q);\n",
"d.open('w'); d.read(); d.readch(); d.readln();\n",
"Folder.temp.write(s); (new Folder(q)).copy(q);\n",
"d.openDlg(); Folder.desktop.saveDlg();\n",
"Folder(p).write(s);\n",
"Folder.current.copy(q);\n",
"d.create(); d.getFiles(); d.selectDlg();\n",
"var g = Folder(p); g.open('r');\n",
));
let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default();
let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect();
assert_eq!(outside, [("filesWritten", &[6, 7, 8][..])]);
assert_eq!(lines("file.write"), [6, 7, 8]);
assert_eq!(lines("file.read"), [8, 9]);
assert_eq!(lines("file.dialog"), [8]);
}
/// A File object assigned to a function's own variable, its parameter or a `catch` block's
/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter
/// starts without what the outer variable of the same name was assigned.
+3
View File
@@ -284,6 +284,9 @@ pub struct ToolContext<'a> {
/// General → Double Click To Isolate: a double-click on a group with the Selection tool
/// isolates it.
pub double_click_isolate: bool,
/// General → Double-Click Adds Anchor Points: a plain double-click on a path segment with Direct
/// Selection adds an anchor there.
pub double_click_adds_anchor: bool,
/// Selection & Anchor Display → Command Click to Select Objects Behind: Cmd/Ctrl-click with the
/// Selection tool selects the object under the selected one, the next click the one under
/// that.
+28
View File
@@ -863,6 +863,31 @@ fn segment_at(cx: &ToolContext, id: NodeId, p: Point) -> Option<SegmentHit> {
Some(SegmentHit { si, seg, t, curved: a.has_out() || b.has_in() })
}
/// With General › Double-Click Adds Anchor Points on, a plain
/// double-click on a path segment adds an anchor there, the new anchor alone selected. The path is
/// the one whose stroke or outline a press at `p` hits, a clipping path included. An anchor or a
/// center point under the pointer comes first, so nothing is added (the caller has already given
/// way to the handles, mesh points and blend spine points a press takes first). The path's own
/// line must pass within the pick tolerance of `p`: a click on a wide stroke or on the drawn
/// outline of an effect farther from the path adds nothing.
fn add_anchor_at(cx: &ToolContext, ev: &PointerEvent, p: Point) -> Option<Action> {
let m = ev.mods;
if !cx.double_click_adds_anchor || m.shift || m.alt || m.cmd || m.ctrl {
return None;
}
let (tol, point) = (cx.pick_tol(), cx.point_tol());
if hit_anchor(cx, p, point).is_some() || hit_center(cx, p, point).is_some() {
return None;
}
let h = hit_test(cx.doc, p, cx.selection_hit_options()).filter(|h| matches!(h.kind, HitKind::Stroke | HitKind::Outline))?;
let id = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf);
if !cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })) {
return None;
}
let (id, si, seg, t) = crate::draw2::segment_in(cx, [id], p, tol)?;
Some(Action::Exec("path.insertAnchor".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t, "selectAnchor": true})))
}
impl Tool for DirectSelectionTool {
/// The pointer hovers nothing for the tool: no bracket is highlighted.
fn hover_ended(&mut self, _cx: &ToolContext) {
@@ -1484,6 +1509,9 @@ impl DirectSelectionTool {
if crate::rulerguide::guide_at(cx, p).is_some() {
return vec![];
}
if let Some(a) = add_anchor_at(cx, ev, p).filter(|_| !self.takes_point(cx, p)) {
return vec![a];
}
// A double-click edits what is drawn: not a clipping path's outline.
let hit = hit_test(cx.doc, p, cx.hit_options());
if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) {
+104
View File
@@ -1355,6 +1355,110 @@ fn a_double_click_outside_isolation_leaves_it() {
assert!(DirectSelectionTool::new(false).pointer(&cx(&d, &none, &p), &PointerEvent::new(PointerKind::DoubleClick, 700.0, 700.0)).is_empty());
}
/// The anchor a Direct Selection double-click at `at` adds: (path, subpath, segment, t).
fn double_click_adds(cx: &ToolContext, at: (f64, f64), mods: Mods) -> Option<(u64, usize, usize, f64)> {
let a = DirectSelectionTool::new(false).pointer(cx, &PointerEvent::new(PointerKind::DoubleClick, at.0, at.1).with_mods(mods));
a.iter().find_map(|a| match a {
Action::Exec(c, p) if c == "path.insertAnchor" => {
assert_eq!(p["selectAnchor"], true, "the new anchor is selected: {p}");
Some((p["id"].as_u64()?, p["subpath"].as_u64()? as usize, p["segment"].as_u64()? as usize, p["t"].as_f64()?))
}
_ => None,
})
}
/// With General › Double-Click Adds Anchor Points on, a plain
/// Direct Selection double-click on a segment of a selected or unselected path adds an anchor at
/// the clicked point. Off, Group Selection, a modifier, an anchor or the fill add none.
#[test]
fn with_the_preference_on_a_double_click_on_a_segment_adds_an_anchor_there() {
let (d, id) = doc_with_rect();
let p = paint();
let mut whole = Selection::default();
whole.add(id);
let none = Selection::default();
let top = d.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].clone()).unwrap_or_else(|| panic!("the rectangle"));
for sel in [&none, &whole] {
let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, sel, &p) };
let (path, si, seg, t) = double_click_adds(&on, (150.0, 101.0), Mods::default()).unwrap_or_else(|| panic!("an anchor is added"));
assert_eq!((path, si), (id.0, 0));
let c = top.segment(seg);
assert!(c.p0.y == 100.0 && c.p3.y == 100.0, "on the top edge: {c:?}");
let at = vectorcraft_geom::ParamCurve::eval(&c, t);
assert!(at.distance(Point::new(150.0, 100.0)) < 1e-6, "at the clicked point: {at:?}");
assert_eq!(double_click_adds(&on, (100.0, 100.0), Mods::default()), None, "on an anchor");
assert_eq!(double_click_adds(&on, (150.0, 150.0), Mods::default()), None, "in the middle of the fill");
for m in [Mods { shift: true, ..Mods::default() }, Mods { alt: true, ..Mods::default() }, Mods { cmd: true, ..Mods::default() }] {
assert_eq!(double_click_adds(&on, (150.0, 101.0), m), None, "with {m:?}");
}
let group = DirectSelectionTool::new(true).pointer(&on, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 101.0));
assert!(group.is_empty(), "Group Selection: {group:?}");
let off = cx(&d, sel, &p);
assert!(DirectSelectionTool::new(false).pointer(&off, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 101.0)).is_empty(), "off");
}
// On a 40 pt stroke 15 pt above the path, the stroke is hit but the path is out of reach.
let mut wide = d.clone();
if let Some(s) = wide.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
s.width = 40.0;
}
let on = ToolContext { double_click_adds_anchor: true, ..cx(&wide, &none, &p) };
assert!(hit_test(&wide, Point::new(150.0, 85.0), on.selection_hit_options()).is_some_and(|h| matches!(h.kind, HitKind::Stroke)));
assert_eq!(double_click_adds(&on, (150.0, 85.0), Mods::default()), None, "away from the path");
assert!(double_click_adds(&on, (150.0, 101.0), Mods::default()).is_some(), "on the path");
// Without a stroke, the edge is taken within the tolerance, and the fill just past it is not.
let mut unstroked = d.clone();
if let Some(n) = unstroked.node_mut(id) {
n.appearance.set_stroke(vectorcraft_color::Paint::None);
}
let on = ToolContext { double_click_adds_anchor: true, ..cx(&unstroked, &none, &p) };
assert!(double_click_adds(&on, (150.0, 101.0), Mods::default()).is_some(), "on the edge of the fill");
assert!(hit_test(&unstroked, Point::new(150.0, 104.0), on.selection_hit_options()).is_some_and(|h| matches!(h.kind, HitKind::Fill)));
assert_eq!(double_click_adds(&on, (150.0, 104.0), Mods::default()), None, "on the fill past the tolerance");
}
/// With the preference on, a double-click on a segment of a path in a group adds the anchor to
/// that path; on the group's fill it does what it did before (nothing), and outside isolated art it
/// still leaves isolation mode.
#[test]
fn with_the_preference_on_a_double_click_in_a_group_adds_only_on_a_segment() {
let (d, inside, outside, inner, _) = nested_group_doc();
let p = paint();
let none = Selection::default();
let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) };
assert_eq!(double_click_adds(&on, (150.0, 101.0), Mods::default()).map(|a| a.0), Some(inside.0));
assert_eq!(double_click_adds(&on, (350.0, 301.0), Mods::default()).map(|a| a.0), Some(outside.0));
assert!(DirectSelectionTool::new(false).pointer(&on, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0)).is_empty(), "the fill");
let isolated = ToolContext { isolation: Some(inner), ..on };
assert_eq!(double_click_adds(&isolated, (150.0, 101.0), Mods::default()).map(|a| a.0), Some(inside.0), "isolated art");
let exit = vec![Action::Exec("object.exitIsolation".into(), json!({}))];
assert_eq!(DirectSelectionTool::new(false).pointer(&isolated, &PointerEvent::new(PointerKind::DoubleClick, 350.0, 301.0)), exit);
}
/// With the preference on, a double-click on a blend's spine point, which a press takes before the
/// path under it, adds no anchor to that path; on the same path away from the spine point it does.
/// A clipping path's segment, which a press takes over the art it clips, gets the anchor.
#[test]
fn with_the_preference_on_a_double_click_gives_way_to_spine_points_and_reaches_clipping_paths() {
let (mut d, _) = doc_with_rect();
let l = d.layers[0].id;
let key = |id: NodeId, x: f64| {
let line = vectorcraft_geom::shapes::line(Point::new(x, 310.0), Point::new(x + 40.0, 310.0));
std::sync::Arc::new(vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art()))
};
let (g, k1, k2) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
let b = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, 100.0), key(k2, 200.0)], spec: Default::default() });
d.insert(Some(l), 1, b).unwrap();
let p = paint();
let none = Selection::default();
let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) };
assert_eq!(double_click_adds(&on, (130.0, 310.0), Mods::default()).map(|a| a.0), Some(k1.0), "on the line");
assert_eq!(double_click_adds(&on, (120.0, 310.0), Mods::default()), None, "on the spine point at its center");
let (d, _, clip, _) = doc_with_masked_square();
let on = ToolContext { double_click_adds_anchor: true, ..cx(&d, &none, &p) };
assert_eq!(double_click_adds(&on, (500.0, 450.0), Mods::default()).map(|a| a.0), Some(clip.0), "on the clipping path");
}
/// With Direct Selection, an Alt-click on a path selected whole adds its group on release, and
/// each further Alt-click adds the next group up, as Group Selection's clicks do, on an anchor,
/// a segment and the fill alike. The climb stops below the layer and at the isolated group.
+26 -5
View File
@@ -1561,6 +1561,26 @@ impl GestureTool {
v
}
/// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that
/// redraws a selected path is shown as it is drawn, joined at its start to the point of the
/// path nearest to it, with no fill, and leaves the path and the selection as they are: where
/// the stroke ends is only known at the release, which redraws the path (`finish`).
fn drawing_params(&self, cx: &ToolContext) -> Value {
let mut v = self.freehand_params(cx, false);
let Some((id, _)) = self.redraw else { return v };
if let Some(o) = v.as_object_mut() {
o.remove("redraw");
}
v["fill"] = json!(false);
v["keepSelected"] = json!(false);
v["leaveSelection"] = json!(true);
let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3);
if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) {
pts.insert(0, json!([on.x, on.y]));
}
v
}
fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec<Action> {
let pts = &self.points;
let has_sel = !cx.selection.is_empty();
@@ -1764,7 +1784,7 @@ impl Tool for GestureTool {
}
// With the Pencil's Live preview off a thin line shows instead (`overlays`).
if self.previews() && crate::previews_at(self.points.len()) {
let mut v = self.freehand_params(cx, false);
let mut v = self.drawing_params(cx);
let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX);
v["fidelity"] = json!(fit_tolerance(cx, fidelity));
// A preview fitted coarser than the stroke kept is stale (`deactivate`).
@@ -1883,10 +1903,11 @@ impl Tool for GestureTool {
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
let began = self.began;
self.tip_at = None;
// Drags past the last preview are in the stroke kept, too, and with Live curve fitting
// off the stroke kept is fitted.
let stale = (began && (self.previewed != self.points.len() || !self.live_fit) && self.draws_path() && !self.smoothing)
.then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false)));
// Drags past the last preview are in the stroke kept, too, with Live curve fitting off the
// stroke kept is fitted, and a stroke that redraws a path redraws it (`drawing_params`).
let stale =
(began && (self.previewed != self.points.len() || !self.live_fit || self.redraw.is_some()) && self.draws_path() && !self.smoothing)
.then(|| Action::Preview("path.freehand".into(), self.freehand_params(cx, false)));
self.snap.clear();
self.active = false;
self.near_start = false;
+38
View File
@@ -856,6 +856,44 @@ fn pencil_shows_the_straight_line_cursor_when_a_press_draws_a_line() {
assert_eq!(Cursor::PencilStraight.precise(), Cursor::Crosshair, "Use Precise Cursors");
}
/// While a stroke that redraws a selected path is drawn, its previews show the stroke as drawn,
/// joined at its start to the path, unfilled, and leave the path and the selection as they are;
/// the release (or a switch of tool mid-stroke) redraws the path.
#[test]
fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() {
let (mut d, _) = doc_with_rect();
let l = d.layers[0].id;
let id = d.alloc_id();
let line = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![
vectorcraft_geom::PathEl::MoveTo(Point::new(300.0, 300.0)),
vectorcraft_geom::PathEl::LineTo(Point::new(400.0, 300.0)),
]));
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, line, vectorcraft_doc::Appearance::default_art())).unwrap();
let mut s = Selection::default();
s.set([id]);
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.smart_guides = false;
let mut t = GestureTool::new("pencil");
t.set_option("fill", &json!(true));
// Out from the path and back onto it: within Edit selected paths within all the way.
let acts = drag(&mut t, &cx, &[(350.0, 304.0), (352.0, 308.0), (356.0, 309.0), (360.0, 303.0)], Mods::default());
let (release, drawing) = acts.split_last().unwrap();
let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect();
assert!(!previews.is_empty(), "{acts:?}");
for v in previews {
assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}");
assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}");
assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}");
}
assert!(matches!(release.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0 && v["fill"] == true), "{release:?}");
// A switch of tool mid-stroke keeps the redraw too.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 350.0, 304.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 352.0, 320.0));
let acts = t.deactivate(&cx);
assert!(matches!(acts.as_slice(), [Action::Preview(_, v), Action::Commit] if v["redraw"]["id"] == id.0), "{acts:?}");
}
/// Before a press, the Pencil shows its new-path cursor (the star) exactly when the press draws
/// a new path: over an end of a selected open path, which the stroke continues, and over a
/// selected path, which it redraws, it does not. With nothing selected, with Edit Selected Paths
+1
View File
@@ -653,6 +653,7 @@ pub(crate) mod testutil {
path_only: false,
type_path_only: false,
double_click_isolate: true,
double_click_adds_anchor: false,
select_behind: true,
highlight_anchors: true,
snap_tolerance: 2.0,
+20 -1
View File
@@ -31,6 +31,8 @@ pub const KIND: &str = "nearestSwatch";
/// The query that lists the matches, and how many of each colour's the dialog shows.
const FIND: &str = "addon.color.nearestSwatch";
const MATCHES: u64 = 3;
/// The rows the match list shows before it scrolls.
const LIST_ROWS: u16 = 12;
/// What the query read: the document and its revision, the library, Fill and Stroke. An answer
/// stands while these are what the dialog shows now.
@@ -155,7 +157,8 @@ fn body(ui: &mut Ui, fields: &mut Fields, libraries: &[Entry<String>], selected:
let lines = lines(found);
let keys: Vec<usize> = (0..lines.len()).collect();
let source = keyed(&keys, |i| *i);
List::<usize>::new(label(tl!("Find Nearest Swatch"))).select(SelectMode::None).show_items(ui, &source, &mut |&i, item| match lines.get(i) {
let list = List::<usize>::new(label(tl!("Find Nearest Swatch"))).select(SelectMode::None).max_rows(LIST_ROWS);
list.show_items(ui, &source, &mut |&i, item| match lines.get(i) {
Some(line) => {
let face = SwatchFace::new(line.color);
let row = ListRow::new(line.text.clone())
@@ -267,4 +270,20 @@ mod tests {
assert!(!host(&app, |h| h.confirm_by_id(&ctx, id)), "Apply is off");
assert!(host(&app, |h| h.is_open::<NearestDialog>()));
}
#[test]
fn find_nearest_swatch_draws_its_matches_and_buttons() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": "Brand", "color": "#ff8000", "global": true})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#ff8010"})).unwrap();
let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
menus::invoke(&mut p.app(), COMMAND, serde_json::Value::Null);
p.frame();
p.frame();
for name in ["Brand", "Apply", "Cancel"] {
assert!(p.shows(name), "{name} is drawn");
}
}
}
+3
View File
@@ -33,6 +33,8 @@ pub const COMMAND: &str = "addon.select.byArtboards";
pub const KIND: &str = "selectByArtboards";
/// The relations the dialog offers: (value, label).
const RELATIONS: [(&str, &str); 3] = [("overlap", "Overlapping"), ("inside", "Fully Inside"), ("outside", "Fully Outside")];
/// The rows the artboard list shows before it scrolls.
const LIST_ROWS: u16 = 9;
/// Object › Plug-ins › Selection Tools.
pub fn menu() -> Vec<Node> {
@@ -170,6 +172,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut
.allow_empty(true)
.activate(ActivateOn::DoubleClick)
.empty(label(tl!("No artboards match.")))
.max_rows(LIST_ROWS)
.selection(Bind::bound(&mut selection))
.show_items(ui, &source, &mut |&i, item| match rows.get(i) {
Some((name, size)) => {
@@ -46,6 +46,8 @@ pub const STATUSES: [(&str, &str, &str); 4] = [
];
/// The dialog's Show choices: (value, label).
const SHOW: [(&str, &str); 5] = [("all", "All"), ("linked", "Linked"), ("embedded", "Embedded"), ("missing", "Missing"), ("modified", "Modified")];
/// The rows the image table shows before it scrolls.
const LIST_ROWS: u16 = 9;
/// How often the statuses are looked at again while the document stays as it is (s): files
/// change on disk without the document knowing.
const RECHECK: f64 = 2.0;
@@ -317,6 +319,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) {
let out = Table::<u64>::new(label(tl!("Select by Link Status")), columns)
.select(SelectMode::None)
.empty(label(tl!("No images match.")))
.max_rows(LIST_ROWS)
.show_items(ui, &source, &mut |id, item| match lines.iter().find(|line| line.id == *id) {
Some(line) => ListRow::new(line.name.clone())
.cells(item.cells())
@@ -197,6 +197,18 @@ fn links_inside_a_symbol_are_left_out_of_selecting_by_status() {
assert_eq!(host(&app, |h| h.get::<LinkStatusDialog>().map(|d| d.rows.len())), Some(0), "the dialog lists no row of the symbol");
}
#[test]
fn the_dialog_draws_its_images_and_buttons() {
let dir = Folder::new("drawn");
let (app, ..) = app(&dir);
let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
menus::invoke(&mut p.app(), COMMAND, Value::Null);
p.frame();
for name in ["river.png", "harbour.png", "Select", "Cancel"] {
assert!(p.shows(name), "{name} is drawn");
}
}
#[test]
fn the_dialog_lists_filters_and_selects_with_zoom() {
let dir = Folder::new("dialog");
+11
View File
@@ -87,6 +87,17 @@ fn select_by_artboards_opens_on_the_active_artboard_and_selects_on_ok() {
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
}
#[test]
fn select_by_artboards_draws_its_artboards_and_buttons() {
let (app, _) = banner();
let mut p = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
menus::invoke(&mut p.app(), COMMAND, Value::Null);
p.frame();
for name in ["Banner", "Select All", "OK", "Cancel"] {
assert!(p.shows(name), "{name} is drawn");
}
}
#[test]
fn a_search_keeps_the_choice_it_hides_and_a_double_click_fits_its_artboard() {
// Boards 0 and 1 chosen, the search shows 0 and 2: picking row 2 leaves hidden board 1 chosen and drops shown board 0.
+12 -15
View File
@@ -349,22 +349,19 @@ impl BulletsDialog {
fn preset_row(ui: &mut Ui, label: &'static str, presets: &[Preset], current: Option<usize>) -> Option<usize> {
let mut selection = current.map_or_else(Selection::default, Selection::single);
let source = keyed(presets, |p: &Preset| p.at);
let _ = TileGrid::new(label).select(SelectMode::Single).caption(CaptionPlace::None).selection(Bind::bound(&mut selection)).show_items(
ui,
&source,
&mut |at, _| {
let Some(preset) = presets.get(*at) else { return Tile::new(String::new()) };
let face = preset.face.clone();
Tile::new(preset.name.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| {
cx.with_draw(|draw| match &face {
Face::Glyph(glyph) => draw.icon(rect, &IconSpec::glyph(*glyph)),
Face::Text(text) => {
let _ = draw.text(rect, &TextRun::new(text.as_str()).align(HAlign::Center));
}
})
let grid = TileGrid::new(label).select(SelectMode::Single).caption(CaptionPlace::None).natural_height(true);
let _ = grid.selection(Bind::bound(&mut selection)).show_items(ui, &source, &mut |at, _| {
let Some(preset) = presets.get(*at) else { return Tile::new(String::new()) };
let face = preset.face.clone();
Tile::new(preset.name.clone()).thumb(ThumbAspect::SQUARE, move |cx, rect| {
cx.with_draw(|draw| match &face {
Face::Glyph(glyph) => draw.icon(rect, &IconSpec::glyph(*glyph)),
Face::Text(text) => {
let _ = draw.text(rect, &TextRun::new(text.as_str()).align(HAlign::Center));
}
})
},
);
})
});
selection.lead.filter(|at| Some(*at) != current)
}
@@ -4,9 +4,11 @@
//! Each field is unset (empty, absent, or a checkbox in its unset state) or set, and an unset field leaves
//! its attribute out of the style. A field still as it opened keeps the style's stored value as it is.
use std::ops::RangeInclusive;
use std::sync::Arc;
use craft::behavior::Mixed;
use craft::text::ui::character::{AKI_PRESETS, DIACRITIC_PRESETS, TSUME_PRESETS};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Entry, Outcome as _, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogResult, FieldRefusal};
@@ -15,7 +17,8 @@ use craft::ui::patterns::form_dialogs::{
DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesDialog, PropertiesTab, PropertyRow, TabLayout,
};
use craft::ui::pickers::Select;
use craft::ui::runtime::env::Label;
use craft::ui::runtime::env::{Env, Label};
use craft::ui::text::{NumberField, NumberPick};
use serde_json::{Map, Value, json};
use vectorcraft_doc::setup::DocSetup;
@@ -429,6 +432,23 @@ fn case_from_attrs(attrs: &Map<String, Value>) -> Option<&'static str> {
}
}
/// The number the text typed into number field `key` reads as, with the arithmetic of the app's number
/// fields (`6x2`, `10+4`, `200/2`) and a decimal comma: a length in points in the length fields (`1 in`),
/// and a final `%` in the percent fields or `°` in Character Rotation.
fn typed_number(key: &str, text: &str) -> Option<f64> {
let text = text.trim().replace('\u{2212}', "-");
let text = vectorcraft_doc::decimal_point(&text);
let mark = match key {
"size" | "leading" | "baseline_shift" | "tcyUpDown" | "tcyLeftRight" | "stroke_width" => {
return vectorcraft_doc::Unit::Points.parse(&text);
}
"h_scale" | "v_scale" | "tsume" | "fill_tint" | "stroke_tint" => Some('%'),
"rotation" => Some('°'),
_ => None,
};
vectorcraft_doc::parse_number(mark.and_then(|m| text.strip_suffix(m)).unwrap_or(&text))
}
fn optional_number(d: &Values, key: &str) -> Result<Option<Value>, String> {
let label = match key {
"size" => tl!("Size"),
@@ -458,7 +478,7 @@ fn optional_number(d: &Values, key: &str) -> Result<Option<Value>, String> {
Some(v) => {
let n = v
.as_f64()
.or_else(|| v.as_str().and_then(|s| s.trim().parse::<f64>().ok()))
.or_else(|| v.as_str().and_then(|s| typed_number(key, s)))
.filter(|n| n.is_finite())
.ok_or_else(|| format!("{label} must be a number"))?;
// Character Style fields use the Character panel's visible ranges.
@@ -898,7 +918,39 @@ fn basic_rows() -> Vec<PropertyRow> {
])
}
// PLAN: the Aki, Tsume and Diacritic rows are plain text rows: `Param::text` has no preset menu to carry the Character panel's presets.
/// A number row over the text field `key` (empty for unset) whose menu offers `presets`, as the Character panel's field
/// of the same name does. A typed value stays within `range`; automation sets the field's text, as for a text row.
fn preset_number(key: &'static str, label: String, range: RangeInclusive<f64>, presets: &'static [f32]) -> Param {
let name = label.clone();
Param::custom(key, label, move |ui, fields, _| {
let value = fields.text(key).and_then(|text| text.trim().parse::<f64>().ok()).filter(|n| n.is_finite());
let units = Env::of(ui).units();
let rows: Vec<Entry<NumberPick>> = presets
.iter()
.map(|&p| {
let n = f64::from(p);
Entry::new(NumberPick::Number(n), units.number(n, 0..=2))
})
.collect();
let out = NumberField::new(name.clone(), Bind::given(value)).range(range.clone()).presets(&rows).id_salt(key).show(ui);
if let Some(picked) = out.edit.value() {
let text = picked.map(|n| n.to_string()).unwrap_or_default();
if fields.text(key) != Some(text.as_str()) {
fields.set(key, FieldValue::Text(text));
}
}
out.edit.response.clone()
})
// Set from outside: the field's text, as a text row takes it.
.on_set(|fields, key, value| match value {
Value::String(text) => {
fields.set(key, FieldValue::Text(text));
Ok(())
}
other => Err(FieldRefusal::Rejects(&other).message(key)),
})
}
fn advanced_rows() -> Vec<PropertyRow> {
let mut params: Vec<Param> = [
("h_scale", tl!("Horizontal Scale"), "%"),
@@ -907,15 +959,20 @@ fn advanced_rows() -> Vec<PropertyRow> {
("tcyUpDown", tl!("Tate-chu-yoko Up/Down"), "pt"),
("tcyLeftRight", tl!("Tate-chu-yoko Left/Right"), "pt"),
("rotation", tl!("Character Rotation"), "°"),
("akiLeft", tl!("Insert Aki Left"), ""),
("akiRight", tl!("Insert Aki Right"), ""),
("tsume", tl!("Tsume"), "%"),
("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position"), ""),
("diacriticVertical", tl!("Adjust Vertical Diacritic Position"), ""),
]
.into_iter()
.map(|(key, caption, unit)| text(key, if unit.is_empty() { caption.to_string() } else { format!("{caption} ({unit})") }))
.map(|(key, caption, unit)| text(key, format!("{caption} ({unit})")))
.collect();
let aki = 0.0..=vectorcraft_doc::text::MAX_AKI;
let tsume = 0.0..=vectorcraft_doc::text::MAX_TSUME;
let diacritic = -vectorcraft_doc::text::MAX_DIACRITIC_POSITION..=vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
params.extend([
preset_number("akiLeft", tl!("Insert Aki Left").to_string(), aki.clone(), &AKI_PRESETS),
preset_number("akiRight", tl!("Insert Aki Right").to_string(), aki, &AKI_PRESETS),
preset_number("tsume", format!("{} (%)", tl!("Tsume")), tsume, &TSUME_PRESETS),
preset_number("diacriticHorizontal", tl!("Adjust Horizontal Diacritic Position").to_string(), diacritic.clone(), &DIACRITIC_PRESETS),
preset_number("diacriticVertical", tl!("Adjust Vertical Diacritic Position").to_string(), diacritic, &DIACRITIC_PRESETS),
]);
let languages: Vec<(&'static str, &'static str)> = vectorcraft_doc::setup::LANGUAGES.iter().map(|(name, _, _)| (*name, *name)).collect();
params.push(select("language", tl!("Language:"), &languages));
rows(params)
@@ -515,6 +515,33 @@ fn diacritic_position_fields_show_set_reset_and_commit() {
assert!(t.runs.iter().all(|r| (r.style.diacritic_horizontal, r.style.diacritic_vertical) == (-120.0, 1000.0)));
}
/// The number fields read typed text as the app's other number fields do: `6x2`, `10+4`, `200/2%`,
/// `45°`, a decimal comma, and a length with its unit. `%` and `°` only where the field takes them,
/// and an exponent is not read.
#[test]
fn number_fields_take_field_arithmetic() {
let typed = [
("size", "6x2", 12.0),
("tracking", "10+4", 14.0),
("h_scale", "200/2%", 100.0),
("rotation", "45°", 45.0),
("fill_tint", "25*2", 50.0),
("leading", "1 in", 72.0),
("baseline_shift", "\u{2212}2", -2.0),
("kerning", "12,5", 12.5),
];
for (key, text, want) in typed {
let (mut d, _) = dialog_for(json!({}));
put(&mut d, key, json!(text));
assert_eq!(optional_number(&Values::new(&d), key), Ok(Some(json!(want))), "{key} {text}");
}
for (key, text) in [("size", "12°"), ("leading", "50%"), ("tracking", "10%"), ("rotation", "45%"), ("h_scale", "1%2"), ("size", "1e3")] {
let (mut d, _) = dialog_for(json!({}));
put(&mut d, key, json!(text));
assert!(optional_number(&Values::new(&d), key).is_err(), "{key} {text}");
}
}
/// Tsume: empty is unset, an explicit 0 stays set, a typed value stops at 0 and 100, Reset Panel
/// unsets it, and it commits to the style and the text set in it.
#[test]
@@ -523,7 +550,7 @@ fn tsume_field_shows_sets_resets_and_commits() {
assert_eq!(val(&d, "tsume"), json!(""));
let (mut d, o) = dialog_for(json!({"tsume": 50.0}));
assert_eq!(val(&d, "tsume"), json!("50.0"));
for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("150", 100.0), ("-5", 0.0)] {
for (typed, kept) in [("0", 0.0), ("25.5", 25.5), ("25%", 25.0), ("50/2%", 25.0), ("150", 100.0), ("-5", 0.0)] {
put(&mut d, "tsume", json!(typed));
assert_eq!(edited_attrs(&d, &o).unwrap(), attrs(json!({"tsume": kept})), "{typed}");
}
@@ -547,6 +574,41 @@ fn tsume_field_shows_sets_resets_and_commits() {
assert!(t.runs.iter().all(|r| r.style.tsume == 75.0));
}
/// The Insert Aki, Tsume and diacritic rows each have the Character panel's presets menu beside the field, and a
/// preset picked from it is the field's value and commits to the style, with each frame drawn once.
#[test]
fn aki_tsume_and_diacritic_rows_pick_from_the_character_panel_presets() {
use craft::ui::testing::Fixture;
let mut fx = Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui)));
fx.room(egui::vec2(900.0, 900.0));
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.ui_ctx = Some(fx.ctx().clone());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
styled(&mut app, json!({"size": 24.0}), "Text");
open(&mut app, "Body");
set::<Existing>(&app, "tab", json!("advanced"));
fx.settle();
let presets_in_row = |fx: &Fixture, label: &str| {
let field = fx.by_label(label).unwrap_or_else(|| panic!("the {label} field"));
let tree = fx.tree();
tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Presets")).filter_map(|key| fx.target(key)).find(|chevron| {
chevron.rect.center().y > field.rect.top() && chevron.rect.center().y < field.rect.bottom() && chevron.rect.left() >= field.rect.left()
})
};
for label in ["Insert Aki Left", "Insert Aki Right", "Tsume (%)", "Adjust Horizontal Diacritic Position", "Adjust Vertical Diacritic Position"] {
assert!(presets_in_row(&fx, label).is_some(), "{label} has a presets menu");
}
let chevron = presets_in_row(&fx, "Insert Aki Left").unwrap();
fx.click(&chevron).settle();
let pick = fx.by_label("500").expect("the 500 preset");
fx.click(&pick).settle();
assert_eq!(fields::<Existing>(&app)["akiLeft"], json!("500"));
assert!(ok::<Existing>(&mut app));
assert_eq!(app.session.doc().unwrap().doc.char_styles[0].attrs, attrs(json!({"size": 24.0, "akiLeft": 500.0})));
}
/// The negated tags of the twenty stylistic sets: an explicit empty Stylistic Sets choice.
fn no_sets() -> Vec<String> {
vectorcraft_text::EXTRA_FEATURES[..20].iter().map(|s| format!("-{s}")).collect()
+7 -2
View File
@@ -6,7 +6,8 @@
//! `artboard.setProps {index, color}`.
//!
//! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog
//! and answers the row with its OK.
//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's
//! colour in the table instead ([`super::save_for_web::take_palette_pick`]).
//!
//! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`,
//! `swatches`, `library`). `stroke`, `artboard` and `color` come from the opener.
@@ -253,7 +254,11 @@ fn finish(
) {
let preview = std::mem::take(&mut open.preview);
match (result, &open.target) {
(Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)),
(Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => {
if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) {
dialogs.with(|h| h.answer_color(*parent, key, r.picked.color));
}
}
(Some(DialogResult::Ok(r)), _) => {
if let Err(e) = commit(app, open, preview, &r.picked) {
app.status(e);
@@ -76,6 +76,8 @@ const IMPORT: &str = "type.compositeFonts.import";
/// The purpose of the file picks, which keeps their last folder.
const PURPOSE: &str = "compositeFonts";
/// The rows of a custom set's characters shown before they scroll.
const CHAR_ROWS: u16 = 5;
/// The table's columns: the class (or the custom set's name) is the row's label.
const CLASS: ColumnKey = ColumnKey::new("class");
@@ -656,6 +658,7 @@ impl CompositeFontsDialog {
let out = TileGrid::<usize>::new(tl!("Characters"))
.select(SelectMode::Single)
.thumb_size(ThumbSize::Small)
.max_rows(CHAR_ROWS)
.selection(Bind::given(selection))
.show_items(ui, &keyed(&keys, |k: &usize| *k), &mut |key, _| {
let c = chars.get(*key).copied().unwrap_or_default();
@@ -458,3 +458,19 @@ fn the_sample_draws_color_glyphs_in_their_colors() {
let (_, tall) = sample::measure(&f, 36.0);
assert!(tall.ascender.unwrap() > plain.ascender.unwrap() * 1.5, "{plain:?} {tall:?}");
}
/// With Custom on, the dialog draws the set's characters and its buttons.
#[test]
fn custom_character_sets_draw_their_characters_and_the_buttons() {
let mut p = crate::tests::panel_harness::Panel::new(app(), crate::tests::picks::dialogs);
open(&mut p.app()).unwrap();
new_font(&mut p.app());
dialog(&mut p.app(), |d| d.custom = true);
new_set(&mut p.app());
dialog(&mut p.app(), |d| d.entry = "AB".into());
edit(&mut p.app(), SetAction::AddChars).unwrap();
p.frame();
for name in ["A", "B", "OK", "Cancel"] {
assert!(p.shows(name), "{name} is drawn");
}
}
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more