Merge upstream main into PR #6593

This commit is contained in:
yoriswind committed 2026-11-14 18:19:06 -08:00
commit 6182fb161c
999 files changed
+161499 -13916

No files matched your search

+22 -22
View File
@@ -17,25 +17,25 @@ concurrency:
jobs:
affinity3:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
AFFINITY_CORPUS_REQUIRED: "1"
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_PROFILE_TEST_DEBUG: "0"
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: "1.95"
- name: Fetch pinned and checksum-verified corpus
run: cargo xtask corpus --affinity
- name: Parse every file and freeze actual Affinity 3 feature retention
run: cargo test -p vectorcraft-affinity --all-features -- --nocapture
- name: Check every artboard, native save, SVG, PDF and PSD exports
run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
timeout-minutes: 30
toolchain: "1.95"
# As before: no craft-fonts, apt packages, wasm target or nextest.
craft-fonts-ref: ""
targets: ""
tools: ""
dev-debug: "0"
env: |
AFFINITY_CORPUS_REQUIRED=1
CARGO_PROFILE_TEST_DEBUG=0
# Its own cache, apart from ci.yml's gate.
cache-version: v1-affinity
command: |
# Pinned and checksum-verified corpus.
cargo xtask corpus --affinity
# Parse every file and freeze actual Affinity 3 feature retention.
cargo test -p vectorcraft-affinity --all-features -- --nocapture
# Every artboard, native save, SVG, PDF and PSD export.
cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
+5
View File
@@ -31,3 +31,8 @@ jobs:
require-craft-fonts: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
run-package-check: true
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
# four jobs and again with two. One rustc at a time; it still uses every core.
cargo-build-extra-args: "-j 1"
cargo-test-extra-args: "-j 1"
+1 -43
View File
@@ -30,51 +30,9 @@ jobs:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
release:
needs: [git-sources, credits]
needs: credits
permissions:
contents: write
packages: write
+1 -1
View File
@@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
Generated
+114 -29
View File
@@ -978,11 +978,33 @@ dependencies = [
"ruzstd",
]
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-codepage",
"encoding_rs",
"kurbo 0.13.1",
"log",
"thiserror 2.0.21",
]
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1021,6 +1043,17 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"encoding_rs",
"image",
"kurbo 0.13.1",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -1057,6 +1090,21 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"craft-xml",
"flate2",
"kurbo 0.13.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
"vectorcraft-geom 0.18.0",
"vectorcraft-pathops 0.18.0",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1146,6 +1194,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -6340,8 +6397,8 @@ dependencies = [
"pollster 1.0.1",
"raw-window-handle",
"rfd",
"rustix 1.1.6",
"serde_json",
"smithay-clipboard",
"socket2",
"tempfile",
"vectorcraft-engine",
@@ -6387,13 +6444,14 @@ dependencies = [
"serde_json",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6401,8 +6459,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6419,7 +6477,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-mcp",
"vectorcraft-render",
"vectorcraft-svg",
@@ -6456,7 +6514,7 @@ dependencies = [
"thiserror 2.0.21",
"tiff",
"vectorcraft-color",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
]
@@ -6471,12 +6529,13 @@ dependencies = [
"svgtypes 0.16.1",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-trace",
"wat",
]
[[package]]
@@ -6515,10 +6574,10 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
@@ -6537,6 +6596,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-pdf",
"encoding_rs",
"fax",
@@ -6552,9 +6612,9 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-metafile",
"vectorcraft-pathops",
"vectorcraft-pathops 0.24.1",
"vectorcraft-pdf",
"vectorcraft-render",
"vectorcraft-testkit",
@@ -6573,10 +6633,20 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-geom"
version = "0.24.1"
@@ -6611,7 +6681,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
"vectorcraft-testkit",
@@ -6622,16 +6692,28 @@ dependencies = [
name = "vectorcraft-metafile"
version = "0.24.1"
dependencies = [
"craft-metafile",
"image",
"kurbo 0.13.1",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-text",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo 0.13.1",
"linesweeper",
"thiserror 2.0.21",
"vectorcraft-geom 0.18.0",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.24.1"
@@ -6640,7 +6722,7 @@ dependencies = [
"linesweeper",
"proptest",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
]
@@ -6665,6 +6747,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"siphasher",
"skrifa 0.47.0",
"smallvec",
"thiserror 2.0.21",
@@ -6672,7 +6755,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
@@ -6691,7 +6774,7 @@ dependencies = [
"thiserror 2.0.21",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"wasmi",
"wat",
"web-time",
@@ -6716,7 +6799,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-plugins",
"vectorcraft-testkit",
"vectorcraft-text",
@@ -6740,6 +6823,7 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
"craft-svg",
"flate2",
"image",
"kurbo 0.13.1",
@@ -6751,13 +6835,14 @@ dependencies = [
"skrifa 0.47.0",
"svgtypes 0.16.1",
"thiserror 2.0.21",
"unicode-bidi",
"usvg 0.48.1",
"vectorcraft-brush",
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
]
@@ -6775,7 +6860,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-engine",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-render",
"vectorcraft-svg",
]
@@ -6795,7 +6880,7 @@ dependencies = [
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vello_cpu",
"windows-registry",
"write-fonts",
@@ -6805,8 +6890,8 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
[[package]]
@@ -6821,8 +6906,8 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom",
"vectorcraft-pathops",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
]
@@ -6835,7 +6920,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
]
[[package]]
@@ -6864,7 +6949,7 @@ dependencies = [
"vectorcraft-engine",
"vectorcraft-eps",
"vectorcraft-format",
"vectorcraft-geom",
"vectorcraft-geom 0.24.1",
"vectorcraft-pdf",
"vectorcraft-plugins",
"vectorcraft-render",
+8
View File
@@ -25,6 +25,14 @@ craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", re
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
+11
View File
@@ -18,6 +18,8 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
## Headline numbers
| | Value | Kind |
@@ -96,6 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
| Spanish | `es` | full | 100% |
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -121,8 +124,12 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
@@ -141,6 +148,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
@@ -216,6 +224,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. |
@@ -224,6 +233,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 2026-11-03 | minor | Docked Tools stays between left-side panels and the canvas; redocking accepts canvas and window edges. Requested layout choice; scores and estimates unchanged. |
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
| 2026-11-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) |
| 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback; messages not yet translated; native review pending |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
+11 -3
View File
@@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
// Save as Template writes every artboard, with the .ai options.
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
} else {
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
// PSD).
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale, ppi);
// An option the format doesn't read comes back in the warnings, so each goes out only
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
// written hidden.
if outline_text {
params["outlineText"] = json!(true);
}
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
params["hiddenLayers"] = json!(true);
}
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
+21
View File
@@ -177,6 +177,27 @@ fn convert_reports_import_warnings() {
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
}
/// A conversion sends each format only the options it reads, so its warnings name an unused
/// option only when the command line gave one: `--outline-text` for a format without it.
#[test]
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
let svg = tmp("unused-option.svg");
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="20" height="10"/></svg>"#).unwrap();
let unused = |out: &Value| -> Vec<String> {
let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
};
for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
let path = tmp(&format!("unused-option.{ext}"));
let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{ext}: {out}");
}
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{out}");
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
}
#[test]
fn convert_writes_legacy_ai_with_its_options() {
// Two artboards, a shown rectangle and a hidden one.
+49 -4
View File
@@ -8,23 +8,40 @@
//! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none:
//! heartbeats alone decide there.
#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::collections::{BTreeMap, BTreeSet};
#[cfg(target_arch = "wasm32")]
use std::sync::{Arc, Mutex};
#[cfg(target_arch = "wasm32")]
use js_sys::{Function, Promise, Reflect};
#[cfg(target_arch = "wasm32")]
use vectorcraft_engine::cmd::recovery::Hold;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast as _;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::closure::Closure;
/// How often the snapshot of the locks held is refreshed (ms).
#[cfg(target_arch = "wasm32")]
const REFRESH_MS: i32 = 10_000;
/// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was
/// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under
/// that is safe; an older snapshot counts every area as held.
const FRESH_MS: f64 = 60_000.0;
/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on
/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later
/// than `now`.
fn trusted(asked: f64, now: f64) -> bool {
(0.0..=FRESH_MS).contains(&(now - asked))
}
#[cfg(target_arch = "wasm32")]
thread_local! {
/// What releases each lock this tab holds, by name: it resolves the promise the lock is held
/// by (wasm runs on one thread).
@@ -32,26 +49,31 @@ thread_local! {
}
/// The locks of the page, named `<prefix><area>`.
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct WebLocks {
prefix: &'static str,
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms since
/// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms on
/// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does
/// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// [`REFRESH_MS`] and read from here.
seen: Arc<Mutex<(f64, BTreeSet<String>)>>,
}
/// `navigator.locks`, if the browser has it here.
#[cfg(target_arch = "wasm32")]
fn manager() -> Option<JsValue> {
let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?;
locks.is_object().then_some(locks)
}
/// Method `name` of `obj`.
#[cfg(target_arch = "wasm32")]
fn method(obj: &JsValue, name: &str) -> Option<Function> {
Reflect::get(obj, &name.into()).ok()?.dyn_into().ok()
}
#[cfg(target_arch = "wasm32")]
impl WebLocks {
/// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when
/// the browser has none or won't say which are held (heartbeats alone decide then).
@@ -75,7 +97,7 @@ impl WebLocks {
/// Take a new snapshot of the locks held.
async fn refresh(&self) -> Option<()> {
let m = manager()?;
let asked = js_sys::Date::now();
let asked = vectorcraft_ui_egui::now_ms();
let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?;
let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?;
let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?);
@@ -91,7 +113,7 @@ impl WebLocks {
/// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell.
pub fn held(&self, area: &str) -> bool {
let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area)
!trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area)
}
/// Hold `area`'s lock until the returned hold is dropped (or the page goes).
@@ -110,8 +132,10 @@ impl WebLocks {
}
/// A lock this tab holds (by name), released when dropped.
#[cfg(target_arch = "wasm32")]
struct LockHold(String);
#[cfg(target_arch = "wasm32")]
impl Drop for LockHold {
fn drop(&mut self) {
if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) {
@@ -120,3 +144,24 @@ impl Drop for LockHold {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_is_trusted_for_a_minute() {
assert!(trusted(1_000.0, 1_000.0));
assert!(trusted(1_000.0, 1_000.0 + FRESH_MS));
assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS));
// Before the first snapshot every area counts as held.
assert!(!trusted(f64::NEG_INFINITY, 0.0));
}
#[test]
fn a_snapshot_stamped_later_than_now_is_not_trusted() {
// A clock that went back reads an old snapshot as taken in the future.
assert!(!trusted(5_000_000.0, 1_000.0));
assert!(!trusted(1_001.0, 1_000.0));
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ mod api;
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
mod keys;
#[cfg(target_arch = "wasm32")]
#[cfg(any(target_arch = "wasm32", test))]
mod locks;
#[cfg(any(target_arch = "wasm32", test))]
mod pencil;
+18 -10
View File
@@ -58,7 +58,10 @@ pollster = "1"
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
# display's color profile for the canvas.
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
@@ -93,29 +96,34 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
# RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs).
x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
# through winit.
wayland-client = "0.31"
# Copy and Paste of text through the compositor's core data-device protocol on the window's
# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
# on a Wayland session). MIT, already in the build through egui-winit.
smithay-clipboard = "0.7"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
futures-lite = "2"
# The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read
# or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR
# Apache-2.0 OR MIT, already in the build through the workspace.
rustix = { workspace = true, features = ["std", "event", "fs"] }
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
# exactly: review the diff before bumping.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
zbus = "=5.19.0"
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
# through zbus.
futures-lite = "2"
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
# arboard.
+7
View File
@@ -108,6 +108,10 @@ impl eframe::App for App {
self.app.start_pending_update();
#[cfg(target_os = "macos")]
super::mac_cursor::release();
// Dropping the app can wait for the clipboard handles to let go: the windows leave the
// screen first (`quit_windows`).
#[cfg(not(any(target_os = "macos", windows)))]
super::quit_windows::before_teardown(self.winit_window.as_deref());
end_before_teardown(self.frames);
}
}
@@ -192,6 +196,9 @@ impl App {
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
self.monitors_listed = Some((now, zoom));
}
if let Some(w) = &self.winit_window {
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
}
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
//! Reads the ICC profile of the display that shows most of the main window, for Preferences ›
//! Performance › Use Monitor Profile for Canvas, and hands it to [`DisplayProfile::report`].
//!
//! - Windows: the display's default profile for its standard color mode. A display with Advanced
//! Color on (HDR or Automatic Color Management) is converted by Windows, and nothing is read.
//! - X11: colord's profile for the RandR output, then the output's `_ICC_PROFILE` property, then
//! the screen's `_ICC_PROFILE` when only one output is active.
//! - Wayland, XWayland included: the compositor gives applications no display profile, and the
//! canvas stays sRGB.
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use vectorcraft_ui_egui::display_profile::{DisplayProfile, Found, Reading};
/// Seconds between two readings of the same display.
const EVERY: f64 = 10.0;
/// Seconds between two checks of which display shows the window.
const LOOK_EVERY: f64 = 1.0;
/// Starts the readings from the main window's frames.
#[derive(Default)]
pub(crate) struct Reader {
/// When the last reading started, and the display it was for.
last: Option<(f64, Option<String>)>,
/// When the window's display was last looked up.
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
struct Done(Arc<AtomicBool>);
impl Drop for Done {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
return;
}
self.last = Some((now, display.clone()));
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
ctx.request_repaint();
}
});
if let Err(e) = spawned {
log::warn!("couldn't start reading the display profile: {e}");
}
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
/// display, [`EVERY`] seconds later, or a clock that went back.
fn due(last: Option<&(f64, Option<String>)>, now: f64, display: Option<&str>) -> bool {
last.is_none_or(|(at, shown)| shown.as_deref() != display || !(*at..at + EVERY).contains(&now))
}
#[cfg(windows)]
fn read(display: Option<String>) -> Reading {
let found = win::read(display.as_deref());
Reading { display, found }
}
#[cfg(target_os = "linux")]
fn read(display: Option<String>) -> Reading {
let found = if wayland_session(|k| std::env::var_os(k)) {
Found::NoProfile("a Wayland session doesn't give applications the display's profile".into())
} else {
x11::read(display.as_deref())
};
Reading { display, found }
}
#[cfg(all(target_os = "macos", feature = "wgpu"))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::System("macOS converts the window to the display's profile".into()) }
}
#[cfg(not(any(windows, target_os = "linux", all(target_os = "macos", feature = "wgpu"))))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::NoProfile("this build doesn't read display profiles on this system".into()) }
}
/// Whether the app runs in a Wayland session, read from the environment `var` gives. XWayland
/// windows count: the variables stay set for them.
#[cfg(any(target_os = "linux", test))]
fn wayland_session(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|k| var(k).is_some_and(|v| !v.is_empty()))
}
/// The X11 reading from colord's answer `colord` (the profile file it names, read) and the X11
/// properties `properties`: colord's profile when its file can be read, otherwise the
/// properties' profile. When neither has one, the reason colord gave is kept.
#[cfg(any(target_os = "linux", test))]
fn x11_choice(colord: Option<Result<Option<Found>, String>>, properties: impl FnOnce() -> Result<Option<Found>, String>) -> Found {
let colord_reason = match colord {
Some(Ok(Some(found @ Found::Profile { .. }))) => return found,
Some(Ok(Some(Found::NoProfile(e) | Found::System(e)))) | Some(Err(e)) => Some(e),
Some(Ok(None)) | None => None,
};
match properties() {
Ok(Some(found)) => found,
Ok(None) => Found::NoProfile(match colord_reason {
Some(e) => format!("no profile is set for this display ({e})"),
None => "no profile is set for this display".into(),
}),
Err(e) => Found::NoProfile(e),
}
}
/// `found` when it is not a profile or the profile can be used, otherwise why it can't, so the
/// next source is tried.
#[cfg(any(target_os = "linux", test))]
fn usable(found: Found) -> Found {
match found {
Found::Profile { icc, from } => match vectorcraft_ui_egui::display_profile::check_profile(&icc) {
Ok(()) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(format!("{from}: {e}")),
},
other => other,
}
}
/// The ICC file at `path`, refused before it is read when it is larger than [`MAX_PROFILE_BYTES`].
///
/// [`MAX_PROFILE_BYTES`]: vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES
#[cfg(any(windows, target_os = "linux", test))]
fn read_icc(path: &std::path::Path) -> Result<Vec<u8>, String> {
use std::io::Read as _;
let max = vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES;
let too_large = || format!("{} is larger than {} MiB", path.display(), max >> 20);
let file = std::fs::File::open(path).map_err(|e| format!("couldn't open {}: {e}", path.display()))?;
let len = file.metadata().map_err(|e| format!("couldn't read {}: {e}", path.display()))?.len();
if len > max as u64 {
return Err(too_large());
}
let mut bytes = Vec::with_capacity(len as usize);
file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("couldn't read {}: {e}", path.display()))?;
if bytes.len() > max { Err(too_large()) } else { Ok(bytes) }
}
/// The file a profile `name` stands for: `name` itself when it is a path, otherwise the file of
/// that name in the system's color folder `dir`.
#[cfg(any(windows, test))]
fn profile_path(dir: Option<&std::path::Path>, name: &str) -> std::path::PathBuf {
match dir {
Some(dir) if !name.contains(['\\', '/']) => dir.join(name),
_ => std::path::PathBuf::from(name),
}
}
/// `path`'s profile, or why there is none.
#[cfg(any(windows, target_os = "linux"))]
fn profile_file(path: &std::path::Path) -> Found {
let from = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
match read_icc(path) {
Ok(icc) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(e),
}
}
#[cfg(windows)]
#[allow(unsafe_code)]
mod win {
use std::path::PathBuf;
use std::sync::OnceLock;
use vectorcraft_ui_egui::display_profile::Found;
use windows::Win32::Devices::Display::{
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig,
};
use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS, HLOCAL, LUID, LocalFree};
use windows::Win32::Graphics::Gdi::{CreateDCW, DeleteDC};
use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
use windows::Win32::UI::ColorSystem::{
CPST_STANDARD_DISPLAY_COLOR_MODE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER,
};
use windows::core::{HRESULT, PCWSTR, PWSTR, s, w};
/// `ColorProfileGetDisplayDefault` and `ColorProfileGetDisplayUserScope` (mscms.dll), which
/// older Windows versions don't have.
type GetDefault = unsafe extern "system" fn(i32, LUID, u32, i32, i32, *mut PWSTR) -> HRESULT;
type GetScope = unsafe extern "system" fn(LUID, u32, *mut i32) -> HRESULT;
/// The display path that shows a GDI device.
struct Path {
source: u32,
target_adapter: LUID,
target: u32,
}
pub(super) fn read(display: Option<&str>) -> Found {
let Some(device) = display else { return Found::NoProfile("Windows didn't name the window's display".into()) };
let path = match find_path(device) {
Ok(path) => path,
Err(e) => return Found::NoProfile(e),
};
if path.as_ref().is_some_and(advanced_color) {
return Found::System("Windows manages this display's colors (Advanced Color)".into());
}
let name = match path.as_ref().and_then(default_profile) {
Some(Ok(name)) => name,
Some(Err(e)) => return Found::NoProfile(e),
// Older Windows, or a display without an active path: GDI's profile for the device.
None => match icm_profile(device) {
Ok(name) => name,
Err(e) => return Found::NoProfile(e),
},
};
match name {
Some(name) => super::profile_file(&super::profile_path(color_directory().as_deref(), &name)),
None => Found::NoProfile("no color profile is set for this display".into()),
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
fn until_nul(w: &[u16]) -> String {
String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])
}
/// The active display paths.
fn paths() -> Result<Vec<DISPLAYCONFIG_PATH_INFO>, String> {
for _ in 0..4 {
let (mut paths_len, mut modes_len) = (0u32, 0u32);
// SAFETY: both pointers are to live `u32`s.
let e = unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, &mut modes_len) };
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); paths_len as usize];
let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); modes_len as usize];
// SAFETY: the arrays hold as many elements as the lengths passed with them.
let e =
unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, paths.as_mut_ptr(), &mut modes_len, modes.as_mut_ptr(), None) };
if e == ERROR_INSUFFICIENT_BUFFER {
// The displays changed between the two calls.
continue;
}
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
paths.truncate(paths_len as usize);
return Ok(paths);
}
Err("the displays kept changing while Windows listed them".into())
}
/// The path whose source is the GDI device `device` (`\\.\DISPLAY1`), if one is active.
fn find_path(device: &str) -> Result<Option<Path>, String> {
for p in paths()? {
let mut name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
adapterId: p.sourceInfo.adapterId,
id: p.sourceInfo.id,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_SOURCE_DEVICE_NAME` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut name.header) } == 0 && until_nul(&name.viewGdiDeviceName).eq_ignore_ascii_case(device) {
return Ok(Some(Path { source: p.sourceInfo.id, target_adapter: p.targetInfo.adapterId, target: p.targetInfo.id }));
}
}
Ok(None)
}
/// Whether Windows color-manages the path's display itself: Advanced Color is on (HDR), or
/// wide color is enforced (Automatic Color Management on an SDR display).
fn advanced_color(path: &Path) -> bool {
let mut info = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO,
size: size_of::<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>() as u32,
adapterId: path.target_adapter,
id: path.target,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut info.header) } != 0 {
return false;
}
// SAFETY: every bit pattern is a valid `u32`.
let bits = unsafe { info.Anonymous.value };
// advancedColorEnabled is bit 1 and wideColorEnforced bit 2.
bits & 0b110 != 0
}
fn api() -> Option<(GetDefault, GetScope)> {
static API: OnceLock<Option<(GetDefault, GetScope)>> = OnceLock::new();
*API.get_or_init(|| {
// SAFETY: mscms.dll is loaded from System32 only, and stays loaded for the process.
let module = unsafe { LoadLibraryExW(w!("mscms.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?;
// SAFETY: the names are NUL-terminated, and the module is loaded.
let (default, scope) = unsafe {
(GetProcAddress(module, s!("ColorProfileGetDisplayDefault"))?, GetProcAddress(module, s!("ColorProfileGetDisplayUserScope"))?)
};
// SAFETY: both exports have these signatures (icm.h).
unsafe {
Some((
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetDefault>(default),
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetScope>(scope),
))
}
})
}
/// The display's default profile name for its standard color mode, `None` without the API.
fn default_profile(path: &Path) -> Option<Result<Option<String>, String>> {
let (get_default, get_scope) = api()?;
let mut scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
// SAFETY: `scope` is a live `i32`.
if unsafe { get_scope(path.target_adapter, path.source, &mut scope) }.is_err() {
scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
}
let mut name = PWSTR::null();
// SAFETY: `name` is a live pointer the function fills with a string it allocates.
let hr = unsafe { get_default(scope, path.target_adapter, path.source, CPT_ICC.0, CPST_STANDARD_DISPLAY_COLOR_MODE.0, &mut name) };
if hr.is_err() {
return Some(Err(format!("Windows couldn't give the display's profile (error {:#010x})", hr.0)));
}
if name.is_null() {
return Some(Ok(None));
}
// SAFETY: `name` is a NUL-terminated string from the call above, freed once with LocalFree.
let text = unsafe { name.to_string() };
// SAFETY: as above.
let _ = unsafe { LocalFree(Some(HLOCAL(name.0.cast()))) };
Some(text.map(|t| Some(t).filter(|t| !t.is_empty())).map_err(|e| format!("the display's profile name isn't readable: {e}")))
}
/// GDI's profile file for the display device `device`.
fn icm_profile(device: &str) -> Result<Option<String>, String> {
let device = wide(device);
// SAFETY: both strings are NUL-terminated and outlive the call.
let dc = unsafe { CreateDCW(w!("DISPLAY"), PCWSTR(device.as_ptr()), PCWSTR::null(), None) };
if dc.is_invalid() {
return Err("Windows couldn't open the display".into());
}
let mut len = 0u32;
// SAFETY: a null buffer asks for the length only.
let _ = unsafe { GetICMProfileW(dc, &mut len, None) };
let mut buf = vec![0u16; len.clamp(1, 32 * 1024) as usize];
len = buf.len() as u32;
// SAFETY: `buf` holds `len` characters.
let ok = unsafe { GetICMProfileW(dc, &mut len, Some(PWSTR(buf.as_mut_ptr()))) }.as_bool();
// SAFETY: `dc` came from CreateDCW above.
let _ = unsafe { DeleteDC(dc) };
Ok(ok.then(|| until_nul(&buf)).filter(|n| !n.is_empty()))
}
/// The system's color folder (`…\spool\drivers\color`).
fn color_directory() -> Option<PathBuf> {
let mut bytes = 0u32;
// SAFETY: a null buffer asks for the size only, in bytes.
let _ = unsafe { GetColorDirectoryW(PCWSTR::null(), None, &mut bytes) };
let mut buf = vec![0u16; (bytes as usize / 2).clamp(1, 32 * 1024)];
bytes = (buf.len() * 2) as u32;
// SAFETY: `buf` holds `bytes` bytes.
unsafe { GetColorDirectoryW(PCWSTR::null(), Some(PWSTR(buf.as_mut_ptr())), &mut bytes) }.as_bool().then(|| PathBuf::from(until_nul(&buf)))
}
#[cfg(test)]
mod tests {
use windows::Win32::Graphics::Gdi::{DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICEW, EnumDisplayDevicesW};
use super::*;
/// The GDI names (`\\.\DISPLAY1`) of the displays attached to the desktop.
fn attached_displays() -> Vec<String> {
let mut names = Vec::new();
for i in 0.. {
let mut device = DISPLAY_DEVICEW { cb: size_of::<DISPLAY_DEVICEW>() as u32, ..Default::default() };
// SAFETY: `device` is a live `DISPLAY_DEVICEW` with `cb` set to its size.
if !unsafe { EnumDisplayDevicesW(PCWSTR::null(), i, &mut device, 0) }.as_bool() {
break;
}
if device.StateFlags.contains(DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
names.push(until_nul(&device.DeviceName));
}
}
names
}
#[test]
fn windows_reads_each_attached_display_and_refuses_an_unknown_one() {
assert_eq!(read(None), Found::NoProfile("Windows didn't name the window's display".into()));
assert!(color_directory().is_none_or(|dir| dir.is_absolute()));
match find_path(r"\\.\DISPLAY999") {
Ok(path) => {
assert!(path.is_none());
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile("Windows couldn't open the display".into()));
}
// A session without displays (a service): the reading gives Windows' error.
Err(e) => {
eprintln!("the displays couldn't be listed: {e}");
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile(e));
return;
}
}
for name in attached_displays() {
// A display without an active path is read through GDI (`icm_profile`).
let path = find_path(&name).unwrap();
// winit names the display in GDI's spelling; the match ignores letter case.
let lower = find_path(&name.to_lowercase()).unwrap();
assert_eq!(lower.map(|p| (p.source, p.target)), path.as_ref().map(|p| (p.source, p.target)), "{name} in lowercase");
match read(Some(&name)) {
Found::Profile { icc, from } => {
eprintln!("{name}: profile {from}, {} bytes", icc.len());
assert!(!icc.is_empty() && !from.is_empty());
assert!(!path.as_ref().is_some_and(advanced_color));
}
Found::System(e) => {
eprintln!("{name}: system, {e}");
assert!(path.as_ref().is_some_and(advanced_color));
}
Found::NoProfile(e) => {
eprintln!("{name}: no profile, {e}");
assert!(!e.is_empty());
}
}
}
}
}
}
#[cfg(target_os = "linux")]
mod x11 {
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use vectorcraft_ui_egui::display_profile::{Found, MAX_PROFILE_BYTES};
use x11rb::connection::Connection as _;
use x11rb::protocol::randr;
use x11rb::protocol::xproto::{self, AtomEnum};
use zbus::blocking::{connection::Builder, proxy::Proxy};
use zbus::zvariant::OwnedObjectPath;
const COLORD: &str = "org.freedesktop.ColorManager";
const COLORD_ROOT: &str = "/org/freedesktop/ColorManager";
const COLORD_MANAGER: &str = "org.freedesktop.ColorManager";
const COLORD_DEVICE: &str = "org.freedesktop.ColorManager.Device";
const COLORD_PROFILE: &str = "org.freedesktop.ColorManager.Profile";
pub(super) fn read(output: Option<&str>) -> Found {
let colord = output.map(|o| colord_profile(o).map(|path| path.map(|path| super::usable(super::profile_file(Path::new(&path))))));
super::x11_choice(colord, || properties(output))
}
/// The file colord assigns the RandR output `output`.
fn colord_profile(output: &str) -> Result<Option<String>, String> {
let connection = Builder::system()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?
.method_timeout(Duration::from_secs(2))
.build()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?;
let manager = Proxy::new(&connection, COLORD, COLORD_ROOT, COLORD_MANAGER).map_err(|e| format!("couldn't reach colord: {e}"))?;
let devices: Vec<OwnedObjectPath> =
manager.call("GetDevicesByKind", &("display",)).map_err(|e| format!("colord couldn't list the displays: {e}"))?;
for path in devices {
let Ok(device) = Proxy::new(&connection, COLORD, &path, COLORD_DEVICE) else { continue };
let Ok(metadata) = device.get_property::<HashMap<String, String>>("Metadata") else { continue };
if metadata.get("XRANDR_name").map(String::as_str) != Some(output) {
continue;
}
// `*` asks for the device's default profile.
let Ok(profile_path) = device.call::<_, _, OwnedObjectPath>("GetProfileForQualifiers", &(vec!["*"],)) else { return Ok(None) };
let profile =
Proxy::new(&connection, COLORD, &profile_path, COLORD_PROFILE).map_err(|e| format!("couldn't reach colord's profile: {e}"))?;
return Ok(profile.get_property::<String>("Filename").ok().filter(|f| !f.is_empty()));
}
Ok(None)
}
/// The `_ICC_PROFILE` property of the RandR output `output`, or of the screen when only one
/// output is active.
fn properties(output: Option<&str>) -> Result<Option<Found>, String> {
let (conn, screen) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
let root = conn.setup().roots.get(screen).ok_or_else(|| "the X11 display has no screen".to_string())?.root;
let atom = xproto::intern_atom(&conn, true, b"_ICC_PROFILE")
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.reply()
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.atom;
if atom == 0 {
return Ok(None);
}
let resources = randr::get_screen_resources_current(&conn, root)
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?
.reply()
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?;
let (mut active, mut shown) = (0usize, None);
for o in resources.outputs {
let Ok(Ok(info)) = randr::get_output_info(&conn, o, resources.config_timestamp).map(|c| c.reply()) else { continue };
if info.connection != randr::Connection::CONNECTED || info.crtc == 0 {
continue;
}
active += 1;
if output.is_some_and(|name| info.name == name.as_bytes()) {
shown = Some(o);
}
}
let longs = (MAX_PROFILE_BYTES / 4) as u32;
let too_large = || Found::NoProfile(format!("the display's profile is larger than {} MiB", MAX_PROFILE_BYTES >> 20));
if let Some(o) = shown
&& let Ok(Ok(p)) = randr::get_output_property(&conn, o, atom, AtomEnum::ANY, 0, longs, false, false).map(|c| c.reply())
&& !p.data.is_empty()
{
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
return Ok(Some(Found::Profile { icc: p.data, from: "the X11 output's _ICC_PROFILE".into() }));
}
if active != 1 {
return Ok(None);
}
let Ok(Ok(p)) = xproto::get_property(&conn, false, root, atom, AtomEnum::ANY, 0, longs).map(|c| c.reply()) else { return Ok(None) };
if p.value.is_empty() {
return Ok(None);
}
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
Ok(Some(Found::Profile { icc: p.value, from: "the X11 screen's _ICC_PROFILE".into() }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_is_due_first_after_ten_seconds_and_when_the_window_changes_display() {
assert!(due(None, 0.0, None));
let last = (100.0, Some("DP-1".to_string()));
assert!(!due(Some(&last), 100.0, Some("DP-1")));
assert!(!due(Some(&last), 109.9, Some("DP-1")));
assert!(due(Some(&last), 110.0, Some("DP-1")));
assert!(due(Some(&last), 101.0, Some("HDMI-1")));
assert!(due(Some(&last), 101.0, None));
// A clock that went back.
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| std::ffi::OsString::from(v))
};
assert!(wayland_session(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")])));
assert!(wayland_session(env(&[("WAYLAND_SOCKET", "5")])));
assert!(!wayland_session(env(&[("DISPLAY", ":0")])));
assert!(!wayland_session(env(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", ":0")])));
}
#[test]
fn profile_files_larger_than_the_limit_are_refused_before_they_are_read() {
let dir = tempfile::tempdir().unwrap();
let small = dir.path().join("small.icc");
std::fs::write(&small, [1u8, 2, 3]).unwrap();
assert_eq!(read_icc(&small).unwrap(), [1, 2, 3]);
let big = dir.path().join("big.icc");
let f = std::fs::File::create(&big).unwrap();
f.set_len(vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES as u64 + 1).unwrap();
assert!(read_icc(&big).unwrap_err().contains("larger than 1 MiB"));
assert!(read_icc(&dir.path().join("missing.icc")).unwrap_err().starts_with("couldn't open"));
}
#[test]
fn x11_takes_the_output_property_when_colord_s_file_cannot_be_read() {
let icc = |b: u8| Found::Profile { icc: vec![b], from: "test".into() };
let property = || Ok(Some(icc(2)));
// colord's profile, read: the property is not asked for.
assert_eq!(x11_choice(Some(Ok(Some(icc(1)))), || panic!("not asked")), icc(1));
// colord names a file that can't be read, or has no profile, or isn't running.
assert_eq!(x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), property), icc(2));
assert_eq!(x11_choice(Some(Ok(None)), property), icc(2));
assert_eq!(x11_choice(Some(Err("no colord".into())), property), icc(2));
assert_eq!(x11_choice(None, property), icc(2));
// Neither has a profile: colord's reason is kept.
assert_eq!(
x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), || Ok(None)),
Found::NoProfile("no profile is set for this display (couldn't open a.icc)".into())
);
assert_eq!(x11_choice(None, || Ok(None)), Found::NoProfile("no profile is set for this display".into()));
assert_eq!(x11_choice(None, || Err("no X11".into())), Found::NoProfile("no X11".into()));
// colord's file holds no usable profile: the property is used.
let broken = usable(Found::Profile { icc: vec![1, 2, 3], from: "a.icc".into() });
assert_eq!(broken, Found::NoProfile("a.icc: the file is not an ICC profile".into()));
assert_eq!(x11_choice(Some(Ok(Some(broken))), property), icc(2));
assert_eq!(usable(Found::NoProfile("none".into())), Found::NoProfile("none".into()));
}
#[test]
fn a_profile_name_is_found_in_the_color_folder_and_a_path_is_kept() {
let dir = std::path::Path::new("C:/Windows/System32/spool/drivers/color");
assert_eq!(profile_path(Some(dir), "Display.icm"), dir.join("Display.icm"));
assert_eq!(profile_path(Some(dir), "D:\\profiles\\Display.icm"), std::path::PathBuf::from("D:\\profiles\\Display.icm"));
assert_eq!(profile_path(None, "Display.icm"), std::path::PathBuf::from("Display.icm"));
}
}
+3 -2
View File
@@ -393,8 +393,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
// Its calls are marked for the hang report (`hang_watch`).
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
// clipboard holds and macOS asks the pasteboard server, so they check in line.
// owner that never answers holds a text read for up to 4 s for each format it tries, and
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
// Help → Discord / website / GitHub, the Discord button, About and Home links.
@@ -4,7 +4,6 @@
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
mod portal;
mod request;
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
@@ -61,9 +61,9 @@ pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<
/// after it has no bound, and ends when the portal answers or leaves the bus.
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
// Made before the call: a portal can send its answer before the call returns.
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| Failure::Failed(e.to_string()))?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
@@ -106,6 +106,7 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f3
#[cfg(test)]
mod tests {
use super::*;
use crate::portal_request::test_bus::private_bus;
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
@@ -186,35 +187,6 @@ mod tests {
}
}
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
fn client(address: &str) -> Connection {
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
@@ -1,127 +0,0 @@
//! The answer to the color sampler's XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
//! first.
use std::io::Read as _;
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
pub(super) fn token(prefix: &str) -> Result<String, String> {
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(super) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes.
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
let header = reply.header();
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
{
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
}
+26 -3
View File
@@ -28,6 +28,7 @@ mod clipboard;
mod compositor_gpu;
mod control_server;
mod cursor_theme;
mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
@@ -53,10 +54,14 @@ mod mac_tablet;
mod mac_window;
#[cfg(target_os = "macos")]
mod open_documents;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
mod portal_request;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
mod portal_save;
mod prefs_dir;
mod printing;
#[cfg(not(any(target_os = "macos", windows)))]
mod quit_windows;
#[cfg(not(target_os = "macos"))]
mod single_instance;
#[cfg(windows)]
@@ -102,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -116,7 +121,8 @@ struct App {
frames: u64,
/// Keeps the custom title bar's window borderless (Windows, #1758).
window_frame: Option<window_frame::WindowFrameFn>,
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635),
/// and to take the window off screen on quit before the clipboard handles let go (`quit_windows`).
winit_window: Option<std::sync::Arc<winit::window::Window>>,
/// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
pending_maximize: bool,
@@ -126,6 +132,8 @@ struct App {
held_files: Vec<String>,
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
monitors_listed: Option<(f64, f32)>,
/// Reads the profile of the display that shows the main window, for the canvas.
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
}
@@ -359,17 +367,20 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
// and the other choices do so when a pen is attached, where the pen draws (#2028, #4967).
#[cfg(target_os = "linux")]
let mut forced_to_x11 = false;
#[cfg(target_os = "linux")]
let options = {
let mut options = options;
let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
if xwayland::x11_libraries_found() {
forced_to_x11 = true;
if pref != Some("x11") {
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
} else {
@@ -385,6 +396,11 @@ fn main() -> std::process::ExitCode {
}
options
};
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
// Preferences › User Interface notes under System Title Bar when the desktop draws the frame
// with it on or off.
let desktop_keeps_frame = titlebar::desktop_keeps_frame(forced_to_x11);
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
// is down; the message hook notes each pointer contact and whether it starts with the barrel
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
@@ -402,6 +418,10 @@ fn main() -> std::process::ExitCode {
}));
options
};
// Quitting takes the X11 windows of floating panels and documents off screen with the main
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
#[cfg(target_os = "linux")]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
#[cfg(feature = "wgpu")]
let options = {
let mut options = options;
@@ -585,7 +605,9 @@ fn main() -> std::process::ExitCode {
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
app.desktop_keeps_frame = desktop_keeps_frame;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx).with_automation_roots(roots.clone());
@@ -629,6 +651,7 @@ fn main() -> std::process::ExitCode {
maximize_tries: 8,
held_files,
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
}))
}),
+231
View File
@@ -0,0 +1,231 @@
//! Linux and the BSDs: the answer to an XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>),
//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler
//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the
//! portal leaves the bus first.
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
#[cfg(target_os = "linux")]
pub(crate) fn token(prefix: &str) -> Result<String, String> {
use std::io::Read as _;
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(crate) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(crate) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes. A
/// `Response` the portal sent before it left is still the answer.
pub(crate) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let answers = |reply: &zbus::Message| {
let header = reply.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
};
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
if answers(&reply) {
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
// zbus puts each message in every matching stream before it reads the
// next one, so a `Response` that came before the bus's report is
// already queued: it is still the answer.
while let Some(Some(reply)) = future::poll_once(replies.next()).await {
if let Ok(reply) = reply
&& answers(&reply)
{
return Ok(reply);
}
}
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
/// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent
/// before it left is still the answer; without one the wait ends with an error.
#[test]
fn a_queued_answer_wins_over_the_portal_leaving() {
use std::collections::HashMap;
use zbus::blocking::connection::Builder;
use zbus::zvariant::OwnedValue;
for answered in [true, false] {
let Some((_daemon, address)) = test_bus::private_bus() else { return };
let address = address.as_str();
let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap();
let unique = portal.unique_name().unwrap().to_string();
let client = Builder::address(address).unwrap().build().unwrap();
let responses = Responses::new(&client).unwrap();
// zbus puts each message in every matching stream before it reads the next one
// (`src/connection/socket_reader.rs`), so once this stream has the bus's report,
// `responses` holds the `Response` sent before it.
let gone_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.unwrap()
.member("NameOwnerChanged")
.unwrap()
.arg(0, DESKTOP)
.unwrap()
.build();
let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap();
let path = "/org/freedesktop/portal/desktop/request/test/t1";
if answered {
let results = HashMap::<String, OwnedValue>::new();
portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap();
}
portal.close().unwrap();
// On a thread of its own, so a report that never comes fails the test instead of
// hanging it.
let (seen, report) = std::sync::mpsc::channel();
let left = unique.clone();
std::thread::spawn(move || {
let mut gone = gone;
let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false))));
});
assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone");
// The call's reply as `wait` reads it: the request path, from the portal's connection.
let call = zbus::Message::signal("/", "org.example.Test", "Reply")
.unwrap()
.sender(unique.as_str())
.unwrap()
.build(&OwnedObjectPath::try_from(path).unwrap())
.unwrap();
let waited = responses.wait(&call);
assert_eq!(waited.is_ok(), answered, "{waited:?}");
}
}
}
/// The private session bus that the D-Bus tests of the portal requests run on.
#[cfg(test)]
pub(crate) mod test_bus {
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
pub(crate) fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
pub(crate) struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
}
+62 -50
View File
@@ -8,6 +8,7 @@
//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension.
//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its
//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call.
//! rfd also shows the dialog when the portal leaves the bus before it answers.
//!
//! The dialog's parent is the window: `x11:<window id>` on X11, and on Wayland (Linux) a handle
//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`).
@@ -183,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option<V
fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result<Option<Saved>, String> {
use std::sync::atomic::{AtomicU32, Ordering};
use zbus::blocking::{MessageIterator, Proxy};
use zbus::zvariant::OwnedObjectPath;
use zbus::blocking::Proxy;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
const REQUEST: &str = "org.freedesktop.portal.Request";
static NEXT: AtomicU32 = AtomicU32::new(0);
let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
// Listen before asking, on every request path: a portal older than version 0.9 ignores
// `handle_token` and answers on the request path it returns, and its answer can come before
// the call's reply. The stream keeps every `Response` from the time it is made.
let rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface(REQUEST))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?;
// Made before the call: a portal can send its answer before the call returns, and a portal
// that leaves the bus while its dialog is open ends the wait.
let responses = crate::portal_request::Responses::new(conn)?;
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
// The title is empty, as rfd sends it for a save.
let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
// The answer is the `Response` on the path returned, from the connection that returned it.
let portal = call.header().sender().map(|s| s.as_str().to_string());
let reply = responses
.filter_map(Result::ok)
.find(|m| {
let header = m.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
})
.ok_or("the save dialog closed without an answer")?;
let reply = responses.wait(&call)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
}
@@ -260,7 +242,7 @@ fn parent(window: &winit::window::Window) -> (String, Option<()>) {
/// (<https://wayland.app/protocols/xdg-foreign-unstable-v2>), made as rfd's `window_identifier`
/// makes it.
#[cfg(target_os = "linux")]
mod wayland {
pub(crate) mod wayland {
use wayland_client::globals::{GlobalListContents, registry_queue_init};
use wayland_client::protocol::wl_registry::{self, WlRegistry};
use wayland_client::protocol::wl_surface::WlSurface;
@@ -326,9 +308,10 @@ mod wayland {
}
}
/// `window`'s Wayland connection and surface, from its raw handles.
/// `window`'s Wayland connection and surface, from its raw handles. The caller holds `window`
/// while it uses them (`quit_windows` unmaps the main window's surface through them).
#[allow(unsafe_code)]
fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> {
pub(crate) fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> {
use wayland_backend::sys::client::{Backend, ObjectId};
use winit::raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _, RawDisplayHandle, RawWindowHandle};
let (RawWindowHandle::Wayland(w), RawDisplayHandle::Wayland(d)) =
@@ -337,8 +320,8 @@ mod wayland {
return None;
};
// SAFETY: the display is winit's open `wl_display`, which outlives `window` (the caller
// holds it until the export is dropped); a backend made from a foreign display does not
// close it when dropped.
// holds it while it uses the connection, and the export holds it until it is dropped); a
// backend made from a foreign display does not close it when dropped.
let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) };
let conn = Connection::from_backend(backend);
// SAFETY: the pointer is the window's live `wl_surface` proxy on that display.
@@ -495,26 +478,22 @@ mod tests {
Old,
/// As `Old`, with the `Response` sent before the reply that names its path.
OldEarly,
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
/// portal that exits while its dialog is open.
Exits,
/// Leaves the bus right after its reply, without a `Response`.
ExitsAtOnce,
/// Sends its `Response` right after its reply, then leaves the bus.
AnswersAndExits,
}
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
/// `None` when there is no `dbus-daemon` to run.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead as _;
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
use zbus::zvariant::OwnedObjectPath;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let mut daemon = daemon.ok()?;
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
let server =
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
let seen = Seen::default();
@@ -539,8 +518,8 @@ mod tests {
});
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
let token = match portal {
Portal::Current => text("handle_token").unwrap_or_default(),
Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()),
Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(),
};
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
@@ -558,14 +537,22 @@ mod tests {
if server.reply(&header, &handle).is_err() {
break;
}
if portal == Portal::Old {
if matches!(portal, Portal::Old | Portal::Exits) {
// As a person answers the dialog: after the caller has the path returned.
std::thread::sleep(std::time::Duration::from_millis(300));
}
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
break;
}
if portal != Portal::OldEarly && respond().is_err() {
break;
}
if portal == Portal::AnswersAndExits {
break;
}
}
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
let _ = server.close();
});
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
Some((client, seen, daemon))
@@ -589,7 +576,7 @@ mod tests {
#[test]
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
eprintln!("no dbus-daemon: skipped");
return;
};
@@ -599,7 +586,6 @@ mod tests {
assert_eq!(save_within(&conn, &request), Ok(None));
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
let _ = daemon.kill();
}
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
@@ -607,13 +593,12 @@ mod tests {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
let _ = daemon.kill();
}
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
@@ -622,14 +607,41 @@ mod tests {
#[test]
fn an_answer_that_comes_before_the_path_is_kept() {
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
assert_eq!(save_within(&conn, &request), Ok(None));
let _ = daemon.kill();
}
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
/// at once, ends the wait with an error, and rfd shows the dialog.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
}
}
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
/// or the bus's report comes first depends on timing here; `portal_request`'s
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
}
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
+280
View File
@@ -0,0 +1,280 @@
//! Takes the app's windows off screen when it quits on Linux and the BSDs, before eframe drops the
//! app. Dropping the app waits up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the
//! clipboard handles to let go, and eframe closes the windows only after that wait.
//!
//! The main window is hidden on X11 (XWayland included). winit cannot hide a Wayland window, so on
//! Linux a Wayland main window is unmapped instead: its surface gets no buffer, and the window stays
//! open with the connection the Wayland clipboard copies and reads on. On Linux the X11 windows of
//! floating panels and documents are recorded as eframe creates and drops them ([`Hooks`]), and
//! quitting unmaps them through an X11 connection of its own. On native Wayland, floating panels and
//! documents are normally drawn inside the main window.
#[cfg(target_os = "linux")]
use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};
#[cfg(target_os = "linux")]
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
/// The main window as quitting sees it.
pub(crate) trait QuittingWindow {
/// The window is a Wayland surface.
fn is_wayland(&self) -> bool;
/// Hides an X11 window.
fn hide(&self);
/// Takes a Wayland window off screen and keeps it open.
fn unmap(&self);
}
impl QuittingWindow for winit::window::Window {
#[cfg(target_os = "linux")]
fn is_wayland(&self) -> bool {
matches!(self.window_handle().map(|h| h.as_raw()), Ok(RawWindowHandle::Wayland(_)))
}
/// The BSDs have no Wayland unmap: their windows are hidden through winit.
#[cfg(not(target_os = "linux"))]
fn is_wayland(&self) -> bool {
false
}
fn hide(&self) {
self.set_visible(false);
}
#[cfg(target_os = "linux")]
fn unmap(&self) {
unmap_wayland(self);
}
#[cfg(not(target_os = "linux"))]
fn unmap(&self) {
self.set_visible(false);
}
}
/// Takes the main window and the floating windows `x11` lists off screen: a Wayland main window is
/// unmapped and any other main window hidden, and `unmap_x11` unmaps the floating windows.
pub(crate) fn off_screen<W: QuittingWindow + ?Sized>(main: Option<&W>, x11: &[u32], unmap_x11: impl FnOnce(&[u32])) {
if let Some(window) = main {
if window.is_wayland() {
window.unmap();
} else {
window.hide();
}
}
if !x11.is_empty() {
unmap_x11(x11);
}
}
/// [`off_screen`] with the running app's main window and the floating windows [`Hooks`] recorded.
/// Runs on quit, before eframe drops the app.
pub(crate) fn before_teardown(main: Option<&winit::window::Window>) {
#[cfg(target_os = "linux")]
off_screen(main, &CHILD_WINDOWS.x11(), unmap_x11);
#[cfg(not(target_os = "linux"))]
off_screen(main, &[], |_| {});
}
/// The X11 windows of floating panels and documents, by viewport, while eframe holds them.
#[cfg(target_os = "linux")]
#[derive(Default)]
pub(crate) struct ChildWindows(Mutex<HashMap<egui::ViewportId, u32>>);
#[cfg(target_os = "linux")]
impl ChildWindows {
/// eframe made `viewport`'s window, with `handle`. The main window, and windows of other window
/// systems, are not recorded; a window made again for the same viewport replaces its record.
pub(crate) fn created(&self, viewport: egui::ViewportId, handle: Option<RawWindowHandle>) {
let mut windows = self.lock();
match handle.and_then(x11_window) {
Some(id) if viewport != egui::ViewportId::ROOT => windows.insert(viewport, id),
_ => windows.remove(&viewport),
};
}
/// eframe dropped `viewport`'s window.
pub(crate) fn destroyed(&self, viewport: egui::ViewportId) {
self.lock().remove(&viewport);
}
/// The recorded windows, in id order.
pub(crate) fn x11(&self) -> Vec<u32> {
let mut ids: Vec<u32> = self.lock().values().copied().collect();
ids.sort_unstable();
ids.dedup();
ids
}
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, u32>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// The X11 window id of `handle`, None for another window system.
#[cfg(target_os = "linux")]
fn x11_window(handle: RawWindowHandle) -> Option<u32> {
match handle {
RawWindowHandle::Xlib(h) => u32::try_from(h.window).ok(),
RawWindowHandle::Xcb(h) => Some(h.window.get()),
_ => None,
}
}
/// The running app's floating windows, which [`Hooks`] records.
#[cfg(target_os = "linux")]
static CHILD_WINDOWS: LazyLock<ChildWindows> = LazyLock::new(ChildWindows::default);
/// Records the windows eframe creates and drops in [`CHILD_WINDOWS`]; set as
/// [`eframe::NativeOptions::viewport_hooks`].
#[cfg(target_os = "linux")]
pub(crate) struct Hooks;
#[cfg(target_os = "linux")]
impl eframe::ViewportHooks for Hooks {
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
CHILD_WINDOWS.created(viewport, window.window_handle().ok().map(|h| h.as_raw()));
}
fn window_destroyed(&self, viewport: egui::ViewportId) {
CHILD_WINDOWS.destroyed(viewport);
}
}
/// Unmaps the X11 `windows` through a connection of its own, and waits until the server has done so.
/// An id whose window is gone gets an error, which is ignored.
#[cfg(target_os = "linux")]
fn unmap_x11(windows: &[u32]) {
use x11rb::protocol::xproto::ConnectionExt as _;
let conn = match x11rb::connect(None) {
Ok((conn, _)) => conn,
Err(e) => {
log::warn!("couldn't reach the X server to hide the floating windows on quit: {e}");
return;
}
};
for &window in windows {
if let Ok(cookie) = conn.unmap_window(window) {
cookie.ignore_error();
}
}
// The server answers once it has handled the requests before this one.
if let Ok(cookie) = conn.get_input_focus() {
let _ = cookie.reply();
}
}
/// Attaches no buffer to `window`'s Wayland surface and commits it, which unmaps the window: the
/// compositor stops showing it, and the window and its connection stay open.
#[cfg(target_os = "linux")]
fn unmap_wayland(window: &winit::window::Window) {
let Some((conn, surface)) = super::portal_save::wayland::surface(window) else { return };
surface.attach(None, 0, 0);
surface.commit();
if let Err(e) = conn.flush() {
log::warn!("couldn't reach the compositor to hide the window on quit: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
/// A main window that records what quitting did to it.
struct Window<'a> {
wayland: bool,
done: &'a RefCell<Vec<String>>,
}
impl QuittingWindow for Window<'_> {
fn is_wayland(&self) -> bool {
self.wayland
}
fn hide(&self) {
self.done.borrow_mut().push("hide".into());
}
fn unmap(&self) {
self.done.borrow_mut().push("unmap".into());
}
}
fn quit(wayland: Option<bool>, x11: &[u32]) -> Vec<String> {
let done = RefCell::new(Vec::new());
let window = wayland.map(|wayland| Window { wayland, done: &done });
off_screen(window.as_ref(), x11, |ids| done.borrow_mut().push(format!("unmap x11 {ids:?}")));
done.into_inner()
}
/// winit cannot hide a Wayland window: quitting unmaps it, and never only asks winit to hide it.
#[test]
fn quitting_unmaps_a_wayland_main_window() {
assert_eq!(quit(Some(true), &[]), ["unmap"]);
}
/// An X11 main window (XWayland included) is hidden, and the floating panels' and documents' X11
/// windows are unmapped with it.
#[test]
fn quitting_hides_an_x11_main_window_and_its_floating_windows() {
assert_eq!(quit(Some(false), &[]), ["hide"]);
assert_eq!(quit(Some(false), &[7, 9]), ["hide", "unmap x11 [7, 9]"]);
}
/// Without a main window (none was made), the floating windows still go, and with none at all
/// nothing is done.
#[test]
fn quitting_without_a_main_window() {
assert_eq!(quit(None, &[3]), ["unmap x11 [3]"]);
assert!(quit(None, &[]).is_empty());
}
#[cfg(target_os = "linux")]
fn xlib(id: std::os::raw::c_ulong) -> Option<RawWindowHandle> {
Some(RawWindowHandle::Xlib(winit::raw_window_handle::XlibWindowHandle::new(id)))
}
#[cfg(target_os = "linux")]
fn viewport(name: &str) -> egui::ViewportId {
egui::ViewportId::from_hash_of(name)
}
/// The floating windows eframe made are recorded until it drops them; the main window, which
/// quitting reaches through winit, is not.
#[cfg(target_os = "linux")]
#[test]
fn floating_x11_windows_are_recorded_while_they_exist() {
let windows = ChildWindows::default();
windows.created(egui::ViewportId::ROOT, xlib(1));
windows.created(viewport("Layers"), xlib(9));
let xcb = winit::raw_window_handle::XcbWindowHandle::new(std::num::NonZeroU32::new(5).expect("not zero"));
windows.created(viewport("Untitled-2"), Some(RawWindowHandle::Xcb(xcb)));
windows.created(viewport("Color"), xlib(7));
assert_eq!(windows.x11(), [5, 7, 9]);
windows.destroyed(viewport("Color"));
assert_eq!(windows.x11(), [5, 9]);
// A viewport that eframe has already dropped, or never made, is no error.
windows.destroyed(viewport("Color"));
windows.destroyed(viewport("Swatches"));
assert_eq!(windows.x11(), [5, 9]);
}
/// A window made again for a viewport replaces its record, and one of another window system, or
/// one whose handle could not be read, removes it.
#[cfg(target_os = "linux")]
#[test]
fn a_window_made_again_replaces_its_record() {
let windows = ChildWindows::default();
windows.created(viewport("Layers"), xlib(9));
windows.created(viewport("Layers"), xlib(11));
assert_eq!(windows.x11(), [11]);
let surface = std::ptr::NonNull::<std::ffi::c_void>::dangling();
let wayland = winit::raw_window_handle::WaylandWindowHandle::new(surface);
windows.created(viewport("Layers"), Some(RawWindowHandle::Wayland(wayland)));
assert!(windows.x11().is_empty());
windows.created(viewport("Layers"), xlib(11));
windows.created(viewport("Layers"), None);
assert!(windows.x11().is_empty());
}
}
+61 -6
View File
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
@@ -312,13 +339,41 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// Preferences says under System Title Bar that the desktop draws the frame with it on or off
/// exactly where the start frame without VectorCraft Title Bar on Every Desktop is the desktop's
/// with System Title Bar off as well as on and `VECTORCRAFT_TITLEBAR` is unset: Linux and the BSDs
/// only.
#[test]
fn the_desktop_keeps_the_frame_where_system_title_bar_does_not_change_it() {
use crate::titlebar::desktop_keeps_frame_from;
use craft_window::{Frame, Layout};
let linux = cfg!(not(any(target_os = "macos", target_os = "windows")));
for probed in [Frame::Desktop, Frame::App(Layout::default())] {
for forced_to_x11 in [false, true] {
let frame = super::start_frame(probed.clone(), None, forced_to_x11, false);
let either_way = !super::custom_titlebar_from(&frame, false) && !super::custom_titlebar_from(&frame, true);
assert_eq!(desktop_keeps_frame_from(&probed, None, forced_to_x11), linux && either_way, "{probed:?} {forced_to_x11}");
}
}
// KDE, Sway and X11, and GNOME through XWayland, keep the desktop's frame; GNOME on Wayland does not.
assert_eq!(desktop_keeps_frame_from(&Frame::Desktop, None, false), linux);
assert_eq!(desktop_keeps_frame_from(&Frame::App(Layout::default()), None, true), linux);
assert!(!desktop_keeps_frame_from(&Frame::App(Layout::default()), None, false));
// While `VECTORCRAFT_TITLEBAR` chooses the frame, System Title Bar does not apply and there is no note.
for (frame, overridden) in [(Frame::App(Layout::default()), Some(true)), (Frame::Desktop, Some(false))] {
for forced_to_x11 in [false, true] {
assert!(!desktop_keeps_frame_from(&frame, overridden, forced_to_x11), "{overridden:?} {forced_to_x11}");
}
}
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
+56 -9
View File
@@ -31,7 +31,7 @@ pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
///
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
@@ -160,7 +188,26 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
}
/// Whether the desktop would draw this window's frame with System Title Bar on or off while
/// VectorCraft Title Bar on Every Desktop is off: `VECTORCRAFT_TITLEBAR` is not set to `app`,
/// `system` or `desktop` (`overridden` is `None`), and the probe chose
/// [`craft_window::Frame::Desktop`] or the window opens through XWayland (`forced_to_x11`)
/// ([`app_draws_frame`]). The saved VectorCraft Title Bar on Every Desktop is left out, so the value
/// stays `true` on such a desktop while that preference gives the app the frame. Always `false` on
/// macOS and Windows, where System Title Bar decides the frame by itself.
pub(crate) fn desktop_keeps_frame_from(probed: &craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool) -> bool {
let probed_app = matches!(probed, craft_window::Frame::App(_));
cfg!(not(any(target_os = "macos", target_os = "windows"))) && overridden.is_none() && !app_draws_frame(probed_app, None, forced_to_x11, false)
}
/// [`desktop_keeps_frame_from`] for this start's probe, given whether the launch path opens the
/// window through XWayland.
pub(crate) fn desktop_keeps_frame(forced_to_x11: bool) -> bool {
let choice = probed_choice();
desktop_keeps_frame_from(choice.frame(), choice.overridden(), forced_to_x11)
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+5 -1
View File
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
for k in 1..pieces {
let u = k as f64 / pieces as f64;
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
let s = t.cum[i] + seg * u;
// On a chord of a flattened curve the samples follow the smooth frame through the
// vertices.
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
out.push((q, tg, s / len));
}
}
}
+3 -45
View File
@@ -114,51 +114,9 @@ fn strip_brushes(n: &mut Node) {
}
}
/// Mix every solid paint under `n` towards `color` by `amount` (0..1) — the Symbol Stainer.
pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
let amount = amount.clamp(0.0, 1.0);
for it in &mut n.appearance.items {
let p = match it {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
};
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
for p in [&mut r.style.fill, &mut r.style.stroke] {
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
tint_node(Arc::make_mut(c), color, amount);
}
}
}
/// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`: with the instance's own appearance changes to it (a dynamic
/// symbol's, [`vectorcraft_doc::symbol_overrides`]), stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = vectorcraft_doc::symbol_overrides::dynamic_art(art, inst);
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
a
}
/// The Symbol Stainer's mix, an instance's stain and its stained art, from
/// [`vectorcraft_doc::symbol_overrides`], which the effects that reshape an instance also read.
pub use vectorcraft_doc::symbol_overrides::{instance_art, stain, tint_node};
/// The solid colours of the fills and strokes under `nodes`, most used first (then in the order
/// they first appear): the colours Brush Options offers as Hue Shift's key colour, the first being
+70 -4
View File
@@ -13,6 +13,7 @@
mod calli;
mod colorize;
mod defaults;
pub mod stored_art;
pub mod track;
mod warp;
@@ -351,7 +352,8 @@ pub enum Direction {
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "mode")]
pub enum ArtScale {
/// Keep the art's proportions (length follows the path; width scales with it).
/// Keep the art's proportions (length follows the path; width scales with it, times the
/// stroke weight and the brush width).
Proportional,
/// Stretch the art to the path length.
#[default]
@@ -762,14 +764,51 @@ pub fn library(doc: &Document) -> Vec<Brush> {
}
/// Parse a stored library value (malformed entries are skipped, values kept within their
/// ranges; see [`Brush::from_json`]).
/// ranges; see [`Brush::from_json`]). A name that repeats is kept by its first brush, and each
/// later brush of that name is numbered ([`number_repeated_names`]).
pub fn parse_library(v: &serde_json::Value) -> Vec<Brush> {
v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default()
let mut lib: Vec<Brush> = v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default();
number_repeated_names(&mut lib);
lib
}
/// Store `lib` as the document's brush library.
/// Renames the second and later brushes of each repeated name in `lib` to the first "Name 2",
/// "Name 3"… that no brush in `lib` has. The first brush of a name keeps it, so a stroke that names
/// it draws the brush [`find`] gave it before.
fn number_repeated_names(lib: &mut [Brush]) {
let mut seen = std::collections::HashSet::new();
if lib.iter().all(|b| seen.insert(b.name.as_str())) {
return;
}
let mut taken: std::collections::HashSet<String> = lib.iter().map(|b| b.name.clone()).collect();
let mut kept = std::collections::HashSet::new();
// The next number to try for each repeated name, so the brushes of one name try each number
// once between them.
let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
for b in lib.iter_mut() {
if kept.insert(b.name.clone()) {
continue;
}
let from = next.entry(b.name.clone()).or_insert(2);
// `taken` is finite, so one of the numbers is free.
if let Some((i, name)) = (*from..).map(|i| (i, format!("{} {i}", b.name))).find(|(_, n)| !taken.contains(n)) {
*from = i.saturating_add(1);
taken.insert(name.clone());
kept.insert(name.clone());
b.name = name;
}
}
}
/// Store `lib` as the document's brush library. When the art of a brush holds images or placed
/// documents, each object in that art whose id is 0 or repeats another object's is given a new
/// id ([`stored_art::StoredArt::persist_ids`]), so the Links panel lists it by the same id until it
/// changes.
pub fn store(doc: &mut Document, lib: &[Brush]) {
doc.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap_or_default());
if lib.iter().any(|b| b.art().into_iter().any(stored_art::holds_files)) {
stored_art::StoredArt::persist_ids(doc);
}
}
/// Find a brush by name.
@@ -969,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
}
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
/// the exports leave for brush art when they cull.
pub fn reach(n: &Node) -> f64 {
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none());
if !n.appearance.items.iter().any(paints) {
return 0.0;
}
let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
16.0 * w + 8.0
}
/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and
/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the
/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as
/// it is painted with its own appearance and not its paths'. Symbol art is not looked into
/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it).
pub fn reach_within(n: &Node) -> f64 {
let members = match &n.kind {
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(),
NodeKind::Compound { .. } => &[],
_ => n.children().map_or(&[][..], |c| &c[..]),
};
members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max)
}
/// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any
/// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed.
pub fn expand(doc: &Document, n: &Node) -> Option<Node> {
+176
View File
@@ -0,0 +1,176 @@
//! The art of the stored brushes (a scatter or art brush's art, a pattern brush's tiles) as stored
//! art of the document ([`Document::mounted_art`]): set on the document while a command looks it up
//! by id or changes it, then written back into the library entries whose art changed. The Links
//! panel finds the images and placed documents in that art this way.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use crate::{Brush, BrushKind, DOC_KEY};
/// The brushes of a document's stored library whose art holds images or placed documents.
#[derive(Default)]
pub struct StoredArt {
entries: Vec<Entry>,
/// How many entries the stored library had when it was read.
read_entries: usize,
}
/// A library entry whose brush's art holds images or placed documents.
struct Entry {
/// Its index in the stored library.
slot: usize,
/// The entry as it was read.
raw: Value,
brush: Brush,
/// The brush's art ([`Brush::art`]), each root with the `owner` the Links panel names for it.
art: Vec<(Arc<Node>, Value)>,
}
/// What names each root of [`Brush::art`] among the brush's art: a pattern brush's tile, in the
/// same order; nothing for the one root of a scatter or art brush.
fn tiles(b: &Brush) -> Vec<Option<&'static str>> {
match &b.kind {
BrushKind::Pattern(p) => std::iter::once(Some("side"))
.chain(
[
(p.outer_corner.is_some(), "outerCorner"),
(p.inner_corner.is_some(), "innerCorner"),
(p.start.is_some(), "start"),
(p.end.is_some(), "end"),
]
.into_iter()
.filter(|(held, _)| *held)
.map(|(_, tile)| Some(tile)),
)
.collect(),
_ => vec![None],
}
}
/// Whether `n` or its subtree, opacity-mask art included, holds an image or a placed document.
pub(crate) fn holds_files(n: &Node) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= matches!(c.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
found
}
impl StoredArt {
/// The brushes of `doc`'s stored library whose art holds an image or a placed document (opacity
/// masks included). An entry that does not read as a brush is left out, and so is left as it
/// is. A root's owner is
/// `{kind: "brush", name, index, tile?}`, with the name and index the brush has in the library as
/// the Brushes panel lists it ([`crate::library`], a repeated name numbered).
pub fn read(doc: &Document) -> Self {
let Some(stored) = doc.unknown.get(DOC_KEY) else { return Self::default() };
let Some(list) = stored.as_array() else { return Self::default() };
let listed = crate::parse_library(stored);
let parsed = list.iter().enumerate().filter_map(|(slot, raw)| Brush::from_json(raw.clone()).ok().map(|b| (slot, raw, b)));
let mut entries = vec![];
for (index, (slot, raw, brush)) in parsed.enumerate() {
if !brush.art().into_iter().any(holds_files) {
continue;
}
let name = listed.get(index).map_or(brush.name.as_str(), |b| b.name.as_str());
let art: Vec<(Arc<Node>, Value)> = brush
.art()
.into_iter()
.zip(tiles(&brush))
.map(|(n, tile)| {
let mut owner = json!({ "kind": "brush", "name": name, "index": index });
if let Some(tile) = tile {
owner["tile"] = json!(tile);
}
(Arc::new(n.clone()), owner)
})
.collect();
if !art.is_empty() {
entries.push(Entry { slot, raw: raw.clone(), brush, art });
}
}
Self { entries, read_entries: list.len() }
}
/// Gives the objects of the stored brushes' art that holds images or placed documents ids of
/// their own in `doc`'s library, as [`Self::mount`] gives them, and writes the brushes whose
/// ids changed back. Does nothing while art is set on `doc` ([`Document::mounted_art`]).
pub fn persist_ids(doc: &mut Document) {
if !doc.mounted_art.is_empty() {
return;
}
let art = Self::read(doc);
if !art.is_empty() {
art.mount(doc);
art.write_entries(doc);
}
}
/// No stored brush's art holds an image or a placed document.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Sets the art on `doc` as [`Document::mounted_art`], each object with an id of its own
/// ([`Document::number_mounted_art`]: an id another stored object has, or none, is replaced, and
/// the id counter stands above them all).
pub fn mount(&self, doc: &mut Document) {
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
doc.number_mounted_art();
}
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
/// included) back into its library entry: the entry at its index when that entry is as it was
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
/// the brush as it was, else the first that does apart from its name. An entry found apart from
/// its name keeps that name (the library was written again meanwhile, as placing a document's
/// brushes into it does, numbering a repeated name). The other entries are left as
/// they are. Then the art of brushes added meanwhile gets ids of its own
/// ([`Self::persist_ids`]).
pub fn write_back(self, doc: &mut Document) {
let read_entries = self.read_entries;
self.write_entries(doc);
if doc.unknown.get(DOC_KEY).and_then(Value::as_array).map(Vec::len) != Some(read_entries) {
Self::persist_ids(doc);
}
}
/// [`Self::write_back`] without giving ids to the art of brushes added meanwhile.
fn write_entries(self, doc: &mut Document) {
let mut mounted = std::mem::take(&mut doc.mounted_art).into_iter();
let mut changed = vec![];
for e in self.entries {
let now: Vec<Arc<Node>> = mounted.by_ref().take(e.art.len()).map(|(n, _)| n).collect();
if now.len() != e.art.len() || now.iter().zip(&e.art).all(|(a, (b, _))| Arc::ptr_eq(a, b)) {
continue;
}
let mut brush = e.brush.clone();
for (slot, art) in brush.art_mut().into_iter().zip(now) {
*slot = Arc::unwrap_or_clone(art);
}
changed.push((e.slot, e.raw, e.brush, brush));
}
let Some(list) = doc.unknown.get_mut(DOC_KEY).and_then(Value::as_array_mut) else { return };
for (slot, raw, was, mut brush) in changed {
// The entry's name when it reads as `was` apart from its name.
let name_of = |entry: &Value| {
Brush::from_json(entry.clone()).ok().and_then(|mut b| {
let name = std::mem::replace(&mut b.name, was.name.clone());
(b == was).then_some(name)
})
};
let at = match list.get(slot) {
Some(entry) if *entry == raw || name_of(entry).is_some() => Some(slot),
_ => list.iter().position(|e| name_of(e).as_ref() == Some(&was.name)).or_else(|| list.iter().position(|e| name_of(e).is_some())),
};
let Some(entry) = at.and_then(|i| list.get_mut(i)) else { continue };
if let Some(name) = name_of(entry) {
brush.name = name;
}
if let Ok(v) = serde_json::to_value(&brush) {
*entry = v;
}
}
}
}
+274
View File
@@ -141,6 +141,50 @@ fn art_brush_proportional_keeps_aspect() {
assert!(near(bounds(&out).height(), 8.0, 1e-6));
}
/// Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch art
/// is, on top of the scale the path length gives it.
#[test]
fn art_brush_proportional_grows_with_weight() {
let brush = |width: f64, overlap: bool| {
let mut b = art_brush(rect_art(100.0, 4.0), ArtScale::Proportional);
if let BrushKind::Art(a) = &mut b.kind {
(a.width, a.overlap) = (width, overlap);
}
b
};
let draw = |b: &Brush, bp: &BezPath, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, bp, st);
// 3 pt stroke → 3× wider than at 1 pt (8 pt); the length still follows the path.
let b = bounds(&draw(&brush(100.0, false), &line(0.0, 0.0, 200.0, 0.0), &stroke(3.0)));
assert!(near(b.height(), 24.0, 1e-6) && near(b.x0, 0.0, 1e-6) && near(b.x1, 200.0, 1e-6), "{b:?}");
// The Width (50 %) applies on top of the stroke weight.
let b = bounds(&draw(&brush(50.0, false), &line(0.0, 0.0, 200.0, 0.0), &stroke(3.0)));
assert!(near(b.height(), 12.0, 1e-6), "{b:?}");
// A path twice as long at twice the weight (as Scale Strokes & Effects at 200 % leaves it):
// 2× from the length and 2× from the weight.
let b = bounds(&draw(&brush(100.0, false), &line(0.0, 0.0, 400.0, 0.0), &stroke(2.0)));
assert!(near(b.height(), 32.0, 1e-6), "{b:?}");
// With Overlap, each run between corners is scaled by its own length and by the weight: the
// 100 pt run 4 pt × 3 across, the 50 pt run 2 pt × 3.
let mut bent = BezPath::new();
bent.move_to((0.0, 0.0));
bent.line_to((100.0, 0.0));
bent.line_to((100.0, 50.0));
let out = draw(&brush(100.0, true), &bent, &stroke(3.0));
assert_eq!(out.len(), 2);
let (r0, r1) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
assert!(near(r0.height(), 12.0, 1e-6) && near(r1.width(), 6.0, 1e-6), "{r0:?} {r1:?}");
// A width that follows the pen: 50 % at the lightest pressure, 300 % at the heaviest, times
// the 2 pt weight (4 pt art on a 100 pt path: 4 pt across at 100 %, 1 pt either side).
let mut pen = brush(50.0, false);
if let BrushKind::Art(a) = &mut pen.kind {
(a.width_mode, a.width_max) = (Some(Variation::Pressure), Some(300.0));
}
let ramp = StrokeLayer { width: 2.0, ..pressed(vec![(0.0, 0.0), (1.0, 1.0)]) };
let out = draw(&pen, &line(0.0, 0.0, 100.0, 0.0), &ramp);
assert!(near(half_width(&out, 0.0, 1.0), 2.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
assert!(near(half_width(&out, 99.0, 100.0), 12.0, 0.2), "{}", half_width(&out, 99.0, 100.0));
}
#[test]
fn art_brush_between_guides_keeps_ends() {
// Head (last 20 % of a 100 pt art) keeps its 20 pt length on a 300 pt path.
@@ -945,6 +989,187 @@ fn library_defaults_store_and_find() {
assert_eq!(unique_name(&lib, "Arrow"), "Arrow 2");
}
/// A stored library that repeats a name reads with the first brush of that name as stored and each
/// later one numbered, past every name the library already has; strokes of the name keep drawing
/// the first brush.
#[test]
fn repeated_brush_names_are_numbered_when_read() {
let mut d = Document::new(100.0, 100.0);
let named = |name: &str, size: f64| Brush { name: name.into(), ..calli(0.0, 100.0, size) };
store(&mut d, &[named("Nib", 1.0), named("Nib 2", 2.0), named("Nib", 3.0), named("Other", 4.0), named("Nib", 5.0), named("Nib 2", 6.0)]);
let lib = library(&d);
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["Nib", "Nib 2", "Nib 3", "Other", "Nib 4", "Nib 2 2"]);
let size = |b: &Brush| if let BrushKind::Calligraphic(c) = &b.kind { c.size } else { 0.0 };
assert_eq!(lib.iter().map(size).collect::<Vec<_>>(), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
assert_eq!(find(&d, "Nib").map(|b| size(&b)), Some(1.0));
assert_eq!(find(&d, "Nib 3").map(|b| size(&b)), Some(3.0));
// Reading again gives the same names, and the numbered library stored again reads as stored.
assert_eq!(library(&d), lib);
store(&mut d, &lib);
assert_eq!(library(&d), lib);
// Many brushes of one name take the numbers in order, past the numbered names the file has.
let many: Vec<Brush> = (0..5000).map(|i| named(if i == 1 { "Nib 3" } else { "Nib" }, 1.0)).collect();
store(&mut d, &many);
let names: Vec<String> = library(&d).into_iter().map(|b| b.name).collect();
assert_eq!(names[..5], ["Nib", "Nib 3", "Nib 2", "Nib 4", "Nib 5"]);
assert_eq!(names.last().map(String::as_str), Some("Nib 5000"));
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len());
}
/// Art of `w`×`h` points holding a linked image: a group of [`rect_art`] and the image, both with id 0.
fn linked_art(w: f64, h: f64) -> Node {
let image = Node::new(
NodeId(0),
NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: Affine::IDENTITY,
link: Some(vectorcraft_doc::LinkInfo::new("/art/a.png")),
placement: Default::default(),
pixels: None,
})),
);
Node::group(NodeId(0), vec![std::sync::Arc::new(rect_art(w, h)), std::sync::Arc::new(image)])
}
/// The art of the stored brushes that holds images mounts on the document as stored art, each tile
/// with the brush, its place in the library and the tile as owner, its objects with ids of their
/// own; writing it back changes only the entries whose art changed, and leaves an entry that does
/// not read as a brush, a brush without art and a brush whose art holds no image as they were stored.
#[test]
fn stored_brush_art_mounts_and_writes_back_only_what_changed() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let layer_object = d.layers[0].id;
let mut side = linked_art(10.0, 4.0);
side.id = layer_object;
let pattern =
Brush { name: "Frame".into(), kind: BrushKind::Pattern(PatternBrush { side, start: Some(linked_art(4.0, 4.0)), ..Default::default() }) };
let scatter = Brush {
name: "Dots".into(),
kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), colorization: Colorization::None, ..Default::default() }),
};
// Written as a file holds it, without the ids `store` gives.
let lib = [calli(0.0, 100.0, 3.0), pattern, scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)];
d.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap());
let odd = serde_json::json!({ "name": "Odd", "type": "unknown" });
if let Some(list) = d.unknown.get_mut(DOC_KEY).and_then(serde_json::Value::as_array_mut) {
list.insert(1, odd.clone());
}
let stored = d.unknown[DOC_KEY].clone();
let art = StoredArt::read(&d);
art.mount(&mut d);
let owners: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| o).collect();
assert_eq!(
owners,
[
&serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "side" }),
&serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "start" }),
&serde_json::json!({ "kind": "brush", "name": "Dots", "index": 2 }),
]
);
let ids: Vec<NodeId> = d.mounted_art.iter().map(|(n, _)| n.id).collect();
let mut all = vec![];
d.visit_stored(|n, _| all.push(n.id));
assert!(all.iter().all(|id| id.0 != 0) && !all[1..].contains(&layer_object), "{all:?}");
assert_eq!(all.iter().collect::<std::collections::HashSet<_>>().len(), all.len(), "{all:?}");
// The scatter brush's art changes; the pattern brush's tiles keep the ids mounting gave them.
d.stored_node_mut(ids[2]).unwrap().name = Some("changed".into());
art.write_back(&mut d);
assert!(d.mounted_art.is_empty());
let now = d.unknown[DOC_KEY].as_array().unwrap();
assert_eq!(now.len(), 5);
assert_eq!((&now[0], &now[1], &now[4]), (&stored[0], &odd, &stored[4]), "the entries without images stay as stored");
assert_ne!(now[2], stored[2], "the pattern brush keeps the ids its art was given");
let lib = library(&d);
let Some(BrushKind::Pattern(p)) = lib.iter().find(|b| b.name == "Frame").map(|b| &b.kind) else { panic!("no pattern brush") };
assert_eq!((p.side.id, p.start.as_ref().map(|n| n.id)), (ids[0], Some(ids[1])));
assert_eq!(find(&d, "Dots").unwrap().art()[0].name.as_deref(), Some("changed"));
// Mounting again gives the same ids and changes nothing, so writing back leaves the library as it is.
let again = d.unknown[DOC_KEY].clone();
let art = StoredArt::read(&d);
art.mount(&mut d);
assert_eq!(d.mounted_art.iter().map(|(n, _)| n.id).collect::<Vec<_>>(), ids);
art.write_back(&mut d);
assert_eq!(d.unknown[DOC_KEY], again);
}
/// A brush whose stored name repeats an earlier brush's is named in its art's owner as the Brushes
/// panel lists it, numbered.
#[test]
fn stored_brush_art_owner_names_a_repeated_name_as_listed() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), ..Default::default() }) };
store(&mut d, &[scatter.clone(), scatter]);
StoredArt::read(&d).mount(&mut d);
let names: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| &o["name"]).collect();
assert_eq!(names, ["Dots", "Dots 2"]);
}
/// Storing a library whose brush art holds an image gives that art ids of its own, so mounting it
/// later gives the same ids whatever the document allocated in between; art without images keeps
/// the ids it was stored with.
#[test]
fn storing_brush_art_with_images_keeps_ids_of_its_own() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let mut art = linked_art(2.0, 2.0);
art.id = d.layers[0].id;
let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art, ..Default::default() }) };
store(&mut d, &[scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)]);
let lib = library(&d);
let stored = lib[0].art()[0].id;
assert_ne!(stored, d.layers[0].id);
assert_eq!(lib[1].art()[0].id, NodeId(0), "art without images is stored as it was");
d.alloc_id();
StoredArt::read(&d).mount(&mut d);
assert_eq!(d.mounted_art[0].0.id, stored);
}
/// When the library is written again while the art is mounted, numbering a repeated name and
/// adding a brush (as placing a document's brushes into it does), writing back changes the entry
/// at its own place that reads as the brush apart from its new name, keeping that name, even when
/// an earlier brush is the same as the one it was, and gives the added brush's art ids of its own.
#[test]
fn brush_art_written_back_finds_its_renamed_entry_and_numbers_added_art() {
use stored_art::StoredArt;
/// `n` with ids from `next` on, in paint order.
fn numbered(mut n: Node, next: &mut u64) -> Node {
n.id = NodeId(*next);
*next += 1;
for c in n.children_mut().into_iter().flatten() {
*c = std::sync::Arc::new(numbered((**c).clone(), next));
}
n
}
let mut d = Document::new(100.0, 100.0);
let scatter =
|n: &str| Brush { name: n.into(), kind: BrushKind::Scatter(Scatter { art: numbered(linked_art(2.0, 2.0), &mut 50), ..Default::default() }) };
// Two brushes the same apart from the ids mounting gives the second.
d.unknown.insert(DOC_KEY.into(), serde_json::to_value([scatter("Dots"), scatter("Dots")]).unwrap());
let art = StoredArt::read(&d);
art.mount(&mut d);
assert_eq!(d.mounted_art[0].0.id, NodeId(50));
let second = d.mounted_art[1].0.id;
// The library is written again: the repeated name numbered, a brush whose art repeats an id added.
let mut added = scatter("New");
if let BrushKind::Scatter(s) = &mut added.kind {
s.art.id = d.layers[0].id;
}
let lib = [library(&d), vec![added]].concat();
d.unknown.insert(DOC_KEY.into(), serde_json::to_value(&lib).unwrap());
assert_eq!(lib[1].name, "Dots 2");
d.stored_node_mut(second).unwrap().name = Some("changed".into());
art.write_back(&mut d);
let lib = library(&d);
assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Dots", "Dots 2", "New"]);
assert_eq!((lib[0].art()[0].name.as_deref(), lib[1].art()[0].name.as_deref()), (None, Some("changed")));
assert_ne!(lib[2].art()[0].id, d.layers[0].id, "the added brush's art has ids of its own");
}
#[test]
fn brushes_serde_round_trip() {
let lib = defaults().to_vec();
@@ -1009,6 +1234,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
}
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
/// curve those samples sit on the curve, and the outline keeps its distance from it.
#[test]
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
let (r, half) = (50.0, 10.0);
let c = Point::new(r, r);
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
let mut pts = vec![];
for n in &out {
all_points(n, &mut pts);
}
// Away from the round caps at the two ends, every outline point is `half` from the curve.
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
}
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
/// size + variation at the heaviest, along the stroke where the pen pressed.
#[test]
@@ -1658,6 +1903,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
assert!(anchors(&out) < 2_000_000);
}
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
/// anchors the fit puts along them.
#[test]
fn art_brush_edges_stay_smooth_along_a_curve() {
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
// The top half of a circle, as one open path of two curves.
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
// The turn at each smooth anchor of the edges: the angle between the incoming and the
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
let mut kink = 0.0f64;
for sp in &path.subpaths {
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
let (u, v) = (a.p - h_in, h_out - a.p);
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
continue;
}
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
}
}
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
}
}
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
fn anchors_and_curved(n: &Node) -> (usize, usize) {
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
+346 -35
View File
@@ -1,8 +1,9 @@
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
//!
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
//! stays discontinuous, so art folds there.
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
@@ -22,6 +23,11 @@ pub struct Track {
pub tangents: Vec<Vec2>,
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
pub corner: Vec<bool>,
/// Does the segment come from flattening a curve (rather than from a line of the path)?
pub curved: Vec<bool>,
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
/// to follow a curve through them; 0 for a line.
turn: Vec<f64>,
}
fn unit(v: Vec2) -> Vec2 {
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
a.dot(b) > 1.0 - 1e-12
}
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
/// flattening that lands a little inside its tolerance.
const TURN_PER_TOL: f64 = 6.0;
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
for (d, limit) in limits.into_iter().flatten() {
let to = t.cross(d).atan2(t.dot(d));
lo = lo.max(to - limit);
hi = hi.min(to + limit);
}
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
if turn == 0.0 || !turn.is_finite() {
return t;
}
let (sin, cos) = turn.sin_cos();
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
}
/// Left-hand normal in y-down document space (for a path running +x it points +y).
pub fn normal(t: Vec2) -> Vec2 {
Vec2::new(-t.y, t.x)
}
impl Track {
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
/// when it comes from a curve, and `None` when it is a line of the path.
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
// comes from a curve.
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
for (p, c) in raw {
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
continue;
}
pts.push(p);
ends_curve.push(c);
}
let mut closing_curve = None;
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
pts.pop();
closing_curve = ends_curve.pop().flatten();
}
if pts.len() < 2 {
return None;
@@ -52,8 +95,11 @@ impl Track {
let closed = closed && pts.len() > 2;
if closed {
pts.push(pts[0]);
ends_curve.push(closing_curve);
}
let nseg = pts.len() - 1;
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
let mut cum = vec![0.0];
for i in 0..nseg {
@@ -62,34 +108,78 @@ impl Track {
let mut tangents = Vec::with_capacity(nseg + 1);
let mut corner = Vec::with_capacity(nseg + 1);
let cos_limit = CORNER_DEG.to_radians().cos();
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
for i in 0..=nseg {
let incoming = if i > 0 {
Some(dirs[i - 1])
Some(seg(i - 1))
} else if closed {
Some(dirs[nseg - 1])
Some(seg(nseg - 1))
} else {
None
};
let outgoing = if i < nseg {
Some(dirs[i])
Some(seg(i))
} else if closed {
Some(dirs[0])
Some(seg(0))
} else {
None
};
match (incoming, outgoing) {
(Some(a), Some(b)) => {
(Some((a, la, ca)), Some((b, lb, cb))) => {
corner.push(a.dot(b) < cos_limit);
tangents.push(unit(a + b));
tangents.push(match (ca, cb) {
// Between two chords of a flattened curve: each direction weighted by the
// length of the other chord, which is the tangent of the circle through
// the vertex and its two neighbors.
(true, true) => unit(a * lb + b * la),
// Where a line of the path meets a curve, the line's direction.
(false, true) => a,
(true, false) => b,
(false, false) => unit(a + b),
});
}
(a, b) => {
// An end of an open track (both `None` only for a track without segments).
corner.push(false);
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
}
}
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
// An open track's end on a curve continues the bend of its last chord: the tangent there
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
// the last three vertices.
if !closed && nseg >= 2 {
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
if !corner[inner] && curved[s_end] && curved[s_inner] {
let t = tangents[inner];
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
}
}
}
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
// circular arc. Next to a long chord the estimates above can turn much further (a
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
// curved chord whose end tangents turn further than that from it keeps to the chord.
let turn: Vec<f64> = (0..nseg)
.map(|j| match curve_tol.get(j) {
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
_ => 0.0,
})
.collect();
for (i, t) in tangents.iter_mut().enumerate() {
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
let sides = [incoming, outgoing];
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
continue;
}
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
}
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
}
pub fn len(&self) -> f64 {
@@ -135,11 +225,11 @@ impl Track {
let n = self.segments();
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
if s <= 0.0 && !self.closed {
let t = self.dirs[0];
let t = self.tangents[0];
return (self.verts[0] + t * s, t);
}
if s >= l && !self.closed {
let t = self.dirs[n - 1];
let t = self.tangents[n];
return (self.verts[n] + t * (s - l), t);
}
// Binary search the segment.
@@ -149,10 +239,44 @@ impl Track {
};
let seg = self.cum[i + 1] - self.cum[i];
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
let p = self.verts[i].lerp(self.verts[i + 1], u);
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
(p, unit(t0 + (t1 - t0) * u))
self.frame_in(i, u)
}
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
/// tangents, or the segment's direction at a corner.
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
let (&d, &c0, &c1, &t0, &t1) =
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
}
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
/// gives them. `i` must be below [`Self::segments`].
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
};
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
if aligned(t0, d) && aligned(t1, d) {
return (p0.lerp(p1, u), d);
}
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
// A line of the path, or a curved chord at a sharper turn than the curve can make
// there: the point stays on it, and the tangent turns across it toward the vertex
// tangents.
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
}
// On a chord of a flattened curve the frame follows the cubic through both vertices with
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
// meet those of the next segment at each vertex.
let (u2, u3) = (u * u, u * u * u);
let (m0, m1) = (t0 * seg, t1 * seg);
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
(p, unit(dp))
}
/// The point at arc length `s`, offset `d` along the left normal.
@@ -183,8 +307,8 @@ impl Track {
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
return false;
}
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
// those segments are part of the span too.
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
// against the end segment's direction below, so those segments are part of the span too.
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
let touched = (0..n).filter(|&i| {
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
@@ -193,9 +317,7 @@ impl Track {
let mut dir: Option<Vec2> = None;
let mut any = false;
for i in touched.chain(ends.into_iter().flatten()) {
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
else {
let Some((d, t0, t1)) = self.end_tangents(i) else {
return false;
};
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
@@ -203,11 +325,11 @@ impl Track {
}
dir = Some(d);
any = true;
// `frame` blends the two vertex tangents across the segment unless the vertex is a
// corner, where it uses the segment's own direction. So a neighbour outside the span
// can still bend the tangent inside it, and checking the directions alone would miss
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
// `frame` blends the two end tangents across a line, and follows a curve through them
// on a curved chord. So a neighbour outside the span can still bend the tangent
// inside it, and checking the directions alone would miss that: segments d, d, e
// leave vertex 2's tangent at unit(d + e).
if !aligned(t0, d) || !aligned(t1, d) {
return false;
}
}
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
let tol = tol.max(1e-4);
let mut out = vec![];
let mut cur: Vec<Point> = vec![];
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
let mut cur: Vec<(Point, Option<f64>)> = vec![];
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
if let Some(t) = Track::new(std::mem::take(cur), closed) {
out.push(t);
}
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
return out;
}
let mut els = vec![];
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
// pulls each element before it reports that element's lines, and raises the tolerance of a
// long curve as `vectorcraft_geom::flatten` describes.
let in_curve = std::cell::Cell::new(None);
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
let source = bp.iter().inspect(|el| {
let from = last.get();
let (curve, to) = match *el {
PathEl::MoveTo(p) => {
start.set(p);
(None, p)
}
PathEl::LineTo(p) => (None, p),
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
PathEl::ClosePath => (None, start.get()),
};
last.set(to);
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
});
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
vectorcraft_geom::flatten(source, tol, |el| {
if els.len() < MAX_FLATTENED {
els.push(el);
els.push((el, in_curve.get()));
}
});
for el in els {
for (el, from_curve) in els {
match el {
PathEl::MoveTo(p) => {
flush(&mut cur, false, &mut out);
cur.push(p);
cur.push((p, None));
}
PathEl::LineTo(p) => cur.push(p),
PathEl::LineTo(p) => cur.push((p, from_curve)),
PathEl::ClosePath => flush(&mut cur, true, &mut out),
_ => {}
}
@@ -368,6 +512,173 @@ mod tests {
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
}
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
/// stays on the line with the line's direction, and its tangent does not jump at the join.
#[test]
fn a_polylines_frame_stays_on_its_lines() {
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
// the vertex is not a corner.
let turn = 20f64.to_radians();
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
for curve in [false, true] {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
if curve {
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
} else {
bp.line_to((100.0 + c, s));
}
let t = &tracks(&bp, 0.05)[0];
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
let (p, tg) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
if curve {
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
}
}
if curve {
// The curve's first chord keeps to the chord rather than bending toward the line.
let (a, b) = (t.cum[1], t.cum[2]);
let (p, q) = (t.verts[1], t.verts[2]);
let mid = t.frame((a + b) / 2.0).0;
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
}
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
}
}
/// A curve of no length between two lines leaves them lines.
#[test]
fn a_curve_of_no_length_leaves_a_line_a_line() {
let turn = 20f64.to_radians();
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((100.0, 0.0));
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
let t = &tracks(&bp, 0.05)[0];
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
for at in [10.0, 50.0, 90.0] {
let (p, _) = t.frame(at);
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
}
}
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
#[test]
fn a_line_into_a_smooth_curve_keeps_its_direction() {
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
let t = &tracks(&bp, 0.05)[0];
for s in [10.0, 50.0, 90.0, 99.0] {
let (p, tg) = t.frame(s);
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
}
}
/// The handle length of a cubic quarter circle.
const K: f64 = 0.552_284_749_8;
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
/// of the line.
#[test]
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
let tol = 0.05;
for bend_first in [false, true] {
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
// radius 5 that turns toward +y.
let mut bp = BezPath::new();
if bend_first {
bp.move_to((-5.0, -5.0));
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
} else {
bp.move_to((0.0, 0.0));
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
}
let t = &tracks(&bp, tol)[0];
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
// line's stretch of the track.
let on_line: Vec<(Point, Vec2)> =
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
// Along the line the tangent turns by no more than the line's flattening allows.
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
}
}
/// A curve long enough that flattening raises its tolerance still has its frame follow the
/// curve between the vertices, not the chords.
#[test]
fn a_long_curve_flattened_coarser_is_still_followed() {
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
let r = 5.0e6;
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
let mut bp = BezPath::new();
bp.move_to((-100.0, 0.0));
bp.line_to((0.0, 0.0));
bp.curve_to(curve.p1, curve.p2, curve.p3);
let t = &tracks(&bp, 0.05)[0];
let worst = (1..400)
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
.fold(0.0, f64::max);
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
}
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
/// to its radius all the way round, the start included.
#[test]
fn a_closed_curves_frame_is_smooth_across_its_seam() {
let (r, tol) = (50.0, 0.05);
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
bp.close_path();
let t = &tracks(&bp, tol)[0];
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
for k in -20..=20 {
let (p, tg) = t.frame(k as f64 * 0.37);
let radial = p.to_vec2() / p.to_vec2().hypot();
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
}
}
/// A closed path whose last side is the implicit line back to the start keeps that line
/// straight.
#[test]
fn an_implicit_closing_line_is_not_a_curve() {
let r = 50.0;
let mut bp = BezPath::new();
bp.move_to((r, 0.0));
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
bp.close_path();
let t = &tracks(&bp, 0.05)[0];
assert!(t.closed);
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
let n = t.segments();
for u in [0.1, 0.5, 0.9] {
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
}
}
#[test]
fn closed_square_has_four_corners() {
let mut bp = BezPath::new();
+5 -16
View File
@@ -465,17 +465,8 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
bounds.windows(2).map(|w| (w[0], w[1])).collect()
}
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1, and
/// `width` the width (%) there.
fn art_on_run(
t: &Track,
(s0, s1): (f64, f64),
a: &ArtBrush,
(art, b): (&Node, Rect),
cross: f64,
width: f64,
widen: &dyn Fn(f64) -> f64,
) -> Option<Node> {
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
let l = s1 - s0;
if l <= 1e-9 {
return None;
@@ -483,10 +474,8 @@ fn art_on_run(
let w = b.width();
let (along, cross) = match a.scale {
ArtScale::Stretch => (AlongMap::linear(w, s0, s1), cross),
ArtScale::Proportional => {
let k = l / w;
(AlongMap::linear(w, s0, s1), k * width / 100.0)
}
// Scaled across as much as along, times the stroke weight and the width, as the other modes are.
ArtScale::Proportional => (AlongMap::linear(w, s0, s1), l / w * cross),
ArtScale::BetweenGuides { start, end } => {
let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w);
let (g0, g1) = (g0.min(g1), g0.max(g1));
@@ -528,7 +517,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
};
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
for run in runs {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, width, &widen) {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
out.push(n);
}
}
+1
View File
@@ -9,6 +9,7 @@ description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12
workspace = true
[dependencies]
craft-dxf = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
+4 -67
View File
@@ -1,50 +1,11 @@
//! The 256-colour index palette CAD apps share, generated rather than tabulated: indices 1–9 are
//! the standard colours, 10–249 run through 24 hues at five brightnesses each in a full and a
//! half-saturated tone, and 250–255 are greys.
//! The colour index palette is `craft_dxf::model::aci`; here are the indices each colour depth
//! of the writer may use.
use crate::ColorDepth;
/// The nine standard colours (index 7 shows white on a dark background and black on paper).
const STANDARD: [[u8; 3]; 9] =
[[255, 0, 0], [255, 255, 0], [0, 255, 0], [0, 255, 255], [0, 0, 255], [255, 0, 255], [255, 255, 255], [128, 128, 128], [192, 192, 192]];
/// The brightness of the five shades of each hue.
const SHADES: [f64; 5] = [1.0, 0.65, 0.5, 0.3, 0.15];
/// The RGB of colour index `i` (1–255; anything else is index 7's white).
pub fn aci_rgb(i: u8) -> [u8; 3] {
match i {
1..=9 => STANDARD[usize::from(i - 1)],
10..=249 => {
let hue = f64::from(i / 10 - 1) * 15.0;
let k = i % 10;
let v = SHADES[usize::from(k / 2)];
let pastel = k % 2 == 1;
hue_rgb(hue).map(|f| {
let f = if pastel { f + (1.0 - f) / 2.0 } else { f };
(255.0 * v * f).floor() as u8
})
}
250..=255 => {
let g = (51.0 + 204.0 * f64::from(i - 250) / 5.0).floor() as u8;
[g; 3]
}
_ => STANDARD[6],
}
}
/// The fully saturated, full-brightness colour of `hue` degrees as 0–1 channels.
fn hue_rgb(hue: f64) -> [f64; 3] {
let h = hue.rem_euclid(360.0) / 60.0;
let x = 1.0 - (h % 2.0 - 1.0).abs();
match h as u8 {
0 => [1.0, x, 0.0],
1 => [x, 1.0, 0.0],
2 => [0.0, 1.0, x],
3 => [0.0, x, 1.0],
4 => [x, 0.0, 1.0],
_ => [1.0, 0.0, x],
}
craft_dxf::model::aci::rgb(i)
}
/// The indices a colour depth may use (true colour: all of them, for the fallback index).
@@ -59,37 +20,13 @@ fn candidates(depth: ColorDepth) -> Box<dyn Iterator<Item = u8>> {
/// The index of `depth` nearest to `rgb` (squared RGB distance; ties go to the lower index).
/// Index 7 stands for both white and black, as CAD apps draw it in the background's contrast.
pub fn nearest_aci(rgb: [u8; 3], depth: ColorDepth) -> u8 {
let dist = |c: [u8; 3]| rgb.iter().zip(c).map(|(a, b)| (i32::from(*a) - i32::from(b)).pow(2)).sum::<i32>();
candidates(depth).min_by_key(|i| if *i == 7 { dist([255; 3]).min(dist([0; 3])) } else { dist(aci_rgb(*i)) }).unwrap_or(7)
craft_dxf::model::aci::nearest(rgb, candidates(depth))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_palette_matches_its_known_entries() {
let known: [(u8, [u8; 3]); 14] = [
(1, [255, 0, 0]),
(10, [255, 0, 0]),
(11, [255, 127, 127]),
(12, [165, 0, 0]),
(13, [165, 82, 82]),
(17, [76, 38, 38]),
(19, [38, 19, 19]),
(20, [255, 63, 0]),
(21, [255, 159, 127]),
(30, [255, 127, 0]),
(140, [0, 191, 255]),
(250, [51, 51, 51]),
(252, [132, 132, 132]),
(255, [255, 255, 255]),
];
for (i, rgb) in known {
assert_eq!(aci_rgb(i), rgb, "index {i}");
}
}
#[test]
fn nearest_index_by_depth() {
assert_eq!(nearest_aci([255, 0, 0], ColorDepth::Aci8), 1);
+20
View File
@@ -1024,6 +1024,26 @@ fn overlaps(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// Whether a plot draws nothing of `n` wherever it is, apart from what every export leaves out
/// (hidden objects, guides and template layers): an object at 0% opacity, a non-printing layer, a
/// placed image, a gradient mesh whose every point is at 0% opacity, or a path or compound path
/// without effects whose fills and strokes paint nothing. An image or a mesh in `doc` with a
/// visible Crop Marks effect, or with a Vector Halftone effect that makes dots, is not one of them.
/// A clipping path still clips when the plot draws nothing of it.
pub fn plots_nothing(doc: &Document, n: &Node) -> bool {
let unpainted = || n.appearance.effects.is_empty() && top_stroke(n).is_none() && top_fill(n).is_none();
let dots = || vectorcraft_effects::addons::halftone::halftone_art(doc, n).is_some_and(|g| g.children().is_some_and(|c| !c.is_empty()));
let adds_art = || vectorcraft_effects::has_crop_marks(n) || dots();
n.opacity <= 0.0
|| match &n.kind {
NodeKind::Layer { printable, .. } => !printable,
NodeKind::Image(_) => !adds_art(),
NodeKind::Mesh(m) => !adds_art() && m.points.iter().all(|p| p.opacity <= 0.0),
NodeKind::Path { .. } | NodeKind::Compound { .. } => unpainted(),
_ => false,
}
}
/// `nodes` (the children of a clipping container when `clipping`) without the layers and
/// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without
/// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn
+84
View File
@@ -177,6 +177,90 @@ fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() {
assert_eq!(t.matches("PD").count(), 3, "{t}");
}
/// `plots_nothing` picks the objects and layers that a plot draws nothing of: a path that paints
/// nothing, objects at 0% opacity, placed images, meshes with every point at 0% opacity and
/// non-printing layers, and not a painted path or a mesh.
#[test]
fn plots_nothing_picks_what_a_plot_draws_nothing_of() {
type Make = fn(&mut Document) -> Node;
let cases: [(&str, Make, bool); 7] = [
("stroked", |d| stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK), false),
("unpainted", |d| Node::path(d.alloc_id(), rect(10.0, 10.0, 40.0, 40.0), Appearance::basic(Paint::None, Paint::None, 1.0)), true),
(
"clear",
|d| {
let mut n = filled(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK);
n.opacity = 0.0;
n
},
true,
),
(
"image",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))
},
true,
),
(
"image with Crop Marks",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true });
n
},
false,
),
("mesh", |d| Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), false),
(
"clear mesh",
|d| {
let mut clear = mesh_at(10.0);
clear.points.iter_mut().for_each(|p| p.opacity = 0.0);
Node::new(d.alloc_id(), NodeKind::Mesh(clear))
},
true,
),
];
for (name, make, nothing) in cases {
let mut held = None;
let d = doc_with(|d| {
let n = make(d);
held = Some(n.clone());
vec![n]
});
let Some(n) = held else { panic!("{name}") };
assert_eq!(plots_nothing(&d, &n), nothing, "{name}");
assert_eq!(text(&plot(&d, &opts(&d))) == "IN;PU;SP0;", nothing, "{name}");
}
let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK)]);
let layer = d.layers[0].id;
assert!(!plots_nothing(&d, &d.layers[0]));
if let Some(NodeKind::Layer { printable, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
*printable = false;
}
assert!(plots_nothing(&d, &d.layers[0]));
assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;");
}
/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a
/// warning.
#[test]
+20 -19
View File
@@ -1,4 +1,4 @@
//! DXF import: an ASCII DXF drawing of any version as a document.
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
//!
//! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
@@ -10,7 +10,8 @@
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
//! them. What can't come in is listed in the warnings.
//!
//! - `reader`: the file's text, group codes, sections, tables, blocks and layouts.
//! - `reader`: what the import uses of the drawing `craft_dxf::model` reads: header, tables,
//! blocks and layouts.
//! - `entity`: entities to items (geometry and properties).
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
//! - `text`: text values to plain text.
@@ -31,9 +32,6 @@ use crate::{DxfVersion, INSUNITS, SCALE_RANGE};
/// Letter, the box Fit to Artboard fills unless told otherwise (points).
pub const FIT_TO: (f64, f64) = (612.0, 792.0);
/// Why a binary DXF can't be opened.
pub const BINARY: &str = "this is a binary DXF file, which can't be read: save it from the CAD app as an ASCII DXF and open that";
/// How a drawing comes in.
#[derive(Clone, Debug, PartialEq)]
pub struct ImportOptions {
@@ -104,15 +102,20 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
false
}
/// The pairs of a DXF file and where it is damaged (binary and DWG files are refused).
fn text(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>, String> {
if bytes.starts_with(reader::BINARY_SENTINEL) {
return Err(BINARY.into());
}
/// The tags of a DXF file and where it is damaged (DWG files are refused).
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") {
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as an ASCII DXF and open that".into());
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into());
}
Ok(reader::decode(bytes))
let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e {
craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(),
_ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(),
_ => "not a DXF drawing".to_string(),
})?;
if tags.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out"))))
}
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
@@ -161,9 +164,8 @@ fn units_name(code: i64) -> &'static str {
/// Read what `bytes` holds: its version, units, layouts and layers.
pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
let text = text(bytes)?;
let (pairs, _) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, _) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
@@ -180,7 +182,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
})
}
/// Import an ASCII DXF drawing with `o`.
/// Import a DXF drawing with `o`.
pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
let (w, h) = o.fit_to;
if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) {
@@ -191,9 +193,8 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
{
return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end()));
}
let text = text(bytes)?;
let (pairs, damaged) = reader::pairs(&text)?;
let d = reader::Drawing::read(&pairs);
let (tags, damaged) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
}
+180 -302
View File
@@ -7,9 +7,10 @@ use kurbo::{BezPath, PathEl};
use vectorcraft_doc::Justify;
use vectorcraft_geom::{Affine, Point, Vec2};
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
use super::curve::{self, Vertex};
use super::reader::{Groups, Pair, Record, groups, number};
use crate::aci::aci_rgb;
use super::reader::{aci_paper, point};
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
const DESCENT: f64 = 0.3;
@@ -25,21 +26,6 @@ const MAX_COORD: f64 = 1e12;
/// factor 1, the 1 to 10,000% horizontal scale the Character panel allows.
const SPAN_SCALE: (f64, f64) = (0.01, 100.0);
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u64) -> [u8; 3] {
match u8::try_from(i) {
Ok(7) | Err(_) => [0; 3],
Ok(i) => aci_rgb(i),
}
}
/// The true colour (group 420, `0xRRGGBB`) of an entity or layer.
pub(crate) fn true_color(g: &[Pair<'_>]) -> Option<[u8; 3]> {
let v = g.int(420)?;
let [_, r, gr, b] = u32::try_from(v & 0xFF_FFFF).ok()?.to_be_bytes();
Some([r, gr, b])
}
/// An entity's colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Col {
@@ -79,30 +65,30 @@ pub(crate) struct Props {
}
impl Props {
fn read(g: &[Pair<'_>]) -> Self {
let color = match (true_color(g), g.int(62)) {
(Some(rgb), _) => Col::Rgb(rgb),
(None, Some(0)) => Col::ByBlock,
(None, None | Some(256..)) => Col::ByLayer,
(None, Some(i)) => Col::Rgb(aci_paper(i.unsigned_abs())),
fn read(c: &model::Common) -> Self {
let color = match c.color {
model::Color::Rgb(rgb) => Col::Rgb(rgb),
model::Color::ByBlock => Col::ByBlock,
model::Color::ByLayer => Col::ByLayer,
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
};
let lineweight = match g.int(370) {
Some(-2) => Lw::ByBlock,
Some(-3) => Lw::Default,
Some(v @ 0..=211) => Lw::Hundredths(v as i32),
let lineweight = match c.lineweight {
model::Lineweight::ByBlock => Lw::ByBlock,
model::Lineweight::Default => Lw::Default,
model::Lineweight::Hundredths(v @ 0..=211) => Lw::Hundredths(i32::from(v)),
_ => Lw::ByLayer,
};
let alpha = match g.int(440) {
Some(v) if v & 0x0200_0000 != 0 => Alpha::Opacity((v & 0xFF) as f32 / 255.0),
Some(v) if v & 0x0100_0000 != 0 => Alpha::ByBlock,
_ => Alpha::ByLayer,
let alpha = match c.transparency {
model::Transparency::Alpha(a) => Alpha::Opacity(f32::from(a) / 255.0),
model::Transparency::ByBlock => Alpha::ByBlock,
model::Transparency::ByLayer => Alpha::ByLayer,
};
Self {
layer: g.name(8).unwrap_or("0").to_string(),
layer: c.layer.clone(),
color,
lineweight,
linetype: g.name(6).unwrap_or("BYLAYER").to_uppercase(),
ltscale: g.num(48).filter(|v| *v > 0.0).unwrap_or(1.0),
linetype: c.linetype.as_deref().unwrap_or("BYLAYER").to_uppercase(),
ltscale: c.ltscale,
alpha,
}
}
@@ -209,90 +195,87 @@ impl Converter {
}
/// The items of `records` (an entity section or a block), in drawing order.
pub fn items(&mut self, records: &[Record<'_>]) -> Vec<Item> {
pub fn items(&mut self, records: &[EntityRecord<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for group in groups(records) {
let Some(head) = group.first() else { continue };
for e in records {
let m = model::Entity::read(e);
// Invisible entities.
if head.g.int(60) == Some(1) {
if !m.common.visible {
continue;
}
match self.geom(head, group) {
match self.geom(e, &m) {
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
Some(geom) => out.push(Item { props: Props::read(head.g), geom }),
None if is_known(head.kind) => {}
None => self.skip(head.kind),
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
None if is_known(e.kind) => {}
None => self.skip(e.kind),
}
}
out
}
fn geom(&mut self, head: &Record<'_>, group: &[Record<'_>]) -> Option<Geom> {
let g = head.g;
fn geom(&mut self, e: &EntityRecord<'_>, m: &model::Entity) -> Option<Geom> {
let g = e.groups();
let path = |bp: BezPath| Some(Geom::Path { bp, fill: false, width: 0.0 });
match head.kind {
"LINE" => {
let ocs = ocs(m.common.extrusion);
match &m.kind {
model::EntityKind::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(g.point(10));
bp.line_to(g.point(11));
bp.move_to(point(*start));
bp.line_to(point(*end));
path(bp)
}
"CIRCLE" => path(transformed(curve::arc(g.point(10), g.num(40)?, 0.0, std::f64::consts::TAU)?, ocs(g))),
"ARC" => {
let (start, end) = (g.num_or(50, 0.0), g.num_or(51, 360.0));
let sweep = ccw_sweep(start, end);
path(transformed(curve::arc(g.point(10), g.num(40)?, start.to_radians(), sweep.to_radians())?, ocs(g)))
model::EntityKind::Circle { center, radius } => path(transformed(curve::arc(point(*center), *radius, 0.0, std::f64::consts::TAU)?, ocs)),
model::EntityKind::Arc { center, radius, start_angle, end_angle } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
path(transformed(curve::arc(point(*center), *radius, start_angle.to_radians(), sweep.to_radians())?, ocs))
}
"ELLIPSE" => path(ellipse(g)?),
"LWPOLYLINE" => lwpolyline(g),
"POLYLINE" => self.polyline(g, group.get(1..).unwrap_or(&[])),
"SPLINE" => path(spline(g)?),
"SOLID" | "TRACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
model::EntityKind::Ellipse { center, major, ratio, start, end } => {
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
}
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
model::EntityKind::Spline(s) => path(spline(s)?),
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
let [a, b, c, d] = corners.map(point);
// The corners zigzag: the outline runs 1, 2, 4, 3.
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs(g)), fill: true, width: 0.0 })
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
}
"3DFACE" => {
let [a, b, c, d] = [g.point(10), g.point(11), g.point(12), g.point_opt(13).unwrap_or(g.point(12))];
path(polygon(&[a, b, c, d]))
}
"HATCH" => self.hatch(g),
"TEXT" | "ATTRIB" => text(g, head.kind == "ATTRIB").map(Geom::Text),
"MTEXT" => mtext(g).map(Geom::Text),
"INSERT" => self.insert(g, group.get(1..).unwrap_or(&[])),
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
// A dimension draws the anonymous block of its lines, arrows and text.
"DIMENSION" => Some(Geom::Insert(InsertItem { block: g.name(2)?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })),
model::EntityKind::Dimension(d) => {
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
}
_ => None,
}
}
fn polyline(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let flags = g.int_or(70, 0);
if flags & (16 | 64) != 0 {
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
if p.is_mesh() || p.is_polyface() {
self.warn(MESHES);
return None;
}
// Spline frame control points and polyface faces aren't on the line.
let verts: Vec<Vertex> = rest
.iter()
.filter(|r| r.kind == "VERTEX" && r.g.int_or(70, 0) & (16 | 128) == 0)
.map(|r| Vertex { p: r.g.point(10), bulge: r.g.num_or(42, 0.0) })
.collect();
let bp = curve::polyline(&verts, flags & 1 != 0)?;
let verts: Vec<Vertex> =
p.vertices.iter().filter(|v| v.flags & (16 | 128) == 0).map(|v| Vertex { p: point(v.location), bulge: v.bulge }).collect();
let bp = curve::polyline(&verts, p.closed())?;
// 3D polylines are in world coordinates; 2D ones in their plane's.
let bp = if flags & 8 != 0 { bp } else { transformed(bp, ocs(g)) };
Some(Geom::Path { bp, fill: false, width: g.num_or(40, 0.0).max(0.0) })
let bp = if p.is_3d() { bp } else { transformed(bp, ocs) };
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
}
fn insert(&mut self, g: &[Pair<'_>], rest: &[Record<'_>]) -> Option<Geom> {
let block = g.name(2)?.to_uppercase();
let (sx, sy) = (g.num_or(41, 1.0), g.num_or(42, 1.0));
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
let [sx, sy, _] = ins.scale;
if sx.abs() < 1e-12 || sy.abs() < 1e-12 {
return None;
}
let place = ocs(g) * Affine::translate(g.point(10).to_vec2()) * Affine::rotate(g.num_or(50, 0.0).to_radians());
let (cols, rows) = (g.int_or(70, 1).max(1), g.int_or(71, 1).max(1));
let (cs, rs) = (g.num_or(44, 0.0), g.num_or(45, 0.0));
let place = ocs * Affine::translate(point(ins.insert).to_vec2()) * Affine::rotate(ins.rotation.to_radians());
let (cols, rows) = (ins.columns, ins.rows);
let (cs, rs) = (ins.column_spacing, ins.row_spacing);
let (cols, rows) = if cols.saturating_mul(rows) > MAX_CELLS {
self.warn(BIG_ARRAY);
(cols.min(MAX_CELLS), (MAX_CELLS / cols.min(MAX_CELLS)).max(1).min(rows))
@@ -312,27 +295,41 @@ impl Converter {
.flat_map(|r| (0..cols).map(move |c| (r, c)))
.map(|(r, c)| place * Affine::translate((c as f64 * cs, r as f64 * rs)) * Affine::scale_non_uniform(sx, sy))
.collect();
let attribs = self.items(rest);
let attribs = self.attribs(followers);
Some(Geom::Insert(InsertItem { block, cells, attribs }))
}
fn hatch(&mut self, g: &[Pair<'_>]) -> Option<Geom> {
let start = g.iter().position(|p| p.code == 91)?;
let count = g.get(start).and_then(|p| number(p.value)).filter(|n| *n >= 0.0)? as usize;
let mut c = Cursor { g, i: start + 1 };
/// An insert's attributes as text.
fn attribs(&mut self, followers: &[model::Record<'_>]) -> Vec<Item> {
let mut out = Vec::new();
for r in followers {
let c = model::Common::read(r.tags);
if !c.visible {
continue;
}
let a = model::Attrib::read("ATTRIB", r.tags);
match text(&a.text, &r.groups(), true, ocs(c.extrusion)) {
Some(t) if !in_range(&Geom::Text(t.clone())) => self.warn(FAR_AWAY),
Some(t) => out.push(Item { props: Props::read(&c), geom: Geom::Text(t) }),
None => {}
}
}
out
}
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
let mut bp = BezPath::new();
for _ in 0..count {
let Some(path) = boundary(&mut c) else { break };
for l in &h.loops {
let Some(path) = boundary(&l.path) else { break };
bp.extend(path);
}
if bp.elements().is_empty() {
return None;
}
let bp = transformed(bp, ocs(g));
let solid = g.int_or(70, 0) == 1;
if g.int_or(450, 0) == 1 {
let bp = transformed(bp, ocs);
if h.gradient.is_some() {
self.warn(GRADIENT_HATCH);
} else if !solid {
} else if !h.solid {
self.warn(PATTERN_HATCH);
return Some(Geom::Path { bp, fill: false, width: 0.0 });
}
@@ -401,217 +398,104 @@ fn polygon(pts: &[Point]) -> BezPath {
bp
}
/// The extrusion direction (210, 220, 230) of a planar entity, normalised.
fn extrusion(g: &[Pair<'_>]) -> [f64; 3] {
let n = [g.num_or(210, 0.0), g.num_or(220, 0.0), g.num_or(230, 1.0)];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len > 1e-12 && len.is_finite() { n.map(|v| v / len) } else { [0.0, 0.0, 1.0] }
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn unit(v: [f64; 3]) -> [f64; 3] {
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if len > 1e-12 { v.map(|x| x / len) } else { v }
}
/// A planar entity's coordinate system seen from above: its x and y axes in world space by the
/// arbitrary axis algorithm (identity for drawings in the world's plane; extruded along −z it
/// mirrors x).
fn ocs(g: &[Pair<'_>]) -> Affine {
let n = extrusion(g);
if n[2] > 1.0 - 1e-12 {
fn ocs(extrusion: model::Point) -> Affine {
let [ax, ay, _] = model::ocs_axes(extrusion);
if ax == [1.0, 0.0, 0.0] && ay == [0.0, 1.0, 0.0] {
return Affine::IDENTITY;
}
let ax = unit(if n[0].abs() < 1.0 / 64.0 && n[1].abs() < 1.0 / 64.0 { cross([0.0, 1.0, 0.0], n) } else { cross([0.0, 0.0, 1.0], n) });
let ay = unit(cross(n, ax));
Affine::new([ax[0], ax[1], ay[0], ay[1], 0.0, 0.0])
}
fn ellipse(g: &[Pair<'_>]) -> Option<BezPath> {
let centre = g.point(10);
let major = g.point(11).to_vec2();
let ratio = g.num_or(40, 1.0);
fn ellipse(extrusion: model::Point, centre: model::Point, major: model::Point, ratio: f64, start: f64, end: f64) -> Option<BezPath> {
let centre = point(centre);
let major = point(major).to_vec2();
if ratio <= 0.0 || major.hypot() < 1e-12 {
return None;
}
// The minor axis is the major one turned a quarter about the extrusion direction.
let n = extrusion(g);
let n = model::ocs_axes(extrusion)[2];
let m = cross(n, [major.x, major.y, 0.0]);
let minor = Vec2::new(m[0], m[1]) * ratio;
let (start, end) = (g.num_or(41, 0.0), g.num_or(42, std::f64::consts::TAU));
let sweep = ccw_sweep(start.to_degrees(), end.to_degrees()).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start, sweep)
}
fn lwpolyline(g: &[Pair<'_>]) -> Option<Geom> {
let mut verts: Vec<Vertex> = Vec::new();
let (mut widths, mut uniform) = (None, true);
for p in g {
match p.code {
10 => verts.push(Vertex { p: Point::new(number(p.value)?, 0.0), bulge: 0.0 }),
20 => verts.last_mut()?.p.y = number(p.value)?,
42 => verts.last_mut()?.bulge = number(p.value).unwrap_or(0.0),
40 | 41 => {
let w = number(p.value).unwrap_or(0.0);
uniform &= widths.is_none_or(|x: f64| (x - w).abs() < 1e-12);
widths = Some(w);
}
_ => {}
}
}
let bp = transformed(curve::polyline(&verts, g.int_or(70, 0) & 1 != 0)?, ocs(g));
let width = g.num(43).filter(|w| *w > 0.0).or(widths.filter(|_| uniform)).unwrap_or(0.0).max(0.0);
fn lwpolyline(p: &model::LwPolyline, ocs: Affine) -> Option<Geom> {
let verts: Vec<Vertex> = p.vertices.iter().map(|v| Vertex { p: Point::new(v.x, v.y), bulge: v.bulge }).collect();
let bp = transformed(curve::polyline(&verts, p.closed)?, ocs);
// One width for every vertex is the line's width.
let widths: Vec<f64> = p.vertices.iter().flat_map(|v| [v.start_width, v.end_width]).collect();
let uniform = widths.first().filter(|w| widths.iter().all(|x| (x - *w).abs() < 1e-12)).copied();
let width = Some(p.const_width).filter(|w| *w > 0.0).or(uniform).unwrap_or(0.0).max(0.0);
Some(Geom::Path { bp, fill: false, width })
}
/// The points at `code` (x) and `code + 10` (y), in order.
fn points(g: &[Pair<'_>], code: i32) -> Option<Vec<Point>> {
let mut out: Vec<Point> = Vec::new();
for p in g {
if p.code == code {
out.push(Point::new(number(p.value)?, 0.0));
} else if p.code == code + 10 {
out.last_mut()?.y = number(p.value)?;
}
}
Some(out)
}
fn spline(g: &[Pair<'_>]) -> Option<BezPath> {
let flags = g.int_or(70, 0);
let ctrl = points(g, 10)?;
let degree = usize::try_from(g.int_or(71, 3)).ok()?;
let knots: Vec<f64> = g.iter().filter(|p| p.code == 40).map(|p| number(p.value)).collect::<Option<_>>()?;
let weights: Vec<f64> = g.iter().filter(|p| p.code == 41).filter_map(|p| number(p.value)).collect();
let weights = (flags & 4 != 0 && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, &knots, &ctrl, weights)
fn spline(s: &model::Spline) -> Option<BezPath> {
let ctrl: Vec<Point> = s.control.iter().map(|p| point(*p)).collect();
let degree = usize::try_from(s.degree).ok()?;
let weights = (s.flags & 4 != 0 && s.weights.len() == ctrl.len()).then_some(s.weights.as_slice());
curve::nurbs(degree, &s.knots, &ctrl, weights)
.map(|mut path| {
if flags & 1 != 0 {
if s.flags & 1 != 0 {
path.close_path();
}
path
})
.or_else(|| curve::through(&points(g, 11)?, flags & 1 != 0))
}
/// Reads a hatch's boundary groups in order.
struct Cursor<'g, 'a> {
g: &'g [Pair<'a>],
i: usize,
}
impl Cursor<'_, '_> {
/// The next group's value when it has `code` (consumed).
fn opt(&mut self, code: i32) -> Option<&str> {
let p = self.g.get(self.i).filter(|p| p.code == code)?;
self.i += 1;
Some(p.value)
}
fn num(&mut self, code: i32) -> Option<f64> {
self.opt(code).and_then(number)
}
fn count(&mut self, code: i32) -> Option<usize> {
self.num(code).filter(|n| *n >= 0.0 && *n <= 1e7).map(|n| n as usize)
}
fn point(&mut self, code: i32) -> Option<Point> {
Some(Point::new(self.num(code)?, self.num(code + 10)?))
}
.or_else(|| curve::through(&s.fit.iter().map(|p| point(*p)).collect::<Vec<_>>(), s.flags & 1 != 0))
}
/// One hatch boundary loop, closed.
fn boundary(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
let flags = c.num(92)? as i64;
let mut bp = BezPath::new();
if flags & 2 != 0 {
let bulges = c.num(72).unwrap_or(0.0) != 0.0;
let _closed = c.opt(73);
let n = c.count(93)?;
let mut verts = Vec::with_capacity(n.min(4096));
for _ in 0..n {
let p = c.point(10)?;
let bulge = if bulges { c.num(42).unwrap_or(0.0) } else { 0.0 };
verts.push(Vertex { p, bulge });
fn boundary(path: &HatchPath) -> Option<BezPath> {
let xy = |p: &[f64; 2]| Point::new(p[0], p[1]);
match path {
HatchPath::Polyline { vertices, .. } => {
let verts: Vec<Vertex> = vertices.iter().map(|[x, y, b]| Vertex { p: Point::new(*x, *y), bulge: *b }).collect();
curve::polyline(&verts, true)
}
bp = curve::polyline(&verts, true)?;
} else {
let n = c.count(93)?;
for _ in 0..n {
let edge = edge(c)?;
append(&mut bp, &edge);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
}
// The boundary objects it was made from.
if let Some(n) = c.count(97) {
for _ in 0..n {
if c.opt(330).is_none() {
break;
}
}
}
Some(bp)
}
/// One edge of a hatch boundary.
fn edge(c: &mut Cursor<'_, '_>) -> Option<BezPath> {
match c.num(72)? as i64 {
1 => {
HatchPath::Edges(edges) => {
let mut bp = BezPath::new();
bp.move_to(c.point(10)?);
bp.line_to(c.point(11)?);
for e in edges {
let seg = match e {
HatchEdge::Line { start, end } => {
let mut bp = BezPath::new();
bp.move_to(xy(start));
bp.line_to(xy(end));
Some(bp)
}
HatchEdge::Arc { center, radius, start_angle, end_angle, ccw } => {
let sweep = ccw_sweep(*start_angle, *end_angle);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if *ccw { (*start_angle, sweep) } else { (-start_angle, -sweep) };
curve::arc(xy(center), *radius, start.to_radians(), sweep.to_radians())
}
HatchEdge::Ellipse { center, major, ratio, start_angle, end_angle, ccw } => {
let (centre, major) = (xy(center), xy(major).to_vec2());
let minor = Vec2::new(-major.y, major.x) * *ratio * if *ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(*start_angle, *end_angle).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start_angle.to_radians(), sweep)
}
HatchEdge::Spline { degree, rational, knots, control, weights, fit, .. } => {
let ctrl: Vec<Point> = control.iter().map(xy).collect();
let degree = usize::try_from(*degree).ok()?;
let weights = (*rational && weights.len() == ctrl.len()).then_some(weights.as_slice());
curve::nurbs(degree, knots, &ctrl, weights).or_else(|| curve::through(&fit.iter().map(xy).collect::<Vec<_>>(), false))
}
};
append(&mut bp, &seg?);
}
if bp.elements().is_empty() {
return None;
}
bp.close_path();
Some(bp)
}
2 => {
let (centre, r, start, end) = (c.point(10)?, c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let sweep = ccw_sweep(start, end);
// Clockwise arcs have their angles measured clockwise.
let (start, sweep) = if ccw { (start, sweep) } else { (-start, -sweep) };
curve::arc(centre, r, start.to_radians(), sweep.to_radians())
}
3 => {
let (centre, major, ratio, start, end) = (c.point(10)?, c.point(11)?.to_vec2(), c.num(40)?, c.num(50)?, c.num(51)?);
let ccw = c.num(73).unwrap_or(1.0) != 0.0;
let minor = Vec2::new(-major.y, major.x) * ratio * if ccw { 1.0 } else { -1.0 };
let sweep = ccw_sweep(start, end).to_radians();
curve::ellipse(Affine::new([major.x, major.y, minor.x, minor.y, centre.x, centre.y]), start.to_radians(), sweep)
}
4 => {
let degree = c.count(94)?;
let rational = c.num(73).unwrap_or(0.0) != 0.0;
let _periodic = c.opt(74);
let (nk, nc) = (c.count(95)?, c.count(96)?);
let knots: Vec<f64> = (0..nk).map(|_| c.num(40)).collect::<Option<_>>()?;
let mut ctrl = Vec::with_capacity(nc.min(4096));
let mut weights = Vec::with_capacity(nc.min(4096));
for _ in 0..nc {
ctrl.push(c.point(10)?);
weights.push(c.num(42).unwrap_or(1.0));
}
// Fit data (DXF 2010 and later): a count, then that many points. Older files have none,
// and the 97 that may follow is the boundary's count of source objects (then their
// handles), so it is only the fit count when it is 0 or points follow.
let fit_count = match (c.g.get(c.i), c.g.get(c.i + 1)) {
(Some(count), next) if count.code == 97 => number(count.value) == Some(0.0) || next.is_some_and(|p| p.code == 11),
_ => false,
};
let fit: Vec<Point> = match fit_count.then(|| c.count(97)).flatten() {
Some(n) => (0..n).map(|_| c.point(11)).collect::<Option<_>>()?,
None => vec![],
};
// Start and end tangents.
for code in [12, 13] {
c.point(code);
}
curve::nurbs(degree, &knots, &ctrl, rational.then_some(weights.as_slice())).or_else(|| curve::through(&fit, false))
}
_ => None,
}
}
@@ -643,18 +527,21 @@ fn baseline(v: i64, height: f64) -> f64 {
}
}
fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
if attrib && g.int_or(70, 0) & 1 != 0 {
/// TEXT, or an ATTRIB's text. The string is read from group 1 as written, so that the caret and
/// percent codes are turned into text once, by `super::text`.
fn text(t: &model::Text, g: &Groups<'_>, attrib: bool, ocs: Affine) -> Option<TextItem> {
if attrib && g.i_or(70, 0) & 1 != 0 {
return None;
}
let s = super::text::plain(g.raw(1)?);
let s = super::text::plain(&g.s(1)?);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let (h, v) = (g.int_or(72, 0), g.int_or(if attrib { 74 } else { 73 }, 0));
let (p1, p2) = (g.point(10), g.point_opt(11));
let mut angle = g.num_or(50, 0.0).to_radians();
let height = Some(t.height).filter(|h| *h > 0.0)?;
// An ATTRIB's 73 is its field length: its vertical alignment is 74.
let (h, v) = (t.halign, if attrib { g.i_or(74, 0) } else { t.valign });
let (p1, p2) = (point(t.insert), t.align.map(point));
let mut angle = t.rotation.to_radians();
let mut span = None;
// Aligned and fit text run from the first point to the second.
let anchor = match (h, p2) {
@@ -674,33 +561,36 @@ fn text(g: &[Pair<'_>], attrib: bool) -> Option<TextItem> {
_ => Justify::Left,
};
let v = if h == 4 { 2 } else { v };
let flags = g.int_or(71, 0);
let flags = t.generation;
let mirror = Affine::scale_non_uniform(if flags & 2 != 0 { -1.0 } else { 1.0 }, if flags & 4 != 0 { -1.0 } else { 1.0 });
let xf = ocs(g) * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
let xf = ocs * Affine::translate(anchor.to_vec2()) * Affine::rotate(angle) * mirror * Affine::translate((0.0, baseline(v, height)));
Some(TextItem {
text: s,
height,
xf,
width: g.num(41).filter(|w| *w > 0.0).unwrap_or(1.0),
width: Some(t.width_factor).filter(|w| *w > 0.0).unwrap_or(1.0),
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
style: t.style.to_uppercase(),
family: None,
leading: None,
span,
})
}
fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1).
let raw: String = g.iter().filter(|p| p.code == 3).map(|p| p.value).chain(g.raw(1)).collect();
/// MTEXT. The contents are read from groups 3 and 1 as written, as for [`text`].
fn mtext(t: &model::MText, tags: &[craft_dxf::Tag]) -> Option<TextItem> {
// The text comes in 250-character chunks (3) before the last (1), up to an embedded object.
let (own, _) = model::text::split_embedded(tags);
let g = Groups(own);
let raw: String = own.iter().filter(|t| t.code == 3).map(craft_dxf::Tag::str).chain(g.s(1)).collect();
let (s, family) = super::text::mtext(&raw);
if s.trim().is_empty() {
return None;
}
let height = g.num(40).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * g.num(44).filter(|f| *f > 0.0).unwrap_or(1.0);
let height = Some(t.height).filter(|h| *h > 0.0)?;
let leading = height * LINE_SPACING * Some(t.line_spacing).filter(|f| *f > 0.0).unwrap_or(1.0);
let lines = s.lines().count().max(1) as f64;
let attach = g.int_or(71, 1).clamp(1, 9) - 1;
let attach = i64::from(t.attach) - 1;
let justify = [Justify::Left, Justify::Center, Justify::Right].get((attach % 3) as usize).copied().unwrap_or_default();
// The first baseline below the attachment point: under the top, around the middle, above
// the bottom of the lines.
@@ -710,18 +600,6 @@ fn mtext(g: &[Pair<'_>]) -> Option<TextItem> {
1 => total / 2.0 - height,
_ => (lines - 1.0) * leading,
};
let direction = g.point_opt(11).map(|p| p.to_vec2()).filter(|d| d.hypot() > 1e-12);
let angle = direction.map_or_else(|| g.num_or(50, 0.0), |d| d.atan2());
let xf = Affine::translate(g.point(10).to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, first));
Some(TextItem {
text: s,
height,
xf,
width: 1.0,
justify,
style: g.name(7).unwrap_or("STANDARD").to_uppercase(),
family,
leading: Some(leading),
span: None,
})
let xf = Affine::translate(point(t.insert).to_vec2()) * Affine::rotate(t.angle()) * Affine::translate((0.0, first));
Some(TextItem { text: s, height, xf, width: 1.0, justify, style: t.style.to_uppercase(), family, leading: Some(leading), span: None })
}
+68 -331
View File
@@ -1,156 +1,14 @@
//! Reading an ASCII DXF file: its text, the group-code pairs, and what the import uses of its
//! sections (header variables; the layer, linetype, text style and block record tables; the
//! blocks; the entities; the layouts).
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
//! linetype and text style tables; the blocks; the entities; the layouts.
use std::borrow::Cow;
use std::collections::HashMap;
use craft_dxf::model::{self, EntityRecord};
use vectorcraft_geom::Point;
/// The most group-code pairs a drawing may hold (about 300 MB of DXF).
const MAX_PAIRS: usize = 20_000_000;
/// The first bytes of a binary DXF file (its format's signature).
pub const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\x00";
/// One group: its code and its value as written.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Pair<'a> {
pub code: i32,
pub value: &'a str,
}
/// Values of a run of pairs by group code.
pub(crate) trait Groups<'a> {
/// The value of the first `code`, as written.
fn raw(&self, code: i32) -> Option<&'a str>;
/// The first `code` as a name (trimmed, never empty).
fn name(&self, code: i32) -> Option<&'a str> {
self.raw(code).map(str::trim).filter(|s| !s.is_empty())
}
/// The first `code` as a finite number.
fn num(&self, code: i32) -> Option<f64> {
self.raw(code).and_then(number)
}
fn num_or(&self, code: i32, default: f64) -> f64 {
self.num(code).unwrap_or(default)
}
/// The first `code` as a whole number.
fn int(&self, code: i32) -> Option<i64> {
self.raw(code).and_then(integer)
}
fn int_or(&self, code: i32, default: i64) -> i64 {
self.int(code).unwrap_or(default)
}
/// The point at `code` (x) and `code + 10` (y); 0 for what is missing.
fn point(&self, code: i32) -> Point {
Point::new(self.num_or(code, 0.0), self.num_or(code + 10, 0.0))
}
/// [`Groups::point`] when its x is given.
fn point_opt(&self, code: i32) -> Option<Point> {
self.num(code).map(|x| Point::new(x, self.num_or(code + 10, 0.0)))
}
}
impl<'a> Groups<'a> for [Pair<'a>] {
fn raw(&self, code: i32) -> Option<&'a str> {
self.iter().find(|p| p.code == code).map(|p| p.value)
}
}
/// A finite number (`1e999`, `NaN` and junk are none).
pub(crate) fn number(s: &str) -> Option<f64> {
s.trim().parse::<f64>().ok().filter(|v| v.is_finite())
}
/// A whole number; some writers put integers as `1.0`.
pub(crate) fn integer(s: &str) -> Option<i64> {
let s = s.trim();
s.parse::<i64>().ok().or_else(|| number(s).filter(|v| v.abs() < 9.0e15 && v.fract() == 0.0).map(|v| v as i64))
}
/// One object: its type (the value of its `0` group) and the groups up to the next object.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Record<'a> {
pub kind: &'a str,
pub g: &'a [Pair<'a>],
}
/// The text of a DXF file: UTF-8 (DXF 2007 and later), else the Windows code page older versions
/// write (a byte order mark is dropped).
pub(crate) fn decode(bytes: &[u8]) -> Cow<'_, str> {
let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
match std::str::from_utf8(bytes) {
Ok(s) => Cow::Borrowed(s),
Err(_) => Cow::Owned(bytes.iter().map(|b| windows_1252(*b)).collect()),
}
}
/// A byte of the Windows Western code page.
fn windows_1252(b: u8) -> char {
const HIGH: [char; 32] = [
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8D}', 'Ž', '\u{8F}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—',
'˜', '™', 'š', '›', 'œ', '\u{9D}', 'ž', 'Ÿ',
];
match b {
0x80..=0x9F => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or('?'),
_ => char::from(b),
}
}
/// The group-code pairs of `text`, up to `0 EOF`. A line that isn't a group code ends the
/// reading: what came before is kept and the second value says where the file is damaged.
pub(crate) fn pairs(text: &str) -> Result<(Vec<Pair<'_>>, Option<String>), String> {
let mut out = Vec::new();
let mut lines = text.lines().enumerate();
let mut damaged = None;
while let Some((n, code)) = lines.next() {
let c = code.trim();
if c.is_empty() && out.is_empty() {
continue;
}
let Ok(code) = c.parse::<i32>() else {
damaged = Some(format!("the file is damaged at line {}: what follows is left out", n + 1));
break;
};
let value = lines.next().map_or("", |(_, v)| v);
if code == 0 && value.trim() == "EOF" {
break;
}
if out.len() >= MAX_PAIRS {
return Err("the drawing is too large to open".into());
}
out.push(Pair { code, value });
}
if out.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((out, damaged))
}
/// The objects in `pairs`: each from a `0` group up to the next.
fn records<'a>(pairs: &'a [Pair<'a>]) -> Vec<Record<'a>> {
let mut out = Vec::new();
let mut start: Option<usize> = None;
for (i, p) in pairs.iter().enumerate() {
if p.code == 0 {
if let Some(s) = start {
out.extend(record(pairs, s, i));
}
start = Some(i);
}
}
if let Some(s) = start {
out.extend(record(pairs, s, pairs.len()));
}
out
}
fn record<'a>(pairs: &'a [Pair<'a>], start: usize, end: usize) -> Option<Record<'a>> {
let kind = pairs.get(start)?.value.trim();
Some(Record { kind, g: pairs.get(start + 1..end)? })
}
/// The header variables the import reads.
#[derive(Clone, Debug, Default)]
pub(crate) struct Header {
@@ -186,7 +44,7 @@ pub(crate) struct LayerDef {
pub(crate) struct BlockDef<'a> {
pub name: String,
pub base: Point,
pub records: Vec<Record<'a>>,
pub records: Vec<EntityRecord<'a>>,
/// A reference to another drawing (its art isn't in this file).
pub xref: bool,
}
@@ -218,97 +76,51 @@ pub(crate) struct Drawing<'a> {
/// Blocks by upper-case name.
pub blocks: HashMap<String, BlockDef<'a>>,
/// The ENTITIES section.
pub entities: Vec<Record<'a>>,
pub entities: Vec<EntityRecord<'a>>,
/// Model space first, then the paper layouts in tab order.
pub layouts: Vec<LayoutDef>,
/// How many sections the file has (none: not a drawing).
pub sections: usize,
}
impl<'a> Drawing<'a> {
/// Read the sections of `pairs`.
pub fn read(pairs: &'a [Pair<'a>]) -> Self {
let mut d = Drawing { header: Header { ltscale: 1.0, lwdefault: 25, ..Header::default() }, ..Drawing::default() };
let all = records(pairs);
let mut section: Option<&str> = None;
let (mut tables, mut blocks, mut objects) = (vec![], vec![], vec![]);
for r in all {
match (r.kind, section) {
("SECTION", _) => {
d.sections += 1;
section = r.g.name(2);
if section == Some("HEADER") {
d.header = header(r.g);
}
}
("ENDSEC", _) => section = None,
(_, Some("TABLES")) => tables.push(r),
(_, Some("BLOCKS")) => blocks.push(r),
(_, Some("ENTITIES")) => d.entities.push(r),
(_, Some("OBJECTS")) => objects.push(r),
_ => {}
}
}
let mut block_records = HashMap::new();
let mut table = "";
for r in &tables {
match r.kind {
"TABLE" => table = r.g.name(2).unwrap_or(""),
"LAYER" if table == "LAYER" => {
if let Some(l) = layer(r.g) {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(l);
}
}
"LTYPE" if table == "LTYPE" => {
if let Some(name) = r.g.name(2) {
let pattern: Vec<f64> = r.g.iter().filter(|p| p.code == 49).filter_map(|p| number(p.value)).collect();
d.linetypes.insert(name.to_uppercase(), pattern);
}
}
"STYLE" if table == "STYLE" => {
if let Some(name) = r.g.name(2) {
d.styles.insert(name.to_uppercase(), font_family(r.g));
}
}
"BLOCK_RECORD" if table == "BLOCK_RECORD" => {
if let (Some(h), Some(name)) = (r.g.name(5), r.g.name(2)) {
block_records.insert(h.to_uppercase(), name.to_uppercase());
}
}
_ => {}
}
}
d.read_blocks(&blocks, &mut block_records);
d.layouts = layouts(&objects, &block_records, &d.entities);
d
}
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
pub(crate) fn aci_paper(i: u8) -> [u8; 3] {
if i == 7 { [0; 3] } else { model::aci::rgb(i) }
}
fn read_blocks(&mut self, records: &[Record<'a>], block_records: &mut HashMap<String, String>) {
let mut current: Option<BlockDef<'a>> = None;
for r in records {
match r.kind {
"BLOCK" => {
let name = r.g.name(2).or_else(|| r.g.name(3)).unwrap_or("").to_string();
// R13+ blocks name their block record: layouts find their block through it.
if let Some(owner) = r.g.name(330) {
block_records.entry(owner.to_uppercase()).or_insert_with(|| name.to_uppercase());
}
let xref = r.g.int_or(70, 0) & 4 != 0;
current = Some(BlockDef { name, base: r.g.point(10), records: vec![], xref });
}
"ENDBLK" => {
if let Some(b) = current.take().filter(|b| !b.name.is_empty()) {
self.blocks.insert(b.name.to_uppercase(), b);
}
}
_ => {
if let Some(b) = &mut current {
b.records.push(*r);
}
}
}
impl<'a> Drawing<'a> {
/// What the import uses of `doc`.
pub fn read(doc: model::Document<'a>) -> Self {
let h = &doc.header;
let header = Header {
acadver: h.acadver().unwrap_or_default(),
insunits: h.insunits(),
measurement: h.measurement(),
ltscale: h.ltscale(),
lwdefault: i32::from(h.lwdefault()),
};
let mut d = Drawing { header, sections: doc.sections, ..Drawing::default() };
for l in doc.layers() {
d.layer_index.entry(l.name.to_uppercase()).or_insert(d.layers.len());
d.layers.push(layer(l));
}
for lt in doc.linetypes() {
d.linetypes.insert(lt.name.to_uppercase(), lt.pattern.iter().map(|e| e.length).collect());
}
for st in doc.text_styles().into_iter().filter(|s| !s.name.is_empty()) {
d.styles.insert(st.name.to_uppercase(), st.family().unwrap_or_default());
}
let block_names = doc.block_names();
d.layouts = layouts(&doc, &block_names);
for b in doc.blocks {
if b.name.is_empty() {
continue;
}
let def = BlockDef { name: b.name.to_string(), base: point(b.base()), xref: b.flags() & 4 != 0, records: b.entities };
d.blocks.insert(b.name.to_uppercase(), def);
}
d.entities = doc.entities;
d
}
/// The layout named `name` (any case; `model` is model space).
@@ -317,7 +129,7 @@ impl<'a> Drawing<'a> {
}
/// The entity records of `layout`.
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<Record<'a>> {
pub fn layout_records(&self, layout: &LayoutDef) -> Vec<EntityRecord<'a>> {
let block = |name: &str| self.blocks.get(name).map(|b| b.records.clone()).unwrap_or_default();
// The active paper layout keeps its art in the ENTITIES section, flagged paper space.
let (block_name, paper) = match &layout.block {
@@ -325,7 +137,7 @@ impl<'a> Drawing<'a> {
Some(b) if b == PAPER_BLOCK => (PAPER_BLOCK, true),
Some(b) => return block(b),
};
let mut out: Vec<Record<'a>> = groups(&self.entities).filter(|g| in_paper_space(g) == paper).flatten().copied().collect();
let mut out: Vec<EntityRecord<'a>> = self.entities.iter().filter(|e| e.paper_space() == paper).cloned().collect();
out.extend(block(block_name));
out
}
@@ -336,111 +148,47 @@ impl<'a> Drawing<'a> {
}
}
/// Is an entity (its first record) in paper space?
fn in_paper_space(group: &[Record<'_>]) -> bool {
group.first().is_some_and(|r| r.g.int(67) == Some(1))
pub(crate) fn point(p: model::Point) -> Point {
Point::new(p[0], p[1])
}
/// The entities of `records`, each with the records that belong to it (a polyline's vertices,
/// an insert's attributes, and the SEQEND closing them).
pub(crate) fn groups<'r, 'a>(records: &'r [Record<'a>]) -> impl Iterator<Item = &'r [Record<'a>]> {
let mut i = 0;
std::iter::from_fn(move || {
let start = i;
let head = records.get(start)?;
i += 1;
if matches!(head.kind, "POLYLINE" | "INSERT") {
while let Some(r) = records.get(i) {
match r.kind {
"VERTEX" | "ATTRIB" => i += 1,
"SEQEND" => {
i += 1;
break;
}
_ => break,
}
}
}
records.get(start..i)
})
}
fn header(g: &[Pair<'_>]) -> Header {
let mut h = Header { ltscale: 1.0, lwdefault: 25, ..Header::default() };
let mut var = "";
for p in g {
if p.code == 9 {
var = p.value.trim();
continue;
}
match (var, p.code) {
("$ACADVER", 1) => h.acadver = p.value.trim().to_string(),
("$INSUNITS", 70) => h.insunits = integer(p.value).unwrap_or(0),
("$MEASUREMENT", 70) => h.measurement = integer(p.value),
("$LTSCALE", 40) => h.ltscale = number(p.value).filter(|v| *v > 0.0).unwrap_or(1.0),
("$LWDEFAULT", 370) => h.lwdefault = integer(p.value).and_then(|v| i32::try_from(v).ok()).filter(|v| *v >= 0).unwrap_or(25),
_ => {}
}
}
h
}
fn layer(g: &[Pair<'_>]) -> Option<LayerDef> {
let name = g.name(2)?.to_string();
let aci = g.int_or(62, 7);
let flags = g.int_or(70, 0);
let rgb = super::entity::true_color(g).unwrap_or_else(|| super::entity::aci_paper(aci.unsigned_abs()));
Some(LayerDef {
fn layer(l: model::Layer) -> LayerDef {
let rgb = match l.color {
model::Color::Rgb(rgb) => rgb,
model::Color::Index(i) => aci_paper(i),
model::Color::ByLayer | model::Color::ByBlock => aci_paper(7),
};
LayerDef {
// CAD apps never plot this layer of dimension points.
plot: g.int_or(290, 1) != 0 && !name.eq_ignore_ascii_case("Defpoints"),
name,
plot: l.plot && !l.name.eq_ignore_ascii_case("Defpoints"),
rgb,
hidden: aci < 0 || flags & 1 != 0,
locked: flags & 4 != 0,
linetype: g.name(6).unwrap_or("CONTINUOUS").to_uppercase(),
lineweight: g.int(370).and_then(|v| i32::try_from(v).ok()).unwrap_or(-3),
})
}
/// A text style's font family: the one 2000-and-later files name, else the font file's name
/// (TrueType); CAD fonts (`.shx`) have none.
fn font_family(g: &[Pair<'_>]) -> String {
if let Some(i) = g.iter().position(|p| p.code == 1001 && p.value.trim() == "ACAD")
&& let Some(f) = g.get(i + 1..).and_then(|rest| rest.name(1000))
{
return f.to_string();
}
let file = g.name(3).unwrap_or("");
let path = std::path::Path::new(file);
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"ttf" | "otf" | "ttc" => path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(),
_ => String::new(),
hidden: !l.on || l.frozen,
locked: l.locked,
linetype: l.linetype.to_uppercase(),
lineweight: i32::try_from(l.lineweight.to_dxf()).unwrap_or(-3),
name: l.name,
}
}
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
/// The most bytes of layout and block names the layouts keep together. Each layout keeps its own
/// copy of its block's name, so many layouts naming one long block name multiplied it; real
/// drawings have a few dozen layouts with short names.
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, entities: &[Record<'_>]) -> Vec<LayoutDef> {
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
let mut paper: Vec<(i64, LayoutDef)> = vec![];
let mut seen = std::collections::HashSet::new();
let mut name_bytes = 0usize;
for r in objects.iter().filter(|r| r.kind == "LAYOUT") {
// The layout's own groups follow its subclass marker.
let own = r.g.iter().position(|p| p.code == 100 && p.value.trim() == "AcDbLayout").and_then(|i| r.g.get(i + 1..)).unwrap_or(&[]);
let Some(name) = own.name(1) else { continue };
let block = own.name(330).and_then(|h| block_records.get(&h.to_uppercase()));
if name.eq_ignore_ascii_case(MODEL) || block.map(String::as_str) == Some(MODEL_BLOCK) {
for l in doc.layouts() {
let block = l.block_record.and_then(|h| block_names.get(&h)).map(|n| n.to_uppercase());
if l.name.eq_ignore_ascii_case(MODEL) || block.as_deref() == Some(MODEL_BLOCK) {
continue;
}
let Some(block) = block else { continue };
let key = name.to_ascii_lowercase();
let cost = name.len() + block.len();
let key = l.name.to_ascii_lowercase();
let cost = l.name.len() + block.len();
// A layout past the allowance is skipped alone: a later short one is still offered, and a
// skipped one reserves neither its name nor its bytes.
if seen.contains(&key) || name_bytes.saturating_add(cost) > MAX_LAYOUT_NAME_BYTES {
@@ -448,22 +196,11 @@ fn layouts(objects: &[Record<'_>], block_records: &HashMap<String, String>, enti
}
seen.insert(key);
name_bytes += cost;
paper.push((own.int_or(71, i64::MAX), LayoutDef { name: name.to_string(), block: Some(block.clone()) }));
paper.push((l.tab_order, LayoutDef { name: l.name, block: Some(block) }));
}
paper.sort_by_key(|(order, _)| *order);
if paper.is_empty() && groups(entities).any(in_paper_space) {
if paper.is_empty() && doc.entities.iter().any(EntityRecord::paper_space) {
paper.push((1, LayoutDef { name: "Layout1".into(), block: Some(PAPER_BLOCK.into()) }));
}
std::iter::once(LayoutDef { name: MODEL.into(), block: None }).chain(paper.into_iter().map(|(_, l)| l)).collect()
}
#[cfg(test)]
mod tests {
use super::integer;
#[test]
fn integer_rejects_fractional_float_values() {
assert_eq!(integer("1.0"), Some(1));
assert_eq!(integer("1.9"), None);
}
}
+8 -4
View File
@@ -997,7 +997,12 @@ fn binary_dwg_damaged_and_foreign_files() {
binary.extend([0u8; 40]);
assert!(is_dxf(&binary));
let e = import(&binary, &ImportOptions::default()).unwrap_err();
assert!(e.contains("binary DXF") && e.contains("ASCII"), "{e}");
assert!(e.contains("binary DXF") && e.contains("damaged"), "{e}");
// A binary DXF opens as its ASCII form does.
let ascii = entities(LINE);
let tags = craft_dxf::parse(&ascii).unwrap();
let r = open(&craft_dxf::write_binary(&tags, true), &points());
assert_eq!(leaves(&r.document).len(), 1);
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
for junk in [&b""[..], b"hello", b"<svg/>", b"999\nnote\n"] {
@@ -1166,9 +1171,8 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
let one = [(0, "INSERT"), (8, "0"), (2, "NOPE"), (10, "0"), (20, "0"), (70, "100"), (71, "100"), (44, "1"), (45, "1")];
let e: Vec<(i32, &str)> = (0..3000).flat_map(|_| one).collect();
let bytes = entities(&e);
let text = reader::decode(&bytes);
let (pairs, _) = reader::pairs(&text).unwrap();
let d = reader::Drawing::read(&pairs);
let tags = craft_dxf::parse(&bytes).unwrap();
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
let model = d.layout("Model").or(d.layouts.first()).unwrap();
let mut conv = entity::Converter::default();
let items = conv.items(&d.layout_records(model));
+6 -4
View File
@@ -1,5 +1,5 @@
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an
//! HP-GL/2 plot file reader and writer.
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
//!
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
@@ -11,7 +11,7 @@
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`].
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
//!
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
@@ -428,7 +428,9 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
return Err("the export region is not finite".into());
}
let baked = vectorcraft_effects::bake_document(doc);
// Symbols' art is placed without clipping, as the scene places it.
let baked =
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
}
+1 -1
View File
@@ -683,7 +683,7 @@ impl<'a> Scene<'a> {
{
// Symbols holding instances of symbols are written in full for each instance,
// empty or not: every instance's art counts against one budget for the export.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
let count = art.count_with_masks() as u64;
// Counted as `place_symbol_art_unclipped` places it: no clip groups.
let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc));
+38
View File
@@ -1395,6 +1395,44 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
}
/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
#[test]
fn a_stained_instance_is_written_in_its_stained_color() {
let mut d = doc_with(|d| {
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((30.0, 30.0)) });
n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
vec![n]
});
let art = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
let out = export(&d, &opts(&d)).unwrap();
let colors: Vec<Option<String>> = entities(&out).iter().map(|e| get(e, 420).map(str::to_string)).collect();
assert!(!colors.is_empty() && colors.iter().all(|c| c.as_deref() == Some("255")), "{colors:?}");
}
#[test]
fn symbol_art_effects_are_written_where_they_draw() {
// A line and the symbol's line below it, each moved 100 pt right by a Transform effect, start
// at the same x.
let moved = |mut n: Node| {
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "distort.transform".into(),
params: serde_json::json!({"moveH": 100.0}),
visible: true,
});
n
};
let mut d = doc_with(|d| {
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
vec![moved(line), Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })]
});
let art = path(&mut d, shapes::line((10.0, 40.0).into(), (20.0, 40.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) });
let starts: Vec<f64> = entities(&export(&d, &opts(&d)).unwrap()).iter().map(|e| all(e, 10).into_iter().fold(f64::INFINITY, f64::min)).collect();
assert_eq!(starts.len(), 2, "{starts:?}");
assert!((starts[0] - starts[1]).abs() < 1e-6, "{starts:?}");
}
#[test]
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
+108 -14
View File
@@ -2,18 +2,23 @@
//! gamut checks and soft-proof transforms.
//!
//! * **RGB working spaces** are ICC matrix/shaper profiles via [`moxcms`] (sRGB, Wide Gamut RGB
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB.
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last ([`display`]).
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
//! [`crate::Color::to_rgb`] uses them. [`with_active`] puts other settings in their place on one
//! thread, as for a document drawn through its own profiles ([`for_document`]). Code that needs
//! deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod display;
pub mod generic;
pub mod icc;
pub mod lab;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
@@ -531,7 +536,7 @@ impl Cms {
}
}
/// Gamut warning: can this colour be printed in the working CMYK space?
/// Gamut warning: can this color be printed in this context's CMYK space?
pub fn out_of_gamut(&self, c: &Color) -> bool {
self.gamut_error(c) > GAMUT_THRESHOLD
}
@@ -908,9 +913,32 @@ static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
thread_local! {
/// The settings [`with_active`] put in place of the active settings on this thread.
static SCOPED: RefCell<Option<Arc<Cms>>> = const { RefCell::new(None) };
/// [`SCOPED`]'s flags for the fast paths: [`SCOPED_SET`] while it is set, [`SCOPED_SRGB`] when
/// its RGB space is sRGB, and [`SCOPED_DEVICE`] when its CMYK space is device CMYK.
static SCOPED_FLAGS: Cell<u8> = const { Cell::new(0) };
}
const SCOPED_SET: u8 = 1;
const SCOPED_SRGB: u8 = 2;
const SCOPED_DEVICE: u8 = 4;
/// The active color-management context: the working settings, with the profiles
/// [`use_document_profiles`] last put in place of the working spaces.
/// [`use_document_profiles`] last put in place of the working spaces. Inside [`with_active`] on
/// this thread: the settings it was given.
pub fn active() -> Arc<Cms> {
if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0
&& let Some(c) = SCOPED.with(|s| s.borrow().clone())
{
return c;
}
installed()
}
/// The active settings of the process, as [`use_document_profiles`] or [`set_active`] last put them
/// in place.
fn installed() -> Arc<Cms> {
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
}
@@ -952,14 +980,8 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
/// the active settings changed.
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
let working = working();
let mut st = working.settings.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
if st == active().settings {
let st = document_settings(&working.settings, rgb, cmyk);
if st == installed().settings {
return false;
}
if st == working.settings {
@@ -974,6 +996,72 @@ pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
true
}
/// The working settings `working` with the profiles a document is assigned (`None`: none) in place
/// of the working spaces, as [`use_document_profiles`] takes them.
fn document_settings(working: &ColorSettings, rgb: Option<&str>, cmyk: Option<&str>) -> ColorSettings {
let mut st = working.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
st
}
/// How many contexts [`for_document`] keeps.
const DOCUMENT_CONTEXTS: usize = 8;
/// The color-management context a document assigned the profiles `rgb` and `cmyk` (`None`: none)
/// draws through: the one [`use_document_profiles`] would make active for it. A context that is the
/// active or the working one is that one; the others are kept for the same working settings and
/// loaded profiles, so the same document gets the same context again. A profile that cannot be
/// loaded gives the working settings.
pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
static KEPT: Mutex<Vec<(u64, Arc<Cms>)>> = Mutex::new(Vec::new());
let working = working();
let st = document_settings(&working.settings, rgb, cmyk);
let installed = installed();
if st == installed.settings {
return installed;
}
if st == working.settings {
return working;
}
let generation = profiles_generation();
let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
kept.retain(|(g, c)| *g == generation && c.working.as_ref().is_some_and(|w| Arc::ptr_eq(w, &working)));
if let Some((_, c)) = kept.iter().find(|(_, c)| c.settings == st) {
return c.clone();
}
let Ok(mut cms) = Cms::new(&st) else { return working };
cms.working = Some(working);
let cms = Arc::new(cms);
if kept.len() >= DOCUMENT_CONTEXTS {
kept.remove(0);
}
kept.push((generation, cms.clone()));
cms
}
/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`]
/// and the conversions that read them), as when drawing a document other than the front one
/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had.
pub fn with_active<R>(cms: Arc<Cms>, f: impl FnOnce() -> R) -> R {
/// Puts back the settings this thread had before, when `f` returns or unwinds.
struct Restore(Option<Arc<Cms>>, u8);
impl Drop for Restore {
fn drop(&mut self) {
SCOPED.with(|s| *s.borrow_mut() = self.0.take());
SCOPED_FLAGS.with(|c| c.set(self.1));
}
}
let flags = SCOPED_SET | if cms.rgb_is_srgb() { SCOPED_SRGB } else { 0 } | if matches!(cms.cmyk, CmykSpace::Device) { SCOPED_DEVICE } else { 0 };
let before = SCOPED.with(|s| s.borrow_mut().replace(cms));
let _restore = Restore(before, SCOPED_FLAGS.with(|c| c.replace(flags)));
f()
}
fn install(cms: Arc<Cms>) {
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
@@ -982,10 +1070,16 @@ fn install(cms: Arc<Cms>) {
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
pub(crate) fn rgb_is_srgb() -> bool {
RGB_IS_SRGB.load(Ordering::Relaxed)
match SCOPED_FLAGS.with(Cell::get) {
f if f & SCOPED_SET != 0 => f & SCOPED_SRGB != 0,
_ => RGB_IS_SRGB.load(Ordering::Relaxed),
}
}
pub(crate) fn cmyk_is_device() -> bool {
CMYK_IS_DEVICE.load(Ordering::Relaxed)
match SCOPED_FLAGS.with(Cell::get) {
f if f & SCOPED_SET != 0 => f & SCOPED_DEVICE != 0,
_ => CMYK_IS_DEVICE.load(Ordering::Relaxed),
}
}
#[cfg(test)]
+327
View File
@@ -0,0 +1,327 @@
//! The canvas's last step before the screen: the sRGB the canvas draws, converted into a display's
//! ICC profile (Preferences › Performance › Use Monitor Profile for Canvas).
//!
//! The display profile is a destination only. Document colors, proofs, exports and the web build
//! keep their sRGB output; a soft proof is applied first, then this conversion.
//!
//! [`DisplayTransform::from_icc`] accepts an RGB display-class (`mntr`) profile of at most
//! [`MAX_PROFILE_BYTES`] whose declared length fits the data and from which a transform can be built.
//! The conversion is relative colorimetric, sampled once into a [`LUT_N`]³ table, so drawing a frame
//! costs a table lookup per pixel and never builds a transform.
use std::hash::{Hash, Hasher};
use super::{Intent, ProfileKind, icc::IccProfile};
/// The largest display profile read: VectorCraft's own limit. Display profiles are a few kilobytes
/// (matrix/shaper) to a few hundred (table-based).
pub const MAX_PROFILE_BYTES: usize = 1 << 20;
/// Grid points per channel of the conversion table.
const LUT_N: usize = 33;
/// Why a display profile can't be used. The canvas then stays sRGB.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProfileError {
/// More bytes than [`MAX_PROFILE_BYTES`].
TooLarge(usize),
/// No ICC header (`acsp` signature) or a header cut short.
NotIcc,
/// The header's length is shorter than a header or longer than the data.
BadLength { declared: usize, len: usize },
/// The profile class isn't a display's (`mntr`): an input, output or other profile.
NotDisplay(String),
/// The profile's data color space isn't RGB.
NotRgb(String),
/// The profile doesn't parse.
Unreadable(String),
/// No conversion from sRGB into the profile can be built.
NoTransform,
}
impl std::fmt::Display for ProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooLarge(n) => write!(f, "the profile is {n} bytes, more than the {MAX_PROFILE_BYTES} a display profile may have"),
Self::NotIcc => f.write_str("the file is not an ICC profile"),
Self::BadLength { declared, len } => write!(f, "the profile's header gives a length of {declared} bytes for {len} bytes of data"),
Self::NotDisplay(class) => write!(f, "the profile's class is `{class}`, not a display profile (`mntr`)"),
Self::NotRgb(space) => write!(f, "the profile's color space is `{space}`, not RGB"),
Self::Unreadable(e) => write!(f, "the profile can't be read: {e}"),
Self::NoTransform => f.write_str("no conversion into the profile can be built"),
}
}
}
/// Four header bytes as text, for an error message.
fn signature(b: &[u8]) -> String {
String::from_utf8_lossy(b).trim_end().to_string()
}
/// sRGB → a display profile, as a table.
pub struct DisplayTransform {
name: String,
fingerprint: u64,
/// `LUT_N`³ display values, red slowest; `None` when the profile shows sRGB unchanged (every
/// grid point within half an 8-bit step of itself).
table: Option<Vec<[f32; 3]>>,
}
impl std::fmt::Debug for DisplayTransform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DisplayTransform").field("name", &self.name).field("identity", &self.is_identity()).finish()
}
}
impl DisplayTransform {
/// Checks `bytes` as a display profile, as [`Self::from_icc`] does, without building the
/// conversion table.
pub fn check(bytes: &[u8]) -> Result<(), ProfileError> {
Self::parse(bytes).map(|_| ())
}
/// Checks `bytes` as a display profile and builds the conversion into it.
pub fn from_icc(bytes: &[u8]) -> Result<Self, ProfileError> {
let (profile, bytes) = Self::parse(bytes)?;
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
let s = (LUT_N - 1) as f32;
let mut table = Vec::with_capacity(LUT_N.pow(3));
for r in 0..LUT_N {
for g in 0..LUT_N {
for b in 0..LUT_N {
let rgb = [r as f32 / s, g as f32 / s, b as f32 / s];
table.push(to_display(rgb).ok_or(ProfileError::NoTransform)?);
}
}
}
let grid = |i: usize| [i / (LUT_N * LUT_N), i / LUT_N % LUT_N, i % LUT_N].map(|v| v as f32 / s);
let identity = table.iter().enumerate().all(|(i, v)| v.iter().zip(grid(i)).all(|(a, b)| (a - b).abs() <= 0.5 / 255.0));
let mut h = std::collections::hash_map::DefaultHasher::new();
bytes.hash(&mut h);
Ok(Self { name: profile.name.clone(), fingerprint: h.finish(), table: (!identity).then_some(table) })
}
/// The parsed profile and its bytes up to its declared length, when `bytes` is an RGB display
/// profile from which a conversion can be built.
fn parse(bytes: &[u8]) -> Result<(IccProfile, &[u8]), ProfileError> {
if bytes.len() > MAX_PROFILE_BYTES {
return Err(ProfileError::TooLarge(bytes.len()));
}
if bytes.len() < 132 || bytes.get(36..40) != Some(b"acsp") {
return Err(ProfileError::NotIcc);
}
let declared = bytes.get(0..4).map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
if declared < 132 || declared > bytes.len() {
return Err(ProfileError::BadLength { declared, len: bytes.len() });
}
let bytes = &bytes[..declared];
if &bytes[12..16] != b"mntr" {
return Err(ProfileError::NotDisplay(signature(&bytes[12..16])));
}
if &bytes[16..20] != b"RGB " {
return Err(ProfileError::NotRgb(signature(&bytes[16..20])));
}
let profile = IccProfile::from_bytes(None, bytes).map_err(|e| ProfileError::Unreadable(e.to_string()))?;
if profile.kind != ProfileKind::Rgb {
return Err(ProfileError::NotRgb(format!("{:?}", profile.kind)));
}
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
if to_display([0.5; 3]).is_none() {
return Err(ProfileError::NoTransform);
}
Ok((profile, bytes))
}
/// The profile's description.
pub fn name(&self) -> &str {
&self.name
}
/// A hash of the profile's bytes, which tells two profiles with the same name apart.
pub fn fingerprint(&self) -> u64 {
self.fingerprint
}
/// The profile shows sRGB unchanged, so nothing is converted.
pub fn is_identity(&self) -> bool {
self.table.is_none()
}
/// One sRGB color (0..1) in the display profile.
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
let Some(table) = &self.table else { return rgb.map(|v| v.clamp(0.0, 1.0)) };
let n = LUT_N;
let s = (n - 1) as f32;
let p = rgb.map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) * s });
let i = p.map(|v| (v.floor() as usize).min(n - 2));
let t = [p[0] - i[0] as f32, p[1] - i[1] as f32, p[2] - i[2] as f32];
let mut out = [0.0f32; 3];
for (dr, wr) in [(0, 1.0 - t[0]), (1, t[0])] {
for (dg, wg) in [(0, 1.0 - t[1]), (1, t[1])] {
for (db, wb) in [(0, 1.0 - t[2]), (1, t[2])] {
let w = wr * wg * wb;
if w == 0.0 {
continue;
}
let v = table[((i[0] + dr) * n + i[1] + dg) * n + i[2] + db];
for c in 0..3 {
out[c] += w * v[c];
}
}
}
}
out.map(|v| v.clamp(0.0, 1.0))
}
/// One 8-bit sRGB color in the display profile.
pub fn apply8(&self, rgb: [u8; 3]) -> [u8; 3] {
if self.table.is_none() {
return rgb;
}
self.apply(rgb.map(|v| f32::from(v) / 255.0)).map(|v| (v * 255.0).round() as u8)
}
/// Premultiplied RGBA8 pixels, converted in place. Alpha is kept, and fully transparent
/// pixels are left as they are.
pub fn apply_premultiplied(&self, pixels: &mut [u8]) {
if self.table.is_none() {
return;
}
let mut last_in = [0u8; 4];
let mut last_out = [0u8; 4];
for px in pixels.as_chunks_mut::<4>().0 {
let a = px[3];
if a == 0 {
continue;
}
if *px == last_in {
*px = last_out;
continue;
}
last_in = *px;
let un = |c: u8| if a == 255 { c } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 };
let out = self.apply8([un(px[0]), un(px[1]), un(px[2])]);
for (c, o) in px.iter_mut().zip(out) {
*c = if a == 255 { o } else { ((u32::from(o) * u32::from(a) + 127) / 255) as u8 };
}
last_out = *px;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cms::{DISPLAY_P3, GENERIC_CMYK, SRGB, icc_bytes};
/// `name`'s ICC file, marked as a display profile.
fn display(name: &str) -> Vec<u8> {
let mut b = icc_bytes(name).unwrap().to_vec();
b[12..16].copy_from_slice(b"mntr");
b
}
#[test]
fn a_wide_gamut_display_shows_srgb_red_less_saturated_and_srgb_is_left_alone() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
assert!(!p3.is_identity());
assert_eq!(p3.name(), DISPLAY_P3);
// sRGB red is inside Display P3: its display values have green and blue above 0 and less red.
let [r, g, b] = p3.apply8([255, 0, 0]);
assert!(r < 245 && g > 40 && b > 10, "{:?}", [r, g, b]);
// White and black stay where they are (relative colorimetric).
assert_eq!(p3.apply8([255; 3]), [255; 3]);
assert_eq!(p3.apply8([0; 3]), [0; 3]);
let srgb = DisplayTransform::from_icc(&display(SRGB)).unwrap();
assert!(srgb.is_identity());
assert_eq!(srgb.apply8([255, 0, 0]), [255, 0, 0]);
assert_ne!(srgb.fingerprint(), p3.fingerprint());
}
#[test]
fn the_table_matches_the_profile_between_its_grid_points() {
let bytes = display(DISPLAY_P3);
let p3 = DisplayTransform::from_icc(&bytes).unwrap();
let profile = IccProfile::from_bytes(None, &bytes).unwrap();
for rgb in [[0.1, 0.7, 0.33], [0.9, 0.05, 0.6], [0.47, 0.47, 0.47], [0.0, 0.2, 1.0]] {
let want = profile.from_srgb(rgb, Intent::RelativeColorimetric).unwrap();
let got = p3.apply(rgb);
for c in 0..3 {
assert!((got[c] - want[c]).abs() < 1.0 / 255.0, "{rgb:?}: {got:?} vs {want:?}");
}
}
}
#[test]
fn premultiplied_pixels_keep_their_alpha_and_transparent_ones_stay_empty() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
let mut px = vec![255, 0, 0, 255, 128, 0, 0, 128, 0, 0, 0, 0, 255, 0, 0, 255];
p3.apply_premultiplied(&mut px);
let opaque = p3.apply8([255, 0, 0]);
assert_eq!(&px[0..4], &[opaque[0], opaque[1], opaque[2], 255]);
assert_eq!(&px[12..16], &px[0..4], "a repeated pixel converts the same");
assert_eq!(px[7], 128);
// Half-covered red: the same color at half coverage, within rounding.
for c in 0..3 {
assert!((i32::from(px[4 + c]) - i32::from(opaque[c]) / 2).abs() <= 1, "{:?}", &px[4..8]);
}
assert_eq!(&px[8..12], &[0, 0, 0, 0]);
}
#[test]
fn profiles_that_are_not_rgb_display_profiles_are_refused() {
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert!(matches!(DisplayTransform::from_icc(&cmyk), Err(ProfileError::NotDisplay(_))));
let mut cmyk_display = cmyk.clone();
cmyk_display[12..16].copy_from_slice(b"mntr");
assert!(matches!(DisplayTransform::from_icc(&cmyk_display), Err(ProfileError::NotRgb(s)) if s == "CMYK"));
let mut input = display(DISPLAY_P3);
input[12..16].copy_from_slice(b"scnr");
assert_eq!(DisplayTransform::from_icc(&input).unwrap_err(), ProfileError::NotDisplay("scnr".into()));
}
#[test]
fn malformed_short_and_oversized_data_is_refused() {
assert_eq!(DisplayTransform::from_icc(&[]).unwrap_err(), ProfileError::NotIcc);
assert_eq!(DisplayTransform::from_icc(&[0; 132]).unwrap_err(), ProfileError::NotIcc);
let good = display(DISPLAY_P3);
assert_eq!(DisplayTransform::from_icc(&good[..100]).unwrap_err(), ProfileError::NotIcc);
let mut long = good.clone();
long[0..4].copy_from_slice(&(good.len() as u32 + 1).to_be_bytes());
assert_eq!(DisplayTransform::from_icc(&long).unwrap_err(), ProfileError::BadLength { declared: good.len() + 1, len: good.len() });
let mut short = good.clone();
short[0..4].copy_from_slice(&64u32.to_be_bytes());
assert!(matches!(DisplayTransform::from_icc(&short), Err(ProfileError::BadLength { declared: 64, .. })));
// Trailing bytes past the declared length are not part of the profile.
let mut padded = good.clone();
padded.extend([0xAB; 16]);
let a = DisplayTransform::from_icc(&padded).unwrap();
assert_eq!(a.fingerprint(), DisplayTransform::from_icc(&good).unwrap().fingerprint());
let mut garbage_tags = good.clone();
for b in &mut garbage_tags[128..] {
*b = 0xFF;
}
assert!(matches!(DisplayTransform::from_icc(&garbage_tags), Err(ProfileError::Unreadable(_) | ProfileError::NoTransform)));
let huge = vec![0u8; MAX_PROFILE_BYTES + 1];
assert_eq!(DisplayTransform::from_icc(&huge).unwrap_err(), ProfileError::TooLarge(MAX_PROFILE_BYTES + 1));
}
#[test]
fn check_accepts_and_refuses_what_from_icc_does() {
assert_eq!(DisplayTransform::check(&display(DISPLAY_P3)), Ok(()));
assert_eq!(DisplayTransform::check(&display(SRGB)), Ok(()));
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert_eq!(DisplayTransform::check(&cmyk), Err(DisplayTransform::from_icc(&cmyk).unwrap_err()));
assert_eq!(DisplayTransform::check(&[1, 2, 3]), Err(ProfileError::NotIcc));
}
#[test]
fn nan_and_out_of_range_values_stay_in_range() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
for v in p3.apply([f32::NAN, -1.0, 9.0]) {
assert!((0.0..=1.0).contains(&v));
}
}
}
+39
View File
@@ -403,3 +403,42 @@ fn lab_colours_round_trip_through_the_cms() {
let Color::Gray { k } = c.convert(&Color::lab(50.0, 0.0, 0.0), Model::Gray, ri) else { panic!("Gray") };
assert!((k - 0.53).abs() < 0.01, "{k}");
}
#[test]
fn with_active_puts_settings_in_place_on_this_thread_only() {
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
let (rgb, ink) = (Color::Rgb { r: 0.2, g: 0.6, b: 0.4 }, Color::Cmyk { c: 0.2, m: 0.3, y: 0.4, k: 0.1 });
let before = (rgb.to_rgb(), ink.to_rgb());
let (inside, ink_inside, other_thread, nested) = with_active(p3.clone(), || {
let other = std::thread::spawn(move || rgb.to_rgb()).join().unwrap();
let nested = with_active(Arc::new(cms()), || rgb.to_rgb());
(rgb.to_rgb(), ink.to_rgb(), other, nested)
});
assert_eq!(inside, p3.display_rgb(&rgb), "RGB is drawn through the settings given");
assert_ne!(inside, before.0);
assert_eq!(ink_inside, naive_cmyk_to_rgb([0.2, 0.3, 0.4, 0.1]), "CMYK takes the device formula of the settings given");
assert_eq!(other_thread, before.0, "another thread keeps the active settings");
assert_eq!(nested, before.0, "an inner call puts its own settings in place");
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after");
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| with_active(p3.clone(), || panic!("unwinds"))));
assert!(unwound.is_err());
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
}
#[test]
fn a_document_gets_the_same_context_for_the_same_profiles() {
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
// of calls sees none.
let same = (0..100).any(|_| {
let generation = profiles_generation();
let (a, b) = (for_document(Some(DISPLAY_P3), None), for_document(Some(DISPLAY_P3), None));
profiles_generation() == generation && Arc::ptr_eq(&a, &b)
});
assert!(same, "the same profiles give the same context");
let p3 = for_document(Some(DISPLAY_P3), None);
assert_eq!(p3.settings().rgb, DISPLAY_P3);
assert_eq!(p3.settings().cmyk, working_settings().cmyk, "the working CMYK space stays");
assert_eq!(for_document(None, None).settings(), &working_settings(), "no profiles: the working settings");
let unknown = for_document(Some("no such profile"), Some(SRGB));
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
}
+178 -25
View File
@@ -65,24 +65,62 @@ pub enum GradientMethod {
/// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to
/// yellow passes through a light blue-grey rather than a dull mid grey.
Perceptual,
/// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls
/// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation
/// and brightness change evenly ([`hue_mix`]).
HueClockwise,
/// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next
/// (red, yellow, green, cyan, blue, magenta, red).
HueCounterclockwise,
}
impl GradientMethod {
/// Parse a method name (`classic`, `perceptual`; any case).
/// Every method, in the order the Gradient panel lists them.
pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise];
/// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`;
/// any case, and the hyphen may be a space or an underscore, or left out). Any other text,
/// one with a separator elsewhere included, is `None`.
pub fn parse(s: &str) -> Option<Self> {
[Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
let name = s.to_ascii_lowercase();
Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name))
}
pub fn label(self) -> &'static str {
match self {
Self::Classic => "Classic",
Self::Perceptual => "Perceptual",
Self::HueClockwise => "Hue Clockwise",
Self::HueCounterclockwise => "Hue Counterclockwise",
}
}
/// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`,
/// `hue-counterclockwise`).
pub fn id(self) -> &'static str {
match self {
Self::Classic => "classic",
Self::Perceptual => "perceptual",
Self::HueClockwise => "hue-clockwise",
Self::HueCounterclockwise => "hue-counterclockwise",
}
}
pub fn is_classic(&self) -> bool {
*self == Self::Classic
}
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an
/// RGB colour between the two).
/// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors
/// between two stops then are not mixes of the stops' inks.
pub fn is_hue(&self) -> bool {
matches!(self, Self::HueClockwise | Self::HueCounterclockwise)
}
/// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a
/// hue method turned the other way, Classic and Perceptual as they are.
pub fn mirrored(self) -> Self {
match self {
Self::HueClockwise => Self::HueCounterclockwise,
Self::HueCounterclockwise => Self::HueClockwise,
m => m,
}
}
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an
/// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour).
pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color {
match self {
Self::Classic => Color::lerp(a, b, t),
@@ -93,10 +131,68 @@ impl GradientMethod {
let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
Color::rgb(c(r), c(g), c(bl))
}
Self::HueClockwise => hue_mix(a, b, t, false),
Self::HueCounterclockwise => hue_mix(a, b, t, true),
}
}
}
/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread
/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it
/// has no hue of its own: under half a color level.
const NO_HUE: f32 = 0.4 / 255.0;
/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose
/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes
/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue.
const SAME_HUE: f32 = 60.0 * 0.5 / 255.0;
/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees),
/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises
/// (`rising`) or only falls, by the fixed-direction rules of
/// <https://www.w3.org/TR/css-color-4/#hue-interpolation>, and two equal hues stay where they are.
/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the
/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do
/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart
/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes
/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number
/// gives `a`.
pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color {
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb());
let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE);
// The spread between each color's own largest and smallest RGB numbers.
let (spread0, spread1) = (s0 * v0, s1 * v1);
// Black takes the other color's saturation, so it darkens that color rather than graying it.
if black0 && !black1 {
s0 = s1;
} else if black1 && !black0 {
s1 = s0;
}
let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE);
match (gray0, gray1) {
(true, _) => h0 = h1,
(false, true) => h1 = h0,
(false, false) => {
// The short way from the first hue to the second, -180..180.
let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0;
h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE {
h0 + short
} else if rising {
h0 + short.rem_euclid(360.0)
} else {
h0 + short.rem_euclid(360.0) - 360.0
};
}
}
let at = |p: f32, q: f32| p + (q - p) * t;
let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1));
if !(h.is_finite() && s.is_finite() && v.is_finite()) {
return Color::rgb(0.0, 0.0, 0.0);
}
Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0))
}
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
@@ -192,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096;
const INK_MIX_STEPS: u32 = 64;
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order.
fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb();
/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around
/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`]
/// times, in order.
fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
let at = |v: f32| method.mix(a, b, v).to_rgb();
let (c0, c1) = (at(v0), at(v1));
let stray = [0.25, 0.5, 0.75]
.into_iter()
@@ -206,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
.fold(0.0, f32::max);
if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE {
let m = (v0 + v1) / 2.0;
perceptual_steps(a, b, (v0, m), depth + 1, out);
perceptual_steps(method, a, b, (v0, m), depth + 1, out);
out.push(m);
perceptual_steps(a, b, (m, v1), depth + 1, out);
perceptual_steps(method, a, b, (m, v1), depth + 1, out);
}
}
/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> {
/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method`
/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order:
/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec<f32> {
let mut vs = Vec::new();
perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs);
vs.push(0.5);
perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs);
vs
}
@@ -449,6 +547,49 @@ impl Gradient {
None => (Color::BLACK, 1.0),
}
}
/// Which of its stops color some part of it that draws, by the stretches [`Self::sample`]
/// mixes in, for stops in any order: the pair of stop `k` and stop `k + 1` covers the offsets
/// above every offset of stops `0..=k` up to stop `k + 1`'s, and both its stops count when that
/// stretch has positive width and either stop is above opacity 0. The first stop also counts
/// when it is above opacity 0, since it colors the offsets up to its own, and so does the last
/// stop, since it colors the offsets above every stop's. Any other stop, opaque or not, counts
/// only through a pair: a stop out of order whose pairs have no width (another stop before it
/// reaches past both ends) colors nothing. A freeform gradient draws from its points, so each of
/// its stops counts while any stop is above opacity 0.
pub fn drawn_stops(&self) -> Vec<bool> {
self.stops_with_color(|s| s.opacity > 0.0)
}
/// [`Self::drawn_stops`] with every stop taken as opaque, for output that leaves stop opacity
/// out: the stops that color a stretch of positive width, and the first and last stops.
pub fn reached_stops(&self) -> Vec<bool> {
self.stops_with_color(|_| true)
}
/// [`Self::drawn_stops`] with `shows` telling whether a stop's opacity shows its color.
fn stops_with_color(&self, shows: impl Fn(&GradientStop) -> bool) -> Vec<bool> {
let stops = &self.stops;
if self.kind == GradientKind::Freeform {
let any = stops.iter().any(&shows);
return vec![any; stops.len()];
}
let mut drawn = vec![false; stops.len()];
if let (Some(first), Some(d)) = (stops.first(), drawn.first_mut()) {
*d = shows(first);
}
if let (Some(last), Some(d)) = (stops.last(), drawn.last_mut()) {
*d |= shows(last);
}
// `f32::max` skips a NaN offset, which the sampler never picks either.
let mut reach = f32::NEG_INFINITY;
for k in 0..stops.len().saturating_sub(1) {
reach = reach.max(stops[k].offset);
let (a, b) = (&stops[k], &stops[k + 1]);
if b.offset > reach && (shows(a) || shows(b)) {
drawn[k] = true;
drawn[k + 1] = true;
}
}
drawn
}
/// [`Self::sample_with`] at each of `ts`, which must not decrease. Each search starts where
/// the one before it stopped, so the work is the samples plus the stops, not their product.
pub fn sample_increasing_with(&self, ts: impl IntoIterator<Item = f32>, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> {
@@ -512,10 +653,11 @@ impl Gradient {
};
(t, c, o, Some(s.midpoint), None)
});
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
// Perceptual and the hue methods: stops along the mix (`v`) where a straight line would
// stray from it, the midpoint (v = ½) among them, placed through the midpoint as
// [`Self::sample`] maps them.
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
perceptual_mixes(s, n).into_iter().map(move |v| {
perceptual_mixes(self.method, s, n).into_iter().map(move |v| {
let mid = v == 0.5;
let t = curve_offset(s, n, v);
let o = s.opacity + (n.opacity - s.opacity) * v;
@@ -571,11 +713,12 @@ impl Gradient {
/// position itself when the two colors' lightness differs by less than
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
/// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue
/// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve
/// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
use crate::libraries::srgb_to_oklab;
if self.method.is_classic() || !self.fits_ink_tints() {
if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() {
return None;
}
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
@@ -592,7 +735,7 @@ impl Gradient {
.collect::<Vec<_>>()
.windows(2)
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
for v in perceptual_mixes(s, n) {
for v in perceptual_mixes(self.method, s, n) {
let weight = if by_position {
v
} else {
@@ -650,8 +793,10 @@ impl Gradient {
Some(Ramp { stops })
}
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
/// segment's midpoint mirrored with it.
/// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue
/// through magenta, reversed, is blue to red through magenta).
pub fn reverse(&mut self) {
self.method = self.method.mirrored();
self.stops.reverse();
for i in 0..self.stops.len() {
// A midpoint belongs to the segment after its stop: reversed, stop i's segment is the
@@ -666,6 +811,13 @@ impl Gradient {
pub fn sort(&mut self) {
self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
}
/// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as
/// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops
/// keep no swatch links, tints or process plates.
pub fn as_classic_curve(&self) -> Gradient {
let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect();
Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats }
}
/// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient
/// of its own running 0 → 1: the same colours (midpoints become stops, as in
/// [`Self::expanded_stops`]). One colour throughout when `from == to`.
@@ -1261,8 +1413,9 @@ impl GradientPaint {
}
/// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill
/// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a
/// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix
/// linearly between the stops, as SVG's and PDF's gradients do)?
/// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the
/// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients
/// do)?
pub fn draws_as_pixels(&self, fill: bool) -> bool {
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
}
+16
View File
@@ -59,6 +59,9 @@ impl Gradient {
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
return None;
}
if self.mirrors_a_hue_turn() {
return self.as_classic_curve().padded_within(geom, area, max_stops);
}
let period = geom.period(kind, self.repeat_count());
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
let ts = corners.map(|p| period.param_at(kind, p));
@@ -128,6 +131,9 @@ impl Gradient {
if self.stops.is_empty() {
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
}
if self.mirrors_a_hue_turn() {
return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned());
}
let n = self.repeat_count() as usize;
let budget = max_stops.min(MAX_SPREAD_STOPS);
let kept = n.min(budget / 2).max(1);
@@ -159,12 +165,22 @@ impl Gradient {
if !self.is_spread() || self.stops.is_empty() {
return None;
}
if self.mirrors_a_hue_turn() {
return self.as_classic_curve().cycle();
}
let one = whole_run(&self.stops);
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
}
/// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops
/// would turn the wheel the other way, and one gradient has one method, so its runs are
/// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are.
fn mirrors_a_hue_turn(&self) -> bool {
self.method.is_hue() && self.spread == GradientSpread::Reflect
}
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
/// Reflect, the odd-numbered runs are mirrored).
+40
View File
@@ -118,6 +118,46 @@ fn reflect_mirrors_every_other_run_and_its_midpoints() {
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
}
/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the
/// way it came, so every point keeps its color when the runs are written out as a gradient that
/// pads, unrolled along the vector, or as one cycle, with a repeating one's too.
#[test]
fn reflected_and_repeated_hue_turns_keep_every_color() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
let stops = || {
let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0));
red.midpoint = 0.3;
vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]
};
let near = |a: Color, b: Color, what: &str| {
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
};
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
for spread in [GradientSpread::Reflect, GradientSpread::Repeat] {
let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) };
let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap();
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
for k in 0..300 {
let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0);
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x));
}
let unrolled = g.unrolled();
let (cycle, runs) = g.cycle().unwrap();
for k in 0..=200 {
let t = (k as f32 + 0.37) / 201.0;
let want = g.sample(g.spread_param(f64::from(t)) as f32).0;
near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}"));
// One cycle covers `runs` of the two runs between 0 and 1.
let along = t * runs as f32 / 2.0;
let want = g.sample(g.spread_param(f64::from(along)) as f32).0;
near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}"));
}
}
}
}
#[test]
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
+340
View File
@@ -66,6 +66,69 @@ fn stop_reach_matches_scanning_the_stops() {
}
}
/// A gradient's stops color what draws where they color a stretch that draws, for stops in any
/// order: the sampler mixes stop `k` with stop `k + 1` above every offset of the stops before it,
/// so an out-of-order stop's pair can have no width.
#[test]
fn drawn_stops_follow_the_sampled_stretches() {
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
// In order: the clear stop next to the opaque one, not the one after it.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![true, true, false]);
// Out of order: the pair (0.8, 0.3) has no width, so the clear stop at 0.3 mixes only with
// the clear stop at 0.8 before it, and the pair (0.3, 1.0) is sampled above 0.8.
assert_eq!(g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 0.0), stop(1.0, 1.0)]).drawn_stops(), vec![false, false, true, true]);
// An opaque stop out of order: the pairs (0, 0.8) and (0.7, 1) cover every offset, so the
// pairs next to the stop at 0.3 have no width and it colors nothing.
let out_of_order = |o: f32| g(vec![stop(0.0, 0.0), stop(0.8, o), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
assert_eq!(out_of_order(0.0).drawn_stops(), vec![false; 5]);
// With the stop at 0.8 opaque, the pairs next to it with width are drawn.
assert_eq!(out_of_order(1.0).drawn_stops(), vec![true, true, false, false, false]);
// The last stop colors the offsets above every stop's, even when it is out of order.
assert_eq!(g(vec![stop(0.0, 0.0), stop(0.6, 0.0), stop(0.5, 1.0)]).drawn_stops(), vec![false, false, true]);
// The first stop colors the offsets up to its own.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.0, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![true, false, false]);
// One stop, every stop clear, and no stops at all.
assert_eq!(g(vec![stop(0.5, 1.0)]).drawn_stops(), vec![true]);
assert_eq!(g(vec![stop(0.0, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![false, false]);
assert!(g(vec![]).drawn_stops().is_empty());
// A freeform gradient draws from its points: its stops count while any is above opacity 0.
let mut free = g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]);
free.kind = GradientKind::Freeform;
assert_eq!(free.drawn_stops(), vec![true, true, true]);
free.stops.iter_mut().for_each(|s| s.opacity = 0.0);
assert_eq!(free.drawn_stops(), vec![false; 3]);
}
/// Taken as opaque, every stop that colors a stretch of positive width counts, and the first and
/// last stops, whatever their opacity; an out-of-order stop whose pairs have no width does not.
#[test]
fn reached_stops_leave_out_only_stops_without_width() {
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
// Clear stops in order color their stretches once opaque.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]).reached_stops(), vec![true; 3]);
assert_eq!(g(vec![stop(0.0, 0.0), stop(1.0, 0.0)]).reached_stops(), vec![true, true]);
// The stop at 0.3 sits inside the stretch the stops at 0 and 0.8 cover.
let out_of_order = g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
assert_eq!(out_of_order.reached_stops(), vec![true, true, false, true, true]);
// A stop at the offset of the stop before it: its pair has no width, the next one does.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.0, 1.0), stop(1.0, 1.0)]).reached_stops(), vec![true, true, true]);
assert_eq!(
g(vec![stop(0.0, 1.0), stop(0.6, 1.0), stop(0.6, 1.0), stop(0.2, 1.0), stop(1.0, 1.0)]).reached_stops(),
vec![true, true, false, true, true]
);
assert!(g(vec![]).reached_stops().is_empty());
// Every pair the sampler picks between the ends has both its stops counted.
let stops: Vec<GradientStop> = [0.1, 0.4, 0.4, 0.2, 0.9, 0.5].iter().map(|&o| stop(o, 1.0)).collect();
let g = g(stops);
let (reached, reach) = (g.reached_stops(), StopReach::new(&g.stops));
for t in (5..=95).map(|k| k as f32 / 100.0).filter(|&t| t > 0.1 && t <= 0.9) {
let k = reach.0.partition_point(|r| *r < t);
assert!(reached[k] && reached[k + 1], "pair {k} at {t}: {reached:?}");
}
}
/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as
/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one
/// offset used to scan them all for each midpoint).
@@ -514,6 +577,283 @@ fn perceptual_gradients_draw_as_pixels() {
}
}
fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient {
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
g.method = method;
g
}
/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the
/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules
/// of <https://www.w3.org/TR/css-color-4/#hue-interpolation> (the angles below are that
/// section's own examples), with saturation and brightness changing evenly.
#[test]
fn hue_methods_turn_one_way_around_the_wheel() {
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise);
assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000");
assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°");
assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°");
assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff");
let falling = two_stops(red, blue, GradientMethod::HueClockwise);
assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000");
assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°");
assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff");
assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix");
// 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling.
for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] {
let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4));
for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] {
let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb();
assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}");
assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}");
}
}
// The other way round, each method takes the arc the other took.
let back = two_stops(blue, red, GradientMethod::HueClockwise);
assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00");
// A position that is not a number gives the first color.
assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000");
}
/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes
/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that
/// hue, whichever way the method turns.
#[test]
fn hue_methods_keep_the_hue_where_a_stop_has_none() {
let red = Color::rgb(1.0, 0.0, 0.0);
let close = |c: Color, want: [f32; 3], what: &str| {
let got = c.to_rgb();
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}");
};
let green = Color::rgb(0.0, 1.0, 0.0);
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green");
close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green");
close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green");
close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green");
close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black");
close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray");
close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black");
let dark = Color::rgb(0.5, 0.0, 0.0);
close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two");
close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays");
// One hue with saturation and brightness both changing: the hue stays, and the color is
// the even mix of saturation and brightness, which is not Classic's RGB mix.
let pink = Color::rgb(1.0, 0.8, 0.8);
close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink");
assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs");
// A color whose RGB numbers are under half a color level apart has no hue of its own: a
// near gray leaning blue takes green's hue rather than turning from blue.
let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0);
let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb();
assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}");
// One a whole color level apart has its hue (240°) and turns from it.
let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0);
let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb();
let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 };
assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}");
}
}
/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose
/// computed hue angles differ in their last digits, mix without turning the wheel, with either
/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color
/// level apart still turn.
#[test]
fn hue_methods_take_hues_within_half_a_color_level_as_one() {
let level = |n: u8| f32::from(n) / 255.0;
let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b));
let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise];
// Colors against their 50% tint toward white and a shade at 40% brightness. At least one
// pair's computed hues differ, or the test checks nothing.
let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)];
let mut uneven = 0;
for c in colors {
let [h, s, v] = c.to_hsb();
let tint = Color::lerp(&c, &Color::WHITE, 0.5);
let shade = Color::from_hsb(h, s, v * 0.4);
for other in [tint, shade] {
let [h1, _, _] = other.to_hsb();
assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}");
uneven += usize::from(h1 != h);
for method in methods {
for (a, b) in [(c, other), (other, c)] {
for k in 0..=20 {
let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb();
let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0;
assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}");
}
}
}
}
}
assert!(uneven > 0, "no pair's hues differ by rounding");
// Across 0°: 359.99° and 0.01° are one hue too.
for method in methods {
let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb();
assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}");
}
// A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors:
// white to red, a color to its tint, and a turn from red to blue.
let ramps = [
(Color::WHITE, rgb8(255, 0, 0)),
(rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)),
(rgb8(255, 0, 0), rgb8(0, 0, 255)),
];
for method in methods {
for (a, b) in ramps {
let g = two_stops(a, b, method);
for at in [0.21, 0.5, 0.83] {
let (stops, i) = insert_stop(&g, at);
assert_eq!((stops.len(), i), (3, 1));
let with = Gradient { stops, ..g.clone() };
for k in 0..=200 {
let t = k as f32 / 200.0;
let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb());
let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}");
}
}
}
}
// One color level of hue is a hue of its own: red to a red one level toward yellow turns
// nearly the whole wheel one way and stays put the other.
let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0));
let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb();
assert!((h - 180.0).abs() < 1.0, "the long way: {h}");
let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb();
assert!(h < 1.0, "the short way: {h}");
}
/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the
/// wheel, close enough that the linear ramp between them stays within half a color level of it,
/// through the midpoint and with the opacity changing evenly.
#[test]
fn hue_segments_expand_into_stops_on_the_curve() {
let pairs = [
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)),
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)),
(Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)),
(Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE),
(Color::BLACK, Color::rgb(0.0, 1.0, 0.0)),
];
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
for (a, b) in pairs {
let mut g = two_stops(a, b, method);
g.stops[0].midpoint = 0.3;
g.stops[1].opacity = 0.5;
let ex: Vec<_> = g.expanded().collect();
assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len());
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint");
let ramp = Ramp::new(&g, &Color::to_rgb);
for k in 0..=4000 {
let t = k as f32 / 4000.0;
let (c, o) = g.sample(t);
let [r, gr, bl] = c.to_rgb();
let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}");
}
assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix");
}
}
}
/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other
/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the
/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a
/// Classic gradient hold the same colors.
#[test]
fn reversing_a_hue_gradient_keeps_its_colors_mirrored() {
let near = |a: Color, b: Color, what: &str| {
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
};
for (method, other) in
[(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)]
{
let mut g = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) },
GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) },
GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)),
],
);
g.method = method;
let mut back = g.clone();
back.reverse();
assert_eq!(back.method, other);
let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve());
assert!(span.method.is_classic() && curve.method.is_classic());
assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5));
for k in 0..=400 {
let t = k as f32 / 400.0;
let (want, opacity) = g.sample(1.0 - t);
near(want, back.sample(t).0, &format!("{method:?} reversed at {t}"));
assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}");
near(want, span.sample(t).0, &format!("{method:?} backward span at {t}"));
near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}"));
}
back.reverse();
assert_eq!(back.method, method);
assert_eq!(back.stops.len(), g.stops.len());
}
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
assert_eq!(method.mirrored(), method);
let mut g = blue_yellow(method);
g.reverse();
assert_eq!(g.method, method);
}
}
/// The hue methods are written by name, read back, and parsed from their param names; their
/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks.
#[test]
fn hue_methods_save_parse_and_draw_as_pixels() {
for (method, name, id) in [
(GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"),
(GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"),
] {
let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method);
let v = serde_json::to_value(&g).unwrap();
assert_eq!(v["method"], name);
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
assert_eq!(method.id(), id);
for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] {
assert_eq!(GradientMethod::parse(&written), Some(method), "{written}");
}
assert!(method.is_hue() && !method.is_classic());
let paint = GradientPaint::new(g.clone());
assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false));
assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks");
assert!(
paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(),
"an RGB image, not an ink image"
);
}
assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue());
for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] {
assert_eq!(method.id(), id);
assert_eq!(GradientMethod::parse(id), Some(method));
}
for bad in [
"hue",
"clockwise",
"hue-",
"",
"hue clockwise wise",
"c-l-a-s-s-i-c",
"per ceptual",
"hue--clockwise",
"hue-clock_wise",
" classic",
"hue- clockwise",
] {
assert_eq!(GradientMethod::parse(bad), None, "{bad}");
}
}
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
/// a straight line.
+41 -7
View File
@@ -102,12 +102,13 @@ impl Color {
pub fn to_lab(&self) -> cms::Lab {
cms::active().lab(self)
}
/// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the
/// profile-free formula).
/// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else
/// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula).
pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] {
cms::active().to_cmyk(self, intent)
}
/// Gamut warning: true when this colour can't be reproduced in the working CMYK space.
/// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front
/// document's assigned CMYK profile, else the working CMYK space).
pub fn out_of_gamut(&self) -> bool {
cms::active().out_of_gamut(self)
}
@@ -434,9 +435,10 @@ impl Paint {
}
/// Apply `f` to the colours of this paint that can link to a swatch (a solid colour, each
/// gradient stop) with their link and tint; `f` returns true when it changed them. A colour
/// left without a link gets tint 1. A freeform gradient's points, which it draws from, go
/// through `f` too, as unlinked colours (a link `f` gives them is dropped). Returns whether
/// anything changed.
/// left without a link gets tint 1, and a stop left without one also loses its process plates
/// ([`GradientStop::plates`], which print with a linked spot tint). A freeform gradient's
/// points, which it draws from, go through `f` too, as unlinked colours (a link `f` gives them
/// is dropped). Returns whether anything changed.
pub fn map_links(&mut self, f: &mut dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool) -> bool {
let mut one = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| {
let changed = f(c, link, tint);
@@ -448,7 +450,11 @@ impl Paint {
match self {
Paint::Solid { color, swatch, tint } => one(color, swatch, tint),
Paint::Gradient(g) => {
let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| one(&mut s.color, &mut s.swatch, &mut s.tint) | ch);
let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| {
let changed = one(&mut s.color, &mut s.swatch, &mut s.tint);
let unplated = s.swatch.is_none() && s.plates.take().is_some();
changed | unplated | ch
});
let points =
g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()).fold(false, |ch, p| one(&mut p.color, &mut None, &mut 1.0) | ch);
stops | points
@@ -592,6 +598,34 @@ mod tests {
assert!(g.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.5));
}
#[test]
fn mapping_links_drops_the_process_plates_of_unlinked_stops() {
let mut gradient = Gradient::default();
let ink = Color::cmyk(0.0, 0.4, 0.0, 0.0);
gradient.stops[0].swatch = Some("Ink".into());
(gradient.stops[0].color, gradient.stops[0].tint, gradient.stops[0].plates) = (ink, 0.4, Some([0.3, 0.0, 0.0, 0.0]));
let mut g = Paint::Gradient(Box::new(GradientPaint::new(gradient)));
// Unlinking the stop takes its plates with its tint and keeps the colour it shows.
assert!(g.map_links(&mut |_, l, _| l.take().is_some()));
let Paint::Gradient(gp) = &g else { panic!("a gradient") };
let st = &gp.gradient.stops[0];
assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (ink, None, 1.0, None));
// A linked stop keeps its plates.
let mut linked = Gradient::default();
(linked.stops[0].swatch, linked.stops[0].plates) = (Some("Ink".into()), Some([0.3, 0.0, 0.0, 0.0]));
let mut l = Paint::Gradient(Box::new(GradientPaint::new(linked)));
assert!(!l.map_links(&mut |_, _, _| false));
let Paint::Gradient(lp) = &l else { panic!("a gradient") };
assert_eq!(lp.gradient.stops[0].plates, Some([0.3, 0.0, 0.0, 0.0]));
// An unlinked stop that still has plates loses them, and that counts as a change.
let mut stale = Gradient::default();
stale.stops[1].plates = Some([0.0, 0.0, 0.2, 0.0]);
let mut p = Paint::Gradient(Box::new(GradientPaint::new(stale)));
assert!(p.map_links(&mut |_, _, _| false));
let Paint::Gradient(pp) = &p else { panic!("a gradient") };
assert!(pp.gradient.stops.iter().all(|s| s.plates.is_none()));
}
#[test]
fn lab_colours_serialize_with_their_tag_and_keep_their_model() {
let c = Color::lab(52.5, 70.0, -30.0);
+157
View File
@@ -567,6 +567,112 @@ pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
groups.into_iter().map(|g| g.2).collect()
}
/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how
/// often the art uses them and the row they are in. A fixed unit (such as the color a row is
/// shown by) stays in its row.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WeighUnit {
pub color: Color,
pub uses: f64,
pub row: usize,
pub fixed: bool,
}
/// The unit-by-row comparisons one [`weigh`] makes, at most.
const WEIGH_WORK: usize = 50_000_000;
/// The uses of `u` that count: a positive finite number, else 0.
fn unit_uses(u: &WeighUnit) -> f64 {
if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 }
}
/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used).
/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing.
pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec<f64> {
let mut sums = vec![0.0; rows];
for u in units {
if let Some(s) = sums.get_mut(u.row) {
*s += unit_uses(u);
}
}
let total: f64 = sums.iter().sum();
if total <= 0.0 {
return vec![0.0; rows];
}
sums.iter().map(|s| s / total * 100.0).collect()
}
/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that
/// each row's share of the uses comes as near its share of `weights` as whole units allow. One
/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of
/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest
/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it
/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past
/// `anchors` and units used no times stay where they are. Weights that are negative or not finite
/// count as 0; when no weight is positive, every unit stays. The moves stop after
/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass
/// it, every unit stays.
pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec<usize> {
let mut row: Vec<usize> = units.iter().map(|u| u.row).collect();
let n = anchors.len();
let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0);
// Scaled by the largest weight first, so the sum stays finite.
let top = (0..n).map(given).fold(0.0, f64::max);
let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 };
let sum_w: f64 = (0..n).map(w).sum();
let movable: Vec<usize> = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect();
let per_pass = movable.len().saturating_mul(n);
if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK {
return row;
}
let mut sums = vec![0.0; n];
for u in units.iter().filter(|u| u.row < n) {
sums[u.row] += unit_uses(u);
}
let total: f64 = sums.iter().sum();
let target: Vec<f64> = (0..n).map(|r| w(r) / sum_w * total).collect();
let anchor_labs: Vec<Lab> = anchors.iter().map(|c| c.to_lab()).collect();
// Each movable unit's distance to each row's color.
let dist: Vec<Vec<f32>> = movable
.iter()
.map(|&i| {
let l = units[i].color.to_lab();
anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect()
})
.collect();
// A move must bring the shares nearer by more than rounding.
let eps = total * 1e-9;
for _ in 0..WEIGH_WORK / per_pass {
let mut best: Option<(f32, f64, usize, usize)> = None;
for (m, &i) in movable.iter().enumerate() {
let (a, x) = (row[i], unit_uses(&units[i]));
let before_a = (sums[a] - target[a]).abs();
let after_a = (sums[a] - x - target[a]).abs();
for b in (0..n).filter(|&b| b != a) {
let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs();
if gain <= eps {
continue;
}
let cost = dist[m][b] - dist[m][a];
let better = match best {
None => true,
Some((c, g, ..)) => cost < c || (cost == c && gain > g),
};
if better {
best = Some((cost, gain, m, b));
}
}
}
let Some((_, _, m, b)) = best else { break };
let i = movable[m];
let x = unit_uses(&units[i]);
sums[row[i]] -= x;
sums[b] += x;
row[i] = b;
}
row
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
@@ -911,4 +1017,55 @@ mod tests {
assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. }));
assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey");
}
fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit {
WeighUnit { color, uses, row, fixed }
}
#[test]
fn row_shares_are_percent_of_the_uses() {
let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)];
assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]);
assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]);
assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]);
}
#[test]
fn weigh_moves_the_nearest_colors_toward_the_weights() {
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
let units = [
unit(red, 1.0, 0, true),
unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false),
unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false),
unit(blue, 1.0, 1, true),
];
// Equal weights: the reddish purple, nearer blue than the red-pink is, moves.
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]);
// Most of the weight on blue: both movable colors go, the row's own color stays.
assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]);
// Weights already met, or none positive: nothing moves.
assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]);
assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]);
assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones");
assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units");
}
#[test]
fn weigh_takes_whole_units_and_stops_when_no_move_helps() {
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
// A heavy unit: moving it would overshoot by more than staying misses.
let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)];
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]);
assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]);
// Many units: the result still follows the weights.
let many: Vec<WeighUnit> = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect();
let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]);
assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300);
assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row");
// Past the work limit (8,000 units by 7,000 rows) nothing moves.
let units: Vec<WeighUnit> = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect();
let anchors = vec![Color::BLACK; 7_000];
let weights = vec![1.0; 7_000];
assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0));
}
}
+4
View File
@@ -8,6 +8,10 @@ description = "VectorCraft document model: artboards, layers, objects, appearanc
[lints]
workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
+10
View File
@@ -271,6 +271,16 @@ impl Appearance {
_ => None,
})
}
/// Does any fill draw: one that is shown, has paint and has an opacity above 0, wherever it
/// sits in the stack?
pub fn has_drawn_fill(&self) -> bool {
self.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0))
}
/// Does any stroke draw: one that is shown, has paint, a weight above 0 and an opacity above
/// 0, wherever it sits in the stack?
pub fn has_drawn_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.width > 0.0 && s.opacity > 0.0)
}
/// Largest distance the painted area can extend beyond any geometry (see
/// [`StrokeLayer::reach`]); paths measure their own with [`Self::stroked_bounds`].
pub fn outset(&self) -> f64 {
+22
View File
@@ -79,6 +79,28 @@ fn basic_means_one_plain_fill_and_stroke() {
assert!(!e.is_basic(), "an effect");
}
#[test]
fn drawn_fills_and_strokes_count_every_row() {
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
let black = || Paint::solid(Color::BLACK);
assert!(!Appearance::default().has_drawn_fill() && !Appearance::default().has_drawn_stroke());
// A painted lower row draws under an unpainted top row.
let a = Appearance { items: vec![fill(black()), stroke(black(), 2.0), fill(Paint::None), stroke(Paint::None, 1.0)], ..Appearance::default() };
assert!(a.has_drawn_fill() && a.has_drawn_stroke());
// A hidden painted row, a zero opacity or a zero weight draws nothing.
let mut b = Appearance { items: vec![fill(black()), stroke(black(), 2.0)], ..Appearance::default() };
b.fill_mut().unwrap().visible = false;
b.stroke_mut().unwrap().visible = false;
assert!(!b.has_drawn_fill() && !b.has_drawn_stroke());
let mut c = Appearance::default_art();
c.fill_mut().unwrap().opacity = 0.0;
c.stroke_mut().unwrap().opacity = 0.0;
assert!(!c.has_drawn_fill() && !c.has_drawn_stroke());
let d = Appearance::basic(Paint::None, black(), 0.0);
assert!(!d.has_drawn_fill() && !d.has_drawn_stroke());
}
#[test]
fn set_creates_missing() {
let mut a = Appearance::default();
+1100 -79
View File
File diff suppressed because it is too large. Load diff
+237 -44
View File
@@ -3,6 +3,7 @@
//! the ruler origin and the objects an edit touches), so a file holding something beyond it could be
//! opened but not edited: one object, artboard or guide out there made every move fail.
use std::collections::BTreeSet;
use std::sync::Arc;
use vectorcraft_geom::{Point, Rect};
@@ -72,27 +73,41 @@ fn clipping(n: &Node) -> Option<bool> {
}
}
/// Does `n`, or any object in it, reach beyond the canvas? A container is looked into object by
/// object: its own bounds leave out a layer's hidden objects and, when it clips, all but its
/// clipping path.
fn reaches_beyond(n: &Node) -> bool {
match clipping(n) {
None => beyond(n),
Some(_) => n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))),
/// The objects of a layer or group that a walk picked, by index in order, each with what was
/// picked inside it (nothing for an object that is not a container).
#[derive(Debug, Default)]
struct Picked(Vec<(usize, Picked)>);
/// What in `n` reaches beyond the canvas, by `far`, or `None` when nothing does. A container is
/// looked into object by object: its own bounds leave out a layer's hidden objects and, when it
/// clips, all but its clipping path. Each object is measured once, and the objects a clipping
/// path beyond the canvas clips are not measured: they go with it (see [`clips_beyond`]).
fn reach(n: &Node, far: &impl Fn(&Node) -> bool) -> Option<Picked> {
let Some(clip) = clipping(n) else { return far(n).then(Picked::default) };
let mut inner = Vec::new();
for (i, c) in n.children().into_iter().flatten().enumerate() {
if let Some(p) = reach(c, far) {
inner.push((i, p));
if clip && i == 0 {
break;
}
}
}
(!inner.is_empty()).then_some(Picked(inner))
}
/// Does `n` clip by a path that reaches beyond the canvas? Then the path and the objects it clips
/// go together, so no other object becomes the clipping path.
fn clips_beyond(n: &Node) -> bool {
clipping(n) == Some(true) && n.children().and_then(|c| c.first()).is_some_and(|c| reaches_beyond(c))
/// Does `n`, whose objects beyond the canvas are `found`, clip by a path that reaches beyond it?
/// Then the path and the objects it clips go together, so no other object becomes the clipping
/// path.
fn clips_beyond(n: &Node, found: &Picked) -> bool {
clipping(n) == Some(true) && found.0.first().is_some_and(|(i, _)| *i == 0)
}
/// Add the ids of `n` and the layers in it, if it is a layer, to `layers`: their layer guides go
/// with them.
fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
fn layers_in(n: &Node, layers: &mut BTreeSet<NodeId>) {
if matches!(n.kind, NodeKind::Layer { .. }) {
layers.push(n.id);
layers.insert(n.id);
}
if clipping(n).is_some() {
for c in n.children().into_iter().flatten() {
@@ -109,22 +124,22 @@ fn guides_in(n: &Node) -> usize {
}
}
/// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its
/// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything
/// else goes whole. Only containers holding such an object are copied. Recursion follows the
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and
/// the ruler guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>, guides: &mut usize) {
if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) {
return;
}
/// Remove the objects in `node` that reach beyond the canvas, which [`reach`] `found`: a layer or
/// group keeps those of its objects within it, unless its clipping path reaches beyond (see
/// [`clips_beyond`]); anything else goes whole. Only containers holding such an object are
/// copied, and only those are visited again. Recursion follows the nesting, which
/// [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and the ruler
/// guides they held to `guides`.
fn drop_children_beyond(node: &mut Arc<Node>, found: Picked, dropped: &mut usize, layers: &mut BTreeSet<NodeId>, guides: &mut usize) {
let Some(children) = Arc::make_mut(node).children_mut() else { return };
let mut found = found.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
if !reaches_beyond(c) {
return true;
}
if clipping(c).is_some() && !clips_beyond(c) {
drop_children_beyond(c, dropped, layers, guides);
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if clipping(c).is_some() && !clips_beyond(c, &inner) {
drop_children_beyond(c, inner, dropped, layers, guides);
return true;
}
layers_in(c, layers);
@@ -134,21 +149,49 @@ fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut
});
}
/// Is `id` unset, or not one of `ids`? The check takes time logarithmic in the number of ids.
fn not_in<T: Ord>(id: Option<T>, ids: &BTreeSet<T>) -> bool {
id.is_none_or(|i| !ids.contains(&i))
}
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
/// to `dropped`. Only layers holding one are copied.
/// to `dropped`. `out` looks at each object in the layers once. Only layers holding one are
/// copied.
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
/// The objects of `n`, if it is a layer, that `out` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none.
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let inner: Vec<(usize, Picked)> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if out(c) { Some((i, Picked::default())) } else { holds(c, out).map(|p| (i, p)) })
.collect();
(!inner.is_empty()).then_some(Picked(inner))
}
if !holds(layer, out) {
return;
fn drop(layer: &mut Arc<Node>, held: Picked, dropped: &mut usize) {
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
children.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; an object picked itself has nothing inside.
if inner.0.is_empty() {
*dropped += 1;
return false;
}
drop(c, inner, dropped);
true
});
}
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
let before = children.len();
children.retain(|c| !out(c));
*dropped += before - children.len();
for c in children.iter_mut().filter(|c| c.is_layer()) {
drop_guides(c, out, dropped);
if let Some(held) = holds(layer, out) {
drop(layer, held, dropped);
}
}
@@ -162,9 +205,10 @@ impl Document {
/// whose artboards were all removed has none left.
pub fn drop_beyond_canvas(&mut self) -> BeyondCanvas {
let mut gone = BeyondCanvas::default();
let mut layers = vec![];
let mut layers = BTreeSet::new();
for layer in &mut self.layers {
if clips_beyond(layer) {
let Some(found) = reach(layer, &beyond) else { continue };
if clips_beyond(layer, &found) {
let layer = Arc::make_mut(layer);
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
for c in children.iter() {
@@ -177,7 +221,7 @@ impl Document {
*clip = false;
}
} else {
drop_children_beyond(layer, &mut gone.objects, &mut layers, &mut gone.guides);
drop_children_beyond(layer, found, &mut gone.objects, &mut layers, &mut gone.guides);
}
}
if gone.objects > 0 {
@@ -192,13 +236,13 @@ impl Document {
self.retire_artboard_id(*id);
}
gone.artboards = removed.len();
let removed: BTreeSet<u32> = removed.into_iter().collect();
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
let guides = self.saved_guides.len();
self.saved_guides
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
self.saved_guides.retain(|g| in_range(g.pos) && not_in(g.artboard, &removed) && not_in(g.layer, &layers));
gone.guides += guides - self.saved_guides.len();
let out = |n: &Node| match n.kind {
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || !not_in(artboard, &removed),
_ => false,
};
for layer in &mut self.layers {
@@ -392,4 +436,153 @@ mod tests {
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
}
#[test]
fn guides_of_many_removed_artboards_and_layers_go_and_the_rest_keep_their_order() {
let probe = Document::new(1.0, 1.0);
// Sublayers 40 to 43 clip by a path beyond the canvas, so they go whole; 50 stays.
let far: Vec<Arc<Node>> = (40..44).map(|id| sublayer(&probe, id, vec![rect(id * 10, 1e17), rect(id * 10 + 1, 0.0)], true)).collect();
let near = sublayer(&probe, 50, vec![rect(500, 0.0)], false);
let mut d = doc(far.into_iter().chain([near, rect(10, 0.0)]).collect());
let kept = d.artboards[0].id;
for id in 9..13 {
d.artboards.push(Artboard { id, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() });
}
let top = d.layers[0].id;
let guide = |pos: f64, artboard: Option<u32>, layer: Option<NodeId>| Guide { artboard, layer, ..Guide::new(false, pos) };
d.saved_guides = vec![
guide(1.0, Some(9), None),
guide(2.0, None, None),
guide(3.0, Some(kept), Some(NodeId(41))),
guide(4.0, Some(kept), None),
guide(5.0, Some(12), None),
guide(6.0, None, Some(NodeId(50))),
guide(7.0, None, Some(NodeId(43))),
guide(8.0, Some(10), Some(top)),
guide(9.0, None, Some(top)),
];
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(42), NodeId(10), NodeId(500)] }].into();
let mut nodes = d.clone();
assert_eq!(nodes.guides_into_nodes(), 9);
let gone = d.drop_beyond_canvas();
assert_eq!(gone, BeyondCanvas { objects: 4, artboards: 4, guides: 5, ruler_origin: false });
assert_eq!(d.artboards.iter().map(|a| a.id).collect::<Vec<_>>(), [kept]);
let left: Vec<f64> = d.saved_guides.iter().map(|g| g.pos).collect();
assert_eq!(left, [2.0, 4.0, 6.0, 9.0], "the guides that stay keep their order");
assert_eq!(d.saved_selections[0].objects, [NodeId(10), NodeId(500)]);
assert_eq!(nodes.drop_beyond_canvas(), gone, "guide nodes go as saved guides do");
let mut left: Vec<f64> = nodes.ruler_guides().iter().map(|g| g.pos).collect();
left.sort_by(f64::total_cmp);
assert_eq!(left, [2.0, 4.0, 6.0, 9.0]);
assert_eq!(nodes.saved_selections, d.saved_selections);
}
thread_local! {
static COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// An id that counts how often it is compared.
#[derive(Debug)]
struct Counted(u32);
impl Ord for Counted {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
COMPARISONS.with(|c| c.set(c.get() + 1));
self.0.cmp(&other.0)
}
}
impl PartialOrd for Counted {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Counted {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}
impl Eq for Counted {}
#[test]
fn a_guide_is_checked_without_scanning_every_removed_id() {
let per_guide = |removed: u32| {
let ids: BTreeSet<Counted> = (0..removed).map(|i| Counted(i * 2)).collect();
COMPARISONS.with(|c| c.set(0));
// Guides on removed ids, on ids between them, on ids past them and on none.
let guides: Vec<Option<Counted>> = (0..64).map(|i| (i % 4 != 3).then(|| Counted(i * 31 % (removed * 2 + 8)))).collect();
let kept = guides.into_iter().filter(|g| not_in(g.as_ref().map(|c| Counted(c.0)), &ids)).count();
assert!(kept > 0 && kept < 64);
COMPARISONS.with(|c| c.get()) as f64 / 64.0
};
let small = per_guide(16);
let large = per_guide(16_384);
// A sorted lookup grows with the depth of the tree; a scan of 16,384 ids compares thousands per guide.
assert!(large < small * 32.0 && large < 256.0, "{small} comparisons per guide among 16 ids, {large} among 16,384");
}
#[test]
fn each_object_is_measured_once_however_deep_the_nesting() {
// 32 groups, each inside the one before and holding an object within the canvas; the
// innermost also holds one beyond it. Beside them, a group with nothing beyond and a clip
// group whose clipping path reaches beyond.
let mut chain = Arc::new(Node::group(NodeId(100), vec![rect(200, 0.0), rect(201, 1e17)]));
for depth in 1..32 {
chain = Arc::new(Node::group(NodeId(100 + depth), vec![rect(300 + depth, 0.0), chain]));
}
let still = Arc::new(Node::group(NodeId(400), vec![rect(401, 0.0), rect(402, 5.0)]));
let clip = Arc::new(Node::new(NodeId(600), NodeKind::Group { children: vec![rect(601, 1e17), rect(602, 0.0), rect(603, 0.0)], clip: true }));
let mut d = doc(vec![chain, Arc::clone(&still), clip]);
let mut whole = d.clone();
let measured = std::cell::Cell::new(0_usize);
let far = |n: &Node| {
measured.set(measured.get() + 1);
beyond(n)
};
let layer = &mut d.layers[0];
let found = reach(layer, &far).unwrap();
assert_eq!(
measured.get(),
36,
"the 33 objects in the groups, the 2 beside them and the clipping path, each measured once; not what the path clips"
);
assert!(!clips_beyond(layer, &found));
let (mut dropped, mut layers, mut guides) = (0, BTreeSet::new(), 0);
drop_children_beyond(layer, found, &mut dropped, &mut layers, &mut guides);
assert_eq!(measured.get(), 36, "removing measures nothing again");
assert_eq!((dropped, layers.len(), guides), (2, 0, 0));
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a group with nothing beyond is not copied");
assert_eq!(whole.drop_beyond_canvas(), BeyondCanvas { objects: 2, ..Default::default() });
assert_eq!(ids(&whole), ids(&d));
assert!(!ids(&d).contains(&201) && !ids(&d).contains(&600) && ids(&d).contains(&200) && ids(&d).contains(&331));
}
#[test]
fn each_object_is_looked_at_once_when_guides_go_from_nested_layers() {
let guide = |id: u64, pos: f64| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos, artboard: None }));
let probe = Document::new(1.0, 1.0);
// 32 sublayers, each inside the one before, each holding a guide within the canvas and one
// beyond it. Beside them, a sublayer with nothing to remove.
let mut chain = sublayer(&probe, 100, vec![guide(200, 5.0), guide(201, 1e17)], false);
for depth in 1..32 {
chain = sublayer(&probe, 100 + depth, vec![guide(300 + depth * 2, 5.0), guide(301 + depth * 2, 1e17), chain], false);
}
let still = sublayer(&probe, 500, vec![guide(501, 5.0), rect(502, 0.0)], false);
let mut d = doc(vec![chain, Arc::clone(&still)]);
let looked = std::cell::Cell::new(0_usize);
let out = |n: &Node| {
looked.set(looked.get() + 1);
matches!(n.kind, NodeKind::RulerGuide { pos, .. } if !in_range(pos))
};
let mut dropped = 0;
drop_guides(&mut d.layers[0], &out, &mut dropped);
assert_eq!(dropped, 32);
assert_eq!(looked.get(), 2 + 2 + 31 * 3 + 2, "each object in the layers is looked at once");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
let left = d.ruler_guides();
assert_eq!(left.len(), 33);
assert!(left.iter().all(|g| g.pos == 5.0));
}
}
+1423 -128
View File
File diff suppressed because it is too large. Load diff
+58
View File
@@ -251,6 +251,45 @@ fn undrawable(heights: &Heights, used: Def, depth: usize) -> bool {
heights.get(&used).is_some_and(|h| h.is_none_or(|h| depth + h > MAX_DRAWN_DEPTH))
}
/// How deep the art of a document's symbols and patterns draws, to measure objects that use them
/// outside the document's layers ([`Self::deepest`]).
#[derive(Clone, Debug, Default)]
pub struct DrawnHeights {
symbols: HashMap<String, usize>,
patterns: HashMap<String, usize>,
}
impl DrawnHeights {
/// The heights of `doc`'s symbols and patterns, as [`Document::too_deep`] counts them: the art
/// is 1 deep, and what it uses is counted under it. A symbol or pattern that uses itself, or
/// draws deeper than [`MAX_DRAWN_DEPTH`], has none.
pub fn of(doc: &Document) -> Self {
let mut out = Self::default();
for ((pattern, name), h) in heights(doc) {
if let Some(h) = h {
let map = if pattern { &mut out.patterns } else { &mut out.symbols };
map.insert(name.to_string(), h);
}
}
out
}
/// The deepest `n`, placed `depth` deep, draws: its own objects and the art of their opacity
/// masks, and under the objects the art of the symbols and patterns they use. A use of a
/// symbol or pattern without a height ([`Self::of`]) counts as the object alone. `n`'s own
/// nesting may pass [`MAX_DEPTH`]. Without recursion.
pub fn deepest(&self, n: &Node, depth: usize) -> usize {
let mut out = depth;
let mut stack = vec![(n, depth)];
while let Some((n, d)) = stack.pop() {
let used = uses(n).filter_map(|(pattern, name)| if pattern { self.patterns.get(name) } else { self.symbols.get(name) }).max();
out = out.max(d + used.copied().unwrap_or(0));
stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| (&**c, d + 1)));
}
out
}
}
/// Take out of `nodes` (each `depth` deep) the uses `bad` picks (given the depth of the object):
/// an instance goes, a pattern paint becomes no paint. Returns whether anything changed. For trees
/// within [`MAX_DEPTH`].
@@ -623,4 +662,23 @@ mod tests {
d.patterns.push(crate::PatternDef::new("q", vec![painted(3, "none")]));
assert!(!d.too_deep(None) && !d.limit_depth());
}
#[test]
fn drawn_heights_measure_objects_outside_the_layers() {
// s0 holds s1 two groups deep, which holds s2, which holds an instance of nothing known:
// s2 draws 3 deep, s1 6 and s0 9.
let d = symbols(3, 2, "none");
let heights = DrawnHeights::of(&d);
let on_layer = instance(1, "s0");
assert_eq!(heights.deepest(&on_layer, 2), 2 + 9);
// An object's own nesting and its mask's art count past MAX_DEPTH.
let mut deep = Node::group(NodeId(5), vec![nested(MAX_DEPTH + 10)]);
deep.extras_mut().mask = Some(Box::new(OpacityMask::new((*instance(6, "s2")).clone(), true)));
assert_eq!(heights.deepest(&deep, 1), 1 + 1 + MAX_DEPTH + 10);
let shallow = Node::group(NodeId(5), vec![instance(7, "s1")]);
assert_eq!(heights.deepest(&shallow, 100), 101 + 6);
// A symbol that holds itself has no height, so its instance counts alone.
let looped = DrawnHeights::of(&symbols(2, 1, "s0"));
assert_eq!(looped.deepest(&instance(1, "s0"), 2), 2);
}
}
+4
View File
@@ -815,6 +815,10 @@ impl Dimension {
if self.line_between_points() && !old.line_between_points() {
self.keep_gap(&old);
}
} else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 {
// A reflection turns the left normal of a → b to the other side, so an aligned
// dimension's line stays on the reflected side of its points.
self.offset = -self.offset;
}
if self.mode == DimensionMode::Linear {
self.length = self.measured();
+9 -4
View File
@@ -78,6 +78,8 @@ impl Document {
units_from_file: _,
index: _,
guide_cache: _,
inline_cycles: _,
mounted_art: _,
} = self;
*version == other.version
&& *title == other.title
@@ -262,6 +264,8 @@ impl Document {
units_from_file: false,
index: Default::default(),
guide_cache: Default::default(),
inline_cycles: Default::default(),
mounted_art: vec![],
};
let id = d.alloc_id();
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
@@ -286,7 +290,9 @@ impl Document {
self.next_id = self.next_id.max(id);
}
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give
/// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns)
/// whose id is missing or already taken a new one, so each stored object has an id of its own.
pub fn fix_next_id(&mut self) {
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
// counter up there: new ids start under them and never reach them, where counting on from
@@ -297,13 +303,12 @@ impl Document {
max = max.max(id);
}
};
for l in &self.layers {
l.walk(&mut |n| see(n.id.0));
}
self.visit_stored(|n, _| see(n.id.0));
self.slices.iter().for_each(|s| see(s.id.0));
self.assets.iter().for_each(|a| see(a.id));
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
self.next_id = counter.max(max.saturating_add(1));
self.renumber_stored_duplicates();
}
/// Find a node anywhere in the tree.
+4 -2
View File
@@ -128,8 +128,8 @@ impl Document {
}
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
/// pattern swatches, the original of the pattern being edited and [`Self::mounted_art`].
/// Opacity masks hang off nodes in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
@@ -137,6 +137,7 @@ impl Document {
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
.chain(self.mounted_art.iter().map(|(n, _)| n))
}
/// [`Self::art_roots`], to change.
@@ -147,6 +148,7 @@ impl Document {
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
+403 -86
View File
@@ -1,6 +1,7 @@
use super::document_ext::free_id;
use super::guides::Guide;
use super::limits::MAX_NEXT_ID;
use super::node::{held_guides, map_held, strip_held};
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
use std::collections::{BTreeMap, HashSet};
@@ -183,8 +184,8 @@ impl Document {
self.layers.retain(|l| !l.is_ruler_guide());
gone -= self.layers.len();
for l in &mut self.layers {
if layer_untidy(l) {
gone += tidy_layer(Arc::make_mut(l));
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
gone += tidy_layer(Arc::make_mut(l), found);
}
}
let others = self
@@ -198,8 +199,8 @@ impl Document {
if root.is_ruler_guide() {
*root = Arc::new(Node::group(root.id, vec![]));
gone += 1;
} else if any_guide(root) {
gone += drop_guides_below(Arc::make_mut(root));
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
gone += drop_guides_below(Arc::make_mut(root), found);
}
}
gone
@@ -272,8 +273,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if l.holds_ruler_guides() {
Arc::make_mut(l).strip_ruler_guides();
if let Some(held) = held_guides(l, &Node::is_ruler_guide) {
strip_held(Arc::make_mut(l), held);
}
}
self.saved_guides.extend(guides);
@@ -347,16 +348,14 @@ impl Document {
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
if !layer.holds_ruler_guides() {
return Ok(layer);
}
let Some(held) = held_guides(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
Arc::make_mut(&mut layer).strip_ruler_guides();
strip_held(Arc::make_mut(&mut layer), held);
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
@@ -418,21 +417,11 @@ impl Document {
if gone.is_empty() {
return 0;
}
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
}
if !holds(layer, gone) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
for c in ch.iter_mut().filter(|c| c.is_layer()) {
drop(c, gone);
}
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
drop(l, &gone);
if let Some(held) = held_guides(l, &pick) {
strip_held(Arc::make_mut(l), held);
}
}
sel.guides.retain(|id| !gone.contains(id));
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
@@ -444,29 +433,11 @@ impl Document {
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
/// position).
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
fn holds(n: &Node, id: u32) -> bool {
n.is_layer()
&& n.children().is_some_and(|ch| {
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
})
}
if !holds(layer, id) {
return;
}
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for c in ch.iter_mut() {
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
} else if c.is_layer() {
visit(c, id, f);
}
}
}
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
visit(l, id, f);
if let Some(held) = held_guides(l, &pick) {
map_held(Arc::make_mut(l), held, f);
}
}
}
@@ -554,6 +525,13 @@ impl Document {
t.cached_baselines.clear();
t.cached_ink = None;
}
// Opacity-mask art is stored art too: the copy's gets ids of its own.
if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) {
let art = Arc::new(self.reid(&art));
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
m.art = art;
}
}
let on_path = n.extras().objects_on_path.is_some();
let mut renamed = std::collections::HashMap::new();
if let Some(ch) = n.children_mut() {
@@ -573,65 +551,121 @@ impl Document {
}
}
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
fn any_guide(n: &Node) -> bool {
let mut any = false;
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
any
/// What a walk picked in a node: its children by index in order, each with what was picked
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
#[derive(Debug, Default)]
struct Picked {
children: Vec<(usize, Picked)>,
mask: Option<Box<Picked>>,
}
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_guides_below(n: &mut Node) -> usize {
let mut gone = drop_mask_guides(n);
impl Picked {
fn is_empty(&self) -> bool {
self.children.is_empty() && self.mask.is_none()
}
/// `self`, or `None` when nothing was picked.
fn some(self) -> Option<Self> {
(!self.is_empty()).then_some(self)
}
}
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
/// ([`guides_below`]).
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
}
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
/// (each with nothing inside), and the members and mask art holding one further down (with what
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
/// nothing inside a ruler guide.
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
Picked { children, mask }.some()
}
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(n, found.mask);
if let Some(ch) = n.children_mut() {
let before = ch.len();
ch.retain(|c| !c.is_ruler_guide());
gone += before - ch.len();
for c in ch.iter_mut().filter(|c| any_guide(c)) {
gone += drop_guides_below(Arc::make_mut(c));
}
let mut found = found.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
if inner.is_empty() {
gone += 1;
return false;
}
gone += drop_guides_below(Arc::make_mut(c), inner);
true
});
}
gone
}
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
/// becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node) -> usize {
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
let Some(found) = found else { return 0 };
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
if mask.art.is_ruler_guide() {
if found.is_empty() {
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
1
} else if any_guide(&mask.art) {
drop_guides_below(Arc::make_mut(&mut mask.art))
} else {
0
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
}
}
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
/// in one of its sublayers?
fn layer_untidy(l: &Node) -> bool {
let Some(ch) = l.children() else { return false };
let start = Node::guide_run_start(ch);
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
/// none: those below art (each with nothing inside), those in its mask art and in its objects
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
/// not looked at.
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
let ch = l.children()?;
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
let children = ch
.iter()
.enumerate()
.take(Node::guide_run_start(ch))
.filter_map(|(i, c)| {
let found = if is_guide(c) {
Some(Picked::default())
} else if c.is_layer() {
untidy(c, is_guide)
} else {
guides_below(c, is_guide)
};
found.map(|p| (i, p))
})
.collect();
Picked { children, mask }.some()
}
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
fn tidy_layer(l: &mut Node) -> usize {
let mut gone = drop_mask_guides(l);
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
/// were removed.
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
let mut gone = drop_mask_guides(l, found.mask);
let Some(ch) = l.children_mut() else { return gone };
for c in ch.iter_mut() {
if c.is_layer() {
if layer_untidy(c) {
gone += tidy_layer(Arc::make_mut(c));
}
} else if !c.is_ruler_guide() && any_guide(c) {
gone += drop_guides_below(Arc::make_mut(c));
let mut below_art = false;
for (i, inner) in found.children {
let Some(c) = ch.get_mut(i) else { continue };
if inner.is_empty() {
below_art = true;
} else if c.is_layer() {
gone += tidy_layer(Arc::make_mut(c), inner);
} else {
gone += drop_guides_below(Arc::make_mut(c), inner);
}
}
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
if below_art {
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
*ch = art;
ch.extend(guides);
@@ -691,3 +725,286 @@ impl std::fmt::Debug for GuideCache {
f.write_str("GuideCache")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Appearance, OpacityMask, Symbol};
use std::cell::Cell;
use vectorcraft_geom::shapes;
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
const CHAIN: u64 = 30;
fn rect(id: u64) -> Arc<Node> {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
}
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
}
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
Arc::new(Node::group(NodeId(id), children))
}
/// `n` with `art` as its opacity-mask art.
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
let mut n = (*n).clone();
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
Arc::new(n)
}
/// A sublayer like a new document's first layer, holding `children`.
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
l.id = NodeId(id);
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
}
/// A document whose first layer holds `children`.
fn doc(children: Vec<Arc<Node>>) -> Document {
let mut d = Document::new(100.0, 100.0);
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
*ch = children;
}
d
}
/// The ids of the nodes in the layers, in tree order.
fn ids(d: &Document) -> Vec<u64> {
fn walk(n: &Node, out: &mut Vec<u64>) {
out.push(n.id.0);
for c in n.children().into_iter().flatten() {
walk(c, out);
}
}
let mut out = vec![];
for l in &d.layers {
walk(l, &mut out);
}
out
}
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
/// sublayer with a canvas guide only. Returns the document and that sublayer.
fn nested() -> (Document, Arc<Node>) {
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
(doc(vec![chain, Arc::clone(&still)]), still)
}
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
fn on_artboard_7(n: &Node) -> bool {
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
}
#[test]
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = held_guides(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
strip_held(Arc::make_mut(&mut d.layers[0]), held);
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
// The command's own entry point removes the same guides.
let before = whole.clone();
let mut sel = Selection::default();
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
sel.objects.push(NodeId(150));
sel.key_guide = Some(NodeId(201));
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
assert_eq!(ids(&whole), ids(&d));
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
// The document as it was (an undo step's copy) still holds every guide.
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
// Saving the guides as a list, and removing a layer but not its guides, take the guides
// out of the nested layers too.
let mut saved = before.clone();
saved.guides_to_saved();
assert_eq!(saved.saved_guides, before.ruler_guides());
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
let mut edited = before.clone();
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
assert!(!chain.holds_ruler_guides());
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
// Keeping every guide changes nothing and copies no layer.
let kept = whole.clone();
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
// Removing every guide leaves the objects.
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
assert_eq!(sel.objects, [NodeId(150)]);
// A document without layers, and one without guides, have nothing to remove.
let mut empty = Document::new(10.0, 10.0);
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
empty.layers.clear();
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
}
#[test]
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
let (mut d, still) = nested();
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let pick = |n: &Node| {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = held_guides(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
map_held(Arc::make_mut(&mut d.layers[0]), held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
// The public moves change the same guides by the same amount.
let before = whole.clone();
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert_eq!(whole, d);
assert_eq!(ids(&whole), ids(&before));
for g in whole.ruler_guides() {
let id = g.id.map_or(0, |id| id.0) as f64;
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
}
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
whole.map_artboard_guides(7, Affine::scale(2.0));
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
// An artboard without guides, and a document without layers, change nothing and copy no layer.
let kept = whole.clone();
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
let mut empty = Document::new(10.0, 10.0);
empty.layers.clear();
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
assert!(empty.layers.is_empty());
}
#[test]
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
// Groups, each inside the one before and holding an object and a guide. Beside them, an
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
let mut chain = group(100, vec![rect(150), guide(200, None)]);
for depth in 1..CHAIN {
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = group(700, vec![rect(701)]);
let root = group(
1,
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
);
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// The chain's groups, objects and guides; a masked object, its mask group and the two in
// it; a masked object and its mask guide; the last group and its object.
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
let found = guides_below(&root, &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
let mut cleared = (*root).clone();
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
let ch = cleared.children().unwrap();
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
assert_eq!(
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
Some(Some(vec![803]))
);
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
assert_eq!(*d.symbols[0].art, cleared);
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
}
#[test]
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
// Sublayers, each inside the one before, with their guides in place; the innermost also
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
// guide in place, and a sublayer whose mask art holds a guide.
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
for depth in 1..CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
}
let still = sublayer(500, vec![rect(502), guide(501, None)]);
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
let mut whole = d.clone();
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
// the innermost sublayer and 2 in each sublayer around it.
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
let found = untidy(&d.layers[0], &is_guide).unwrap();
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
// Opening a file does the same.
let before = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 2);
assert_eq!(whole, d);
let all = ids(&whole);
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
// A tidy document is left alone, and no layer is copied.
let kept = whole.clone();
assert_eq!(whole.tidy_ruler_guides(), 0);
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
}
}
+116
View File
@@ -150,6 +150,10 @@ pub struct LabelStyles {
pub categories: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<crate::CharStyle>,
/// The fill of [`Self::legend`] was set on the legend labels, so it is drawn on every pie wedge with Legends in
/// Wedges. `false`: a black fill there is the default, and the labels on dark wedges are drawn white.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub legend_fill_set: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub values_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -166,12 +170,34 @@ pub struct LabelStyles {
/// The anti-aliasing method the legend labels keep once set. `None` draws them Sharp.
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_anti_alias: Option<crate::text::TypeAntiAlias>,
/// The object fill and stroke rows the value axis numbers keep once set with the Appearance controls ([`LabelRows`]).
/// `None`: no rows, opaque and Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub values_rows: Option<LabelRows>,
/// The object fill and stroke rows the category labels keep, as [`Self::values_rows`].
#[serde(skip_serializing_if = "Option::is_none")]
pub categories_rows: Option<LabelRows>,
/// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`].
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_rows: Option<LabelRows>,
}
impl LabelStyles {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Is the kept legend fill the legend labels' own: set on them ([`Self::legend_fill_set`]), or not black (a file
/// saved without the mark)? Otherwise it is the default black, which edits that map the kept paints leave as it is.
pub fn legend_fill_is_own(&self) -> bool {
self.legend.as_ref().is_some_and(|st| self.legend_fill_set || st.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK))
}
/// Mark a kept legend fill that is the labels' own ([`Self::legend_fill_is_own`]) as set on them, before an edit
/// that maps the kept paints can turn it black.
pub fn mark_own_legend_fill(&mut self) {
self.legend_fill_set = self.legend_fill_is_own();
}
}
/// Graph Type › Position for pie graphs with several pies: the same size (Even), sized by their totals (Ratio), or
@@ -353,6 +379,46 @@ pub struct SeriesPaint {
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub blend: Option<vectorcraft_color::BlendMode>,
/// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque.
/// Graph labels keep none.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_opacity: Option<f32>,
/// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_blend: Option<vectorcraft_color::BlendMode>,
/// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub group_isolate: bool,
/// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral.
#[serde(skip_serializing_if = "Option::is_none")]
pub group_knockout: Option<crate::Knockout>,
/// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub group_knockout_shape: bool,
/// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own
/// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub fill_unit_box: bool,
/// A gradient in [`Self::stroke`] is placed relative to the unit box, as [`Self::fill_unit_box`], and each mark takes
/// it on its stroke's box (the geometric bounds grown by half the weight).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub stroke_unit_box: bool,
}
/// The object rows one kind of graph label keeps ([`LabelStyles::values_rows`]): the paint, weight, opacity and blend mode
/// of a label's topmost visible fill and stroke row (an absent paint: no row of that kind), the label's object opacity and
/// blend mode, and where the two rows paint relative to each other and to the characters.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LabelRows {
#[serde(flatten)]
pub paint: SeriesPaint,
/// How many of the kept rows paint below the characters, counted from the bottom. Absent: none.
#[serde(skip_serializing_if = "Option::is_none")]
pub below: Option<u8>,
/// The stroke row paints below the fill row.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub stroke_under: bool,
}
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
@@ -477,6 +543,10 @@ pub struct GraphSpec {
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
#[serde(skip_serializing_if = "Option::is_none")]
pub placed: Option<Rect>,
/// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
#[serde(skip_serializing_if = "Option::is_none")]
pub placed_art: Option<Rect>,
}
fn at_most_one(n: &usize) -> bool {
@@ -492,12 +562,57 @@ fn edge_to_edge_before_the_option() -> bool {
true
}
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
pub fn graph_art_without_type(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b))
}
/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A
/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the
/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them,
/// give their own bounds.
fn without_type(n: &crate::Node) -> (Option<Rect>, bool) {
use crate::NodeKind::{Compound, Group, Layer, Text};
if matches!(n.kind, Text(_)) {
return (None, true);
}
let children: &[std::sync::Arc<crate::Node>] = match &n.kind {
Group { clip: true, children } | Layer { clip: true, children, .. } => children,
Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(),
_ => return (n.geometric_bounds(), false),
};
let mut bounds: Option<Rect> = None;
let mut had_type = false;
let mut clip_has_type = false;
let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. });
for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) {
let (b, t) = without_type(c);
had_type |= t;
clip_has_type |= i == 0 && t;
bounds = match (bounds, b) {
(Some(a), Some(b)) => Some(a.union(b)),
(a, b) => a.or(b),
};
}
let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. });
if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) }
}
impl GraphSpec {
/// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's.
pub fn series_kind(&self, s: usize) -> GraphKind {
self.series_kinds.get(s).copied().flatten().filter(|k| k.combines_with(self.kind)).unwrap_or(self.kind)
}
/// Does the graph pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie
/// with Legends in Wedges whose legend labels keep no fill of their own ([`LabelStyles::legend_fill_is_own`])? Only
/// then is a black legend fill it keeps the default, which edits that map the kept paints leave as it is; other
/// graphs draw the kept fill as it is.
pub fn picks_legend_fill(&self) -> bool {
self.kind == GraphKind::Pie && self.legend && self.pie_legend_in_wedges && !self.label_styles.legend_fill_is_own()
}
/// The data with blank cells as `None`, every row as long as the longest (at most [`MAX_GRAPH_CATEGORIES`] rows
/// of [`MAX_GRAPH_SERIES`] cells).
pub fn cells(&self) -> Vec<Vec<Option<f64>>> {
@@ -601,6 +716,7 @@ impl Default for GraphSpec {
connect_points: true,
edge_to_edge: false,
placed: None,
placed_art: None,
}
}
}
+399 -107
View File
@@ -1,7 +1,7 @@
//! Hit testing over the document tree.
use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
@@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &
return false;
}
// How a click reaches it, if one does.
let start = opt;
let Some(opt) = path_options(&nodes, &chain, opt) else { return false };
// Hidden by a mask: one of the containers around it clips, and not to `p`.
let masked = nodes
.iter()
.rev()
.skip(1)
.any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p)));
// Hidden by a mask: one of the containers around it clips, and not to `p`. A container
// tests its clipping path in outline from the first layer with Preview off down to it, as
// a click going down to it does ([`path_options`]).
let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| {
let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n)));
n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline))
});
// A click may reach it there ([`may_hit`]: not a guide while guides are locked or
// hidden, nor a Shaper group's hidden part), and its own art is what a click would hit
// in it: a group's hidden, locked or masked contents don't count.
@@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
/// measured by their art ([`Node::geometric_bounds_with`]).
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
let Some(children) = layer.children() else { return true };
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
if layer.clips()
&& let Some(clip) = children.first()
{
@@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) {
tops.push(clip.id);
}
if !clip_contains(clip, p) {
if !clip_contains(clip, p, opt.outline) {
return true;
}
}
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
for (i, c) in children.iter().enumerate().rev() {
if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) {
continue;
@@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
let Some(children) = parent.children() else { return };
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
return;
}
for i in hit_order(parent, children, p) {
@@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool {
matches!(n.kind, NodeKind::Envelope { editing: true, .. })
}
/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame:
/// glyph outlines need the font engine, above this crate.
fn clip_contains(clip: &Node, p: Point) -> bool {
clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`])
/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count.
fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool {
let areas = if outline { clip_regions(clip) } else { clip_areas(clip) };
areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
}
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry
/// effects of the clipping path and of what it clips by applied, as one path and fill rule
/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a
/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated
/// above this crate, so the engine registers one with [`set_clip_region`].
pub type ClipRegion = fn(&Node) -> Option<Option<(BezPath, FillRule)>>;
static CLIP_REGION: OnceLock<ClipRegion> = OnceLock::new();
/// Register how the region of a clipping path with live effects is found (the first registration
/// stays).
pub fn set_clip_region(f: ClipRegion) {
// Already set: the same engine, registered by another session.
let _ = CLIP_REGION.set(f);
}
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
/// then can the registered [`ClipRegion`] find a geometry effect in it.
fn has_effects(clip: &Node) -> bool {
let mut found = false;
clip.walk(&mut |n| {
let visible = |e: &crate::Effect| e.visible;
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
});
found
}
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
/// path elements.
struct EvaluatedClip {
clip: Node,
inputs: u64,
region: Option<Rc<Option<(BezPath, FillRule)>>>,
size: usize,
}
/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip
/// group whose clipping path has live effects asks for its region, and clip groups can be nested.
const CLIPS_KEPT: usize = 16;
thread_local! {
/// The regions [`clip_region`] keeps, the latest first.
static CLIPS: RefCell<Vec<EvaluatedClip>> = const { RefCell::new(Vec::new()) };
}
#[cfg(test)]
thread_local! {
/// How many regions [`clip_region`] evaluated on this thread.
static CLIPS_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The region clipping path `clip` clips to with its live geometry effects applied
/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes
/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the
/// [`LiveInputs`] have changed since.
fn clip_region(clip: &Node) -> Option<Rc<Option<(BezPath, FillRule)>>> {
let f = CLIP_REGION.get()?;
if !has_effects(clip) {
return None;
}
let inputs = live_inputs();
let kept = CLIPS.with_borrow_mut(|kept| {
let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?;
let e = kept.remove(i);
let region = e.region.clone();
kept.insert(0, e);
Some(region)
});
if let Some(region) = kept {
return region;
}
#[cfg(test)]
CLIPS_EVALUATED.with(|c| c.set(c.get() + 1));
let region = f(clip).map(Rc::new);
let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len());
let size = elements.saturating_add(art_size(std::slice::from_ref(clip)));
if size <= LIVE_KEPT_SIZE {
let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size };
CLIPS.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(CLIPS_KEPT);
let mut total = 0usize;
kept.retain(|e| {
total = total.saturating_add(e.size);
total <= LIVE_KEPT_SIZE
});
});
}
region
}
/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the
/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path.
struct ClipBox {
clip: Node,
inputs: u64,
rect: Option<Rect>,
size: usize,
}
/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip
/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not
/// only the latest few as with the regions.
const CLIP_BOXES_KEPT: usize = 4096;
thread_local! {
/// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes.
static CLIP_BOXES: RefCell<(HashMap<NodeId, ClipBox>, usize)> = RefCell::new((HashMap::new(), 0));
}
/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]),
/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change.
/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the
/// pointer moving over more clip groups than fit still finds most of their boxes.
pub(crate) fn reshaped_clip_box(clip: &Node) -> Option<Rect> {
use vectorcraft_geom::kurbo::Shape;
CLIP_REGION.get()?;
if !has_effects(clip) {
return None;
}
let inputs = live_inputs();
let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect));
if let Some(rect) = kept {
return rect;
}
let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box()));
let size = art_size(std::slice::from_ref(clip));
if size <= LIVE_KEPT_SIZE {
CLIP_BOXES.with_borrow_mut(|(boxes, total)| {
if let Some(old) = boxes.remove(&clip.id) {
*total = total.saturating_sub(old.size);
}
while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
let Some(other) = boxes.keys().next().copied() else { break };
if let Some(old) = boxes.remove(&other) {
*total = total.saturating_sub(old.size);
}
}
boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size });
*total = total.saturating_add(size);
});
}
rect
}
/// The regions a click inside a clip group must fall in: those `clip` clips to with its live
/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]).
fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> {
match clip_region(clip) {
Some(region) => region.as_ref().iter().cloned().collect(),
None => clip_regions(clip),
}
}
/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live
/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate.
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
@@ -698,7 +857,7 @@ fn hit_children(
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
// the selection tools in isolation mode within it.
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
if !edited && !clip_contains(clip, p) {
if !edited && !clip_contains(clip, p, opt.outline) {
return None;
}
}
@@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
match &n.kind {
// A clip group only hits inside its clipping path.
NodeKind::Group { children, clip } => {
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
return None;
}
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
@@ -974,43 +1133,45 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
struct InstanceArt {
struct InstanceArt<'a> {
art: Node,
map: Option<crate::NineSliceMap>,
xf: vectorcraft_geom::Affine,
/// Quick boxes, which measure the instances in the art as it is placed through the guides.
boxes: SymbolBoxes<'a>,
}
impl InstanceArt {
impl<'a> InstanceArt<'a> {
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
fn of(doc: &Document, inst: &Node) -> Option<Self> {
fn of(doc: &'a Document, inst: &Node) -> Option<Self> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
let map = doc.symbol_slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
let boxes = doc.symbol_boxes().quick();
let art = crate::symbol_overrides::dynamic_art(boxes.symbol_art(symbol)?, inst);
let map = boxes.slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed_with(&art, &boxes) > crate::MAX_SYMBOL_NODES) {
return None;
}
Some(Self { art, map, xf: *xf })
Some(Self { art, map, xf: *xf, boxes })
}
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
/// object by object.
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
fn whole(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
/// [`Document::place_symbol_art`] refuses it.
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
(Some(m), None) => (m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes)),
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1018,10 +1179,13 @@ impl InstanceArt {
/// Object `n` of the art placed on the canvas without clip groups
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
/// same limit ([`Document::place_symbol_art_unclipped`]).
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place_unclipped(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
(Some(m), None) => {
let m = m.unclipped();
(m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes))
}
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1043,45 +1207,45 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// group's original shapes, which the canvas does not draw, and guide paths with
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
/// no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
struct Find<'a> {
doc: &'a Document,
art: &'a InstanceArt,
art: &'a InstanceArt<'a>,
p: Point,
opt: HitOptions,
symbols: &'a SymbolBoxes<'a>,
}
impl Find<'_> {
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
}
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
return false;
}
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
let outline = outline || previews_off(n);
let opt = HitOptions { outline, ..self.opt };
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole);
return self.hit(n, whole, opt);
}
let whole = self.art.whole(n, self.doc, whole);
let whole = self.art.whole(n, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
if self.opt.clip_outlines
&& first.visible
&& !first.locked
&& !self.skips_guide(first)
&& clip_outline(&clip, self.p, self.opt).is_some()
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
{
path.push(0);
return true;
}
if !clip_contains(&clip, self.p) {
if !clip_contains(&clip, self.p, outline) {
return false;
}
}
@@ -1092,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
}
let Ok(i) = u32::try_from(i) else { continue };
path.push(i);
if self.find(c, path, whole) {
if self.find(c, path, whole, outline) {
return true;
}
path.pop();
@@ -1103,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
}
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
/// does not count.
fn below_preview_off(doc: &Document, n: &Node, scope: Option<NodeId>) -> bool {
let Some(chain) = doc.ancestry(n.id) else { return false };
let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off))
}
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
@@ -1112,36 +1286,64 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
/// picks it.
/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it
/// has any.
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
symbol_part_outline_in_view(doc, inst, path, HitOptions::default())
}
/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view
/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
/// the object leave no region.
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
let art = InstanceArt::of(doc, inst)?;
let part = crate::symbol_overrides::part(&art.art, path)?;
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
let mut out = BezPath::new();
let mut limit = None;
let mut whole = None;
let mut n = &art.art;
for &i in path {
let children = n.children()?;
whole = art.whole(n, doc, whole);
whole = art.whole(n, whole);
outline = outline || previews_off(n);
if i != 0
&& n.clips()
&& let Some(first) = children.first()
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
{
match meet(Some(clip), limit) {
Some(r) => limit = Some(r),
None => return Some(out),
}
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
limit = within;
}
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
Some(out)
}
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the
/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no
/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art
/// is drawn: the effects leave no region, or the box is outside `limit`.
fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Option<Rect>> {
use vectorcraft_geom::kurbo::Shape;
let region = if outline { None } else { clip_region(clip) };
let bounds = match region.as_deref() {
Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()),
Some(_) => return None,
None => clip.geometric_bounds(),
};
match bounds {
Some(b) => meet(Some(b), limit).map(Some),
None => Some(limit),
}
}
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
use vectorcraft_geom::kurbo::Shape;
if let Some(pd) = n.path_data() {
match limit {
@@ -1155,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
out.extend(b.to_path(0.1));
}
let Some(children) = n.children() else { return };
let outline = outline || previews_off(n);
if n.clips()
&& let Some((first, rest)) = children.split_first()
{
let inner = match first.geometric_bounds() {
Some(c) => match meet(Some(c), limit) {
Some(r) => Some(r),
None => return,
},
None => limit,
};
rest.iter().for_each(|c| outline_within(c, inner, out));
let Some(inner) = limit_within(first, limit, outline) else { return };
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
return;
}
children.iter().for_each(|c| outline_within(c, limit, out));
children.iter().for_each(|c| outline_within(c, limit, outline, out));
}
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
@@ -1244,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
/// the selection tools' clicks.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false)
marquee_with(doc, r, scope, leaves, false, false)
}
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
/// the clicks of [`HitOptions::outline`] do.
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false, outline)
}
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true)
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, true, true, outline)
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
fn previews_off(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { preview: false, .. })
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
let mut out = Vec::new();
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
// The objects the marquee may touch ([`Top`]).
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
// marquee touches none of it, as clicks don't (#5309).
Some(s) if !doc.is_editable(s.id) => vec![],
Some(s) => match s.children() {
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
Some(c) => c
.iter()
.enumerate()
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
.map(|(_, c)| (c, Some(r), outline, None))
.collect(),
// A single object isolated: only it.
None => doc
.parent_of(s.id)
.and_then(|p| doc.node(p))
.and_then(|p| p.children())
.into_iter()
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
.collect(),
},
// The objects of the layers, looking through sublayers (hidden, locked and template ones
@@ -1277,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
.layers
.iter()
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
.flat_map(|l| layer_objects(l, r))
.flat_map(|l| layer_objects(l, r, outline))
.collect(),
};
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
/// the sublayers it is in leave.
fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc<Node>, Rect)> {
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
/// shapes ([`mask_marquee`]).
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
let mut out = vec![];
let Some(r) = marquee_in(l, r) else { return out };
for c in l.children().into_iter().flatten() {
let outline = outline || previews_off(l);
let inner = marquee_in_parent(l, r, outline);
for (i, c) in l.children().into_iter().flatten().enumerate() {
if c.is_layer() {
if c.visible && !c.locked && !c.is_template() {
out.extend(layer_objects(c, r));
if let Some(inner) = inner
&& c.visible
&& !c.locked
&& !c.is_template()
{
out.extend(layer_objects(c, inner, outline));
}
} else if !c.is_ruler_guide() {
out.push((c, r));
if i == 0 && l.clips() {
out.push((c, mask_marquee(l, r), outline, Some(r)));
} else if inner.is_some() {
out.push((c, inner, outline, None));
}
}
}
out
}
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
fn mask_marquee(parent: &Node, r: Rect) -> Option<Rect> {
marquee_in_parent(parent, r, true)
}
/// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a
/// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where
/// the clip shows? Never in outline, nor without live effects: its own geometry counts then.
fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool {
if outline {
return false;
}
clip_region(clip).is_some_and(|region| {
region.as_ref().as_ref().is_some_and(|(bp, _)| {
// The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it.
let mut edge = PathData::from_bezpath(bp);
edge.subpaths.iter_mut().for_each(|sp| sp.closed = true);
vectorcraft_geom::hit::intersects_rect(&edge, r)
})
})
}
/// Is `n` collected whole by [`collect_leaves`], not by its members?
fn is_leaf(n: &Node) -> bool {
!matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. })
}
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
/// compound paths, layers and groups are touched by their box.
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
match &n.kind {
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
marquee_in(n, r).is_some_and(|r| {
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
let outline = outline || previews_off(n);
let inner = marquee_in_parent(n, r, outline);
children.iter().enumerate().any(|(i, c)| {
c.visible
&& !shaper_hides(n, i, scope)
&& if i == 0 && n.clips() {
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
} else {
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
}
})
}
NodeKind::Compound { children, .. } if whole_compounds => {
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
}
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
// A box with no width or no height (an instance of a symbol that draws a straight
// line) is touched where the marquee crosses it.
_ => n.geometric_bounds_with(s).is_some_and(|b| {
@@ -1321,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}),
}
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
let Some(r) = marquee_in(n, r) else { return };
let outline = outline || previews_off(n);
let inner = marquee_in_parent(n, r, outline);
for (i, c) in children.iter().enumerate() {
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
collect_leaves(c, s, r, scope, whole_compounds, out);
if !c.visible || c.locked || shaper_hides(n, i, scope) {
continue;
}
if i == 0 && n.clips() {
let before = out.len();
if let Some(r) = mask_marquee(n, r) {
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
}
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
out.push(c.id);
}
} else if let Some(r) = inner {
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
}
}
}
_ => {
if touches(n, s, r, scope, whole_compounds) {
if touches(n, s, r, scope, whole_compounds, outline) {
out.push(n.id);
}
}
@@ -1340,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}
let symbols = doc.symbol_boxes();
let locks = doc.locked_artboards();
for (t, r) in tops {
for (t, r, outline, edge) in tops {
if !t.visible || t.locked || locks.holds_id(t.id) {
continue;
}
if leaves {
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
} else if touches(t, &symbols, r, scope, whole_compounds) {
let before = out.len();
if let Some(r) = r {
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
}
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
out.push(t.id);
}
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
{
out.push(t.id);
}
}
out
}
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`.
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
marquee_in_parent(parent, r, true)
}
/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its
/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline`
/// ([`marquee_in_view`]).
fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline),
_ => Some(r),
}
}
/// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of
/// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip`
/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those
/// bounds, art outside a region that is not a rectangle still counts.
fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of
/// those regions. Within those bounds, art outside a region that is not a rectangle still counts.
fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option<Rect> {
use vectorcraft_geom::kurbo::Shape;
let regions = clip_regions(clip);
let regions = if outline { clip_regions(clip) } else { clip_areas(clip) };
// The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it.
let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| {
let mut edge = vectorcraft_geom::PathData::from_bezpath(bp);
+350
View File
@@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) {
(mask, art)
}
/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping
/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip
/// by; without either, no geometry effect.
fn moved_clip_region(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
let (mut moves, mut empty) = (false, false);
clip.walk(&mut |n| {
moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move");
empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty");
});
if empty {
return Some(None);
}
if !moves {
return None;
}
Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
(bp, rule)
}))
}
/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region.
fn test_move() -> crate::Effect {
crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }
}
/// Clicks inside a clip group whose clipping path has a live effect fall in the region the
/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and
/// again after the clipping path changes; a clipping path without effects is not evaluated.
#[test]
fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() {
set_clip_region(moved_clip_region);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
for x in [148.0, 150.0, 152.0] {
assert_eq!(leaf(&d, x), Some(art_id), "in the moved region");
}
assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place");
assert_eq!(evaluated(), before + 1);
// Outline mode draws no effects: the art's edge shows within the clipping path's own shape.
let outline = HitOptions { outline: true, ..HitOptions::default() };
assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode");
// So with a marquee across the art's left edge: in the view, only in Outline view. The
// clipping path's own left edge lies there too, and counts in both.
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
// `marquee_in` measures by the plain shapes, as its callers clip by them.
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
// Hidden, the effect no longer moves the region.
d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false;
assert_eq!(leaf(&d, 50.0), Some(art_id));
assert_eq!(leaf(&d, 150.0), None);
assert_eq!(evaluated(), before + 1);
// Shown again and widened, the region is evaluated again.
let mask = d.node_mut(mask_id).unwrap();
mask.appearance.effects[0].visible = true;
if let NodeKind::Path { path, .. } = &mut mask.kind {
*path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0));
}
assert_eq!(leaf(&d, 180.0), Some(art_id));
assert_eq!(leaf(&d, 195.0), None);
assert_eq!(evaluated(), before + 2);
}
/// A marquee around a clipping path that an effect moved into the middle of large art touches the
/// clipping path on the edge of its moved region, in a clip group and in a clipping layer.
#[test]
fn a_marquee_touches_a_moved_clipping_path_on_its_region() {
set_clip_region(moved_clip_region);
let parts = |d: &mut Document| {
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default());
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art());
(mask, art)
};
// Around the moved region (120..160) and the clipping path's own place, inside the art.
let around = Rect::new(10.0, 10.0, 170.0, 70.0);
let mut d = Document::new(400.0, 400.0);
let l = d.layers[0].id;
let (mask, art) = parts(&mut d);
let (g, mask_id) = (d.alloc_id(), mask.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
assert_eq!(marquee(&d, around, None, false), [g]);
assert_eq!(marquee(&d, around, None, true), [mask_id]);
// Only over the clipping path's own place, the marquee misses the region but touches the
// clipping path's anchors, which a click on its outline also finds.
let own = Rect::new(10.0, 10.0, 70.0, 70.0);
assert_eq!(marquee(&d, own, None, false), [g]);
assert_eq!(marquee(&d, own, None, true), [mask_id]);
// Away from both, nothing.
assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty());
let mut d = Document::new(400.0, 400.0);
let top = d.layers[0].id;
let (mask, art) = parts(&mut d);
let mask_id = mask.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
}
d.insert(Some(top), 0, sublayer).unwrap();
assert_eq!(marquee(&d, around, None, false), [mask_id]);
}
/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point
/// and marquees count its clipping path by its plain shape, without the effect that moves it.
#[test]
fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() {
set_clip_region(moved_clip_region);
let mut d = Document::new(300.0, 200.0);
let top = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art_id = art.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind {
(*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false);
}
d.insert(Some(top), 0, sublayer).unwrap();
// The art's top edge, within the clipping path's own shape.
let p = Point::new(50.0, 0.5);
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id));
assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id));
assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id));
}
/// The pointer moving over empty canvas past more clip groups with live effects than the regions
/// kept measures each group's box once: the boxes are kept for every clip group.
#[test]
fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() {
set_clip_region(moved_clip_region);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
for i in 0..(2 * CLIPS_KEPT) {
let x = 20.0 * i as f64;
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default());
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art());
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
}
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let empty = Point::new(500.0, 500.0);
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = evaluated();
for _ in 0..3 {
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
}
assert_eq!(evaluated(), first);
}
/// With more clip groups with live effects than the boxes kept, a new box replaces only as many
/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions.
#[test]
fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
set_clip_region(moved_clip_region);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let groups = CLIP_BOXES_KEPT + 64;
let mut members = Vec::with_capacity(groups);
for i in 0..groups {
let x = (i % 100) as f64 * 5.0;
let y = (i / 100) as f64 * 5.0;
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default());
mask.appearance.effects.push(test_move());
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art());
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
members.push(Arc::new(clip));
}
if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) {
*children = members;
}
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
let empty = Point::new(900.0, 900.0);
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let first = evaluated();
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
let again = evaluated() - first;
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
}
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
/// whose Preview is off, which is clicked in outline while the layer above clips by its region.
#[test]
fn every_clip_test_follows_the_moved_region() {
set_clip_region(moved_clip_region);
let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0));
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let (g, art_id) = (d.alloc_id(), art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
d.insert(Some(l), 0, outer.clone()).unwrap();
let opt = HitOptions::default();
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place");
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region");
let symbols = d.symbol_boxes();
assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill));
assert_eq!(hit_any(&outer, own, opt, &symbols), None);
d.node_mut(art_id).unwrap().locked = true;
assert_eq!(locked_objects_at(&d, moved, opt), [art_id]);
assert!(locked_objects_at(&d, own, opt).is_empty());
// A clipping layer holding the mask and a sublayer whose Preview is off, with the art.
let mut d = Document::new(300.0, 200.0);
let top = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let art_id = art.id;
let mut sublayer = (*d.layers[0]).clone();
sublayer.id = d.alloc_id();
if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind {
(*children, *preview) = (vec![Arc::new(art)], false);
}
d.insert(Some(top), 0, sublayer).unwrap();
d.insert(Some(top), 0, mask).unwrap();
d.node_mut(top).unwrap().set_clips(true);
// The art's top edge, at the clipping path's own place and in the moved region.
let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5));
assert!(hit_test(&d, own, opt).is_none());
assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id));
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id));
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None);
}
/// The art a mask hides counts only for a selected object: there a click hits nothing, and the
/// selection tools grab the selection by that art. Not where the art shows (the click hits it),
/// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked,
@@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
}
/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect
/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and
/// when Preview is off for the layer in the art or for the layer the instance is on, the plain
/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline.
#[test]
fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
set_clip_region(moved_clip_region);
// The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that
// layer and of the document layer the instance is on.
let instance = |effect: &str, preview: [bool; 2]| {
let mut d = Document::new(300.0, 200.0);
if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
*p = preview[1];
}
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind {
(*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]);
}
layer.set_clips(true);
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
(d, inst)
};
let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| {
let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap();
vectorcraft_geom::kurbo::Shape::bounding_box(&o)
};
let opt = HitOptions::default();
let (d, inst) = instance("test.move", [true, true]);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region");
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was");
let b = outline_box(&d, inst, opt);
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}");
let b = outline_box(&d, inst, HitOptions { outline: true, ..opt });
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}");
// With Preview off, the art's top edge counts within the plain clipping path.
for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] {
let (d, inst) = instance("test.move", preview);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}");
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}");
let b = outline_box(&d, inst, opt);
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}");
}
// An effect that leaves the clipping path no region hides the art: no pick and no outline.
let (d, inst) = instance("test.empty", [true, true]);
let n = d.node(inst).unwrap();
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None);
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
}
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
/// canvas draws nothing of it. At the art's natural size the same art is picked.
@@ -1586,6 +1889,53 @@ fn symbol_art_past_the_object_limit_picks_nothing() {
assert!(symbol_part_outline(&d, n, &[0]).is_some());
}
/// Picking and outlining an object of a 9-slice instance's art, and placing that art, read the
/// symbol list once for each call, however many instances the art holds.
#[test]
fn picking_in_9_slice_art_reads_the_symbol_list_once() {
let mut d = Document::new(400.0, 400.0);
for i in 0..2_000 {
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: format!("Dot {i}"), art: Arc::new(dot) });
}
// A frame, a group of 20 squares in its top left cell, and 20 instances of the dots across
// the guides.
let square = |d: &mut Document, x: f64, y: f64| {
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Appearance::default_art()))
};
let corner: Vec<_> = (0..20).map(|i| square(&mut d, f64::from(i % 5) * 4.0, f64::from(i / 5) * 4.0)).collect();
let dot = |d: &mut Document, i: u32| {
let xf = vectorcraft_geom::Affine::translate((f64::from(i) * 4.5 + 5.0, 48.0)) * vectorcraft_geom::Affine::scale(4.0);
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Dot {i}"), xf }))
};
let across: Vec<_> = (0..20).map(|i| dot(&mut d, i)).collect();
let frame = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()));
let mut kids = vec![frame, Arc::new(Node::group(d.alloc_id(), corner))];
kids.extend(across);
let root = Node::group(d.alloc_id(), kids);
d.symbols.push(crate::Symbol { dynamic: true, name: "Panel".into(), art: Arc::new(root) });
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
let inst = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Panel".into(), xf });
let art = d.symbols[2_000].art.clone();
let symbols = d.symbols.len();
let read = || crate::symbols::SYMBOLS_READ.with(std::cell::Cell::get);
let reads = |f: &dyn Fn()| {
let before = read();
f();
read() - before
};
// Picking also tests the placed art with boxes of its own, as a click outside symbols does.
let n = reads(&|| assert_eq!(symbol_part_at(&d, &inst, Point::new(2.0, 2.0), HitOptions::default()).map(|p| p[0]), Some(1)));
assert!(n <= 2 * symbols, "picking read {n} symbols");
let n = reads(&|| assert!(symbol_part_outline(&d, &inst, &[2]).is_some()));
assert!(n <= symbols, "outlining read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art_unclipped("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing without clips read {n} symbols");
}
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
/// included, so an object in it is picked and outlined there even when placing that object through
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
+100 -13
View File
@@ -94,25 +94,45 @@ pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent)
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
}
/// Visits one colour: the colour, its swatch link and its tint, all of which it may change.
pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) + 'a;
/// Process plates a colour prints together with its spot tint (C, M, Y, K, 0..1): a gradient
/// stop's [`vectorcraft_color::GradientStop::plates`]; `None` for every other colour.
pub type StopPlates = Option<[f32; 4]>;
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
let mut ink = inks(doc, c, color, link, intent);
if let (Some(p), Some(_)) = (plates, &ink.spot) {
ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
}
ink
}
/// Visits one colour: the colour, its swatch link, its tint and its process plates
/// ([`StopPlates`]), all of which it may change.
pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32, &mut StopPlates) + 'a;
fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
match p {
Paint::Solid { color, swatch, tint } => f(color, swatch, tint),
Paint::Solid { color, swatch, tint } => f(color, swatch, tint, &mut None),
Paint::Gradient(g) => {
for s in &mut g.gradient.stops {
f(&mut s.color, &mut s.swatch, &mut s.tint);
f(&mut s.color, &mut s.swatch, &mut s.tint, &mut s.plates);
}
for p in g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()) {
f(&mut p.color, &mut None, &mut 1.0, &mut None);
}
}
_ => {}
}
}
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its
/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it
/// are dropped.
/// Visit every colour of a node tree (fills, strokes, gradient stops, a freeform gradient's
/// points, text runs, mesh points, an image's colorize color, the fills and strokes a dynamic
/// symbol instance keeps for objects of its art, not opacity masks) with its swatch link, tint and
/// process plates. Freeform and mesh points have no link or plates: a link or plates `f` gives
/// them are dropped.
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
for it in &mut n.appearance.items {
match it {
@@ -137,7 +157,7 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
}
NodeKind::Mesh(m) => {
for p in &mut m.points {
f(&mut p.color, &mut None, &mut 1.0);
f(&mut p.color, &mut None, &mut 1.0, &mut None);
}
}
_ => {}
@@ -149,11 +169,16 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
}
}
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh
/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint,
/// keeping the links.
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, a freeform
/// gradient's points, text runs, mesh points, a dynamic symbol instance's own fills and strokes)
/// given its swatch link and tint, keeping the links and process plates.
pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) {
visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint))));
map_node_inks(n, &mut |c, link, _| f(c, link));
}
/// [`map_node_colors`], with each colour's process plates ([`StopPlates`]) passed to `f` too.
pub fn map_node_inks(n: &mut Node, f: &mut dyn FnMut(&Color, Link, StopPlates) -> Color) {
visit_node_colors(n, &mut |c, swatch, tint, plates| *c = f(c, swatch.as_deref().map(|s| (s, *tint)), *plates));
}
/// Apply `f` to every colour in the document's art and symbol definitions.
@@ -170,8 +195,70 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
mod tests {
use super::*;
use crate::{NodeId, SymbolOverride};
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
use vectorcraft_geom::Affine;
/// A document with spot swatch `Gold` and process swatch `Teal`.
fn gold_doc() -> Document {
let mut d = Document::new(100.0, 100.0);
d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
d.swatches.push(Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.8, 0.0, 0.3, 0.0)), global: true, spot: false });
d
}
#[test]
fn a_spot_stops_process_plates_print_with_its_tint() {
let d = gold_doc();
let c = vectorcraft_color::cms::active();
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
let ink = |link: Link, plates: StopPlates| stop_inks(&d, &c, &look, link, plates, Intent::RelativeColorimetric);
let mixed = ink(Some(("Gold", 0.5)), Some([0.25, 0.0, 0.4, 0.0]));
assert_eq!(mixed, Inks { cmyk: [0.25, 0.0, 0.4, 0.0], spot: Some(("Gold".into(), 0.5)), registration: false });
assert_eq!((mixed.on_plate("Cyan"), mixed.on_plate("Gold")), (0.25, 0.5));
// Amounts outside 0..1 are clamped; one that is not a number prints no ink.
let odd = ink(Some(("Gold", 1.0)), Some([f32::NAN, 2.0, -1.0, f32::INFINITY]));
assert_eq!(odd.cmyk, [0.0, 1.0, 0.0, 0.0]);
// Without plates the spot ink prints alone, as `inks` separates it.
assert_eq!(ink(Some(("Gold", 0.5)), None), inks(&d, &c, &look, Some(("Gold", 0.5)), Intent::RelativeColorimetric));
// Plates beside no spot ink print nothing of their own: a process swatch, an unknown
// swatch, no link and Registration separate as `inks` does.
for link in [Some(("Teal", 1.0)), Some(("Missing", 1.0)), None, Some((REGISTRATION, 0.5))] {
assert_eq!(ink(link, Some([0.25, 0.0, 0.4, 0.0])), inks(&d, &c, &look, link, Intent::RelativeColorimetric), "{link:?}");
}
}
#[test]
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
(stop.swatch, stop.tint, stop.plates) = (Some("Gold".into()), 0.5, Some([0.25, 0.0, 0.4, 0.0]));
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, Color::rgb(1.0, 1.0, 1.0))]));
let point = FreeformPoint::new(kurbo::Point::new(10.0, 10.0), Color::rgb(0.0, 1.0, 0.0));
g.freeform = Some(Freeform { points: vec![point], ..Default::default() });
let mut n = Node::path(
NodeId(1),
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)),
crate::Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0),
);
let mut seen = vec![];
let gray = Color::Gray { k: 0.5 };
map_node_inks(&mut n, &mut |c, link, plates| {
seen.push((*c, link.map(|(s, t)| (s.to_string(), t)), plates));
gray
});
assert_eq!(
seen,
vec![
(Color::cmyk(0.25, 0.1, 0.8, 0.05), Some(("Gold".to_string(), 0.5)), Some([0.25, 0.0, 0.4, 0.0])),
(Color::rgb(1.0, 1.0, 1.0), None, None),
(Color::rgb(0.0, 1.0, 0.0), None, None),
]
);
let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| f.paint.clone()) else { panic!("no gradient fill") };
assert_eq!(g.gradient.stops[0].plates, Some([0.25, 0.0, 0.4, 0.0]), "mapping a colour keeps its plates");
assert!(g.gradient.stops.iter().all(|s| s.color == gray));
assert_eq!(g.freeform.map(|f| f.points[0].color), Some(gray), "the freeform point is mapped too");
}
#[test]
fn a_dynamic_instances_own_fills_and_strokes_are_visited() {
let red = Color::rgb(1.0, 0.0, 0.0);
+575 -46
View File
@@ -2,16 +2,26 @@
//! from the document's symbols, which the text layout needs to size and place it.
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock, Weak};
use vectorcraft_geom::{Affine, Rect};
use crate::{Document, NodeId, NodeKind, TextObject};
use crate::symbols::SymbolNames;
use crate::{Document, Node, NodeId, NodeKind, Symbol, SymbolBoxes, TextObject};
/// The document key under which the app records each symbol's natural size (`{name: [w, h]}`).
pub const SYMBOL_SIZES: &str = "symbolSizes";
/// Half the side of the square symbol art is normalised to.
pub const SYMBOL_HALF: f64 = 10.0;
/// The box symbol art `art` is measured by in [`Document::symbol_art_bounds`]: its visual bounds,
/// or its geometric bounds when it has no visual bounds.
fn art_extent(art: &Node, boxes: &SymbolBoxes) -> Option<Rect> {
art.visual_bounds_with(boxes).or_else(|| art.geometric_bounds_with(boxes))
}
/// Usable art bounds: finite, non-degenerate.
fn usable(r: Option<Rect>) -> Option<Rect> {
r.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) && r.width() >= 0.0 && r.height() > 1e-9)
@@ -32,16 +42,45 @@ impl Document {
}
/// Visual bounds of the art of the symbol named `name` at its natural size (see
/// [`Self::symbol_natural_xf`]), if it exists and has a usable extent.
/// [`Self::symbol_natural_xf`]), if it exists and has a usable extent. The symbol instances in
/// the art are measured by their own symbols' art ([`Node::visual_bounds_with`]), or by the
/// 20 × 20 square where [`crate::SymbolBoxes`] measures them by it.
pub fn symbol_art_bounds(&self, name: &str) -> Option<Rect> {
let s = self.symbols.iter().find(|s| s.name == name)?;
let b = usable(s.art.visual_bounds().or_else(|| s.art.geometric_bounds()))?;
self.symbol_art_bounds_in(name, &self.symbol_boxes())
}
/// [`Self::symbol_art_bounds`], with the symbols found and the instances measured by `boxes`
/// (new boxes of this document).
fn symbol_art_bounds_in(&self, name: &str, boxes: &SymbolBoxes) -> Option<Rect> {
let b = usable(art_extent(boxes.symbol_art(name)?, boxes))?;
usable(Some(self.symbol_natural_xf(name).transform_rect_bbox(b)))
}
/// The art bounds an inline graphic of the symbol named `name` takes: [`Self::symbol_art_bounds`],
/// or `None` (an empty slot) when the symbol's art shows the symbol itself inline, directly or
/// through the inline graphics and symbol instances in other symbols' art, so that its size
/// would depend on itself.
pub fn inline_art_bounds(&self, name: &str) -> Option<Rect> {
let (cyclic, names) = self.inline_cycles();
if cyclic.contains(name) { None } else { self.symbol_art_bounds_in(name, &self.symbol_boxes().with_names(&names)) }
}
/// The names of the symbols that reach themselves through the inline graphics in symbol art
/// ([`InlineGraph`]), with each symbol name → the index of the first symbol of that name, found
/// once while the symbols stay as they are.
fn inline_cycles(&self) -> (Arc<HashSet<String>>, Arc<SymbolNames>) {
if let Some(found) = self.inline_cycles.get(&self.symbols) {
return found;
}
let graph = InlineGraph::of(self);
let found = (Arc::new(graph.cyclic), graph.names);
self.inline_cycles.set(&self.symbols, &found);
found
}
/// Does `t` have inline graphics whose resolved bounds differ from the document's symbols?
fn inline_stale(&self, t: &TextObject) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != self.symbol_art_bounds(&a.symbol))
stale_by(t, &|n| self.inline_art_bounds(n))
}
/// `t` with its inline graphics' art bounds resolved from this document's symbols (borrowed
@@ -56,54 +95,544 @@ impl Document {
Cow::Owned(t)
}
/// Fill in the art bounds of `t`'s inline graphics; returns whether any changed (the text's
/// cached layout bounds are then cleared).
/// Fill in the art bounds of `t`'s inline graphics ([`Self::inline_art_bounds`]); returns
/// whether any changed (the text's cached layout is then cleared).
pub fn resolve_text_inline(&self, t: &mut TextObject) -> bool {
let mut changed = false;
for r in &mut t.runs {
if let Some(a) = &mut r.inline {
let b = self.symbol_art_bounds(&a.symbol);
if a.bounds != b {
a.bounds = b;
changed = true;
}
}
}
if changed {
t.cached_bounds = None;
t.cached_ink = None;
}
changed
resolve_runs(t, &|n| self.inline_art_bounds(n))
}
/// Resolve the inline graphics of every text object in the layers (after opening a document
/// or changing its symbols). Returns the ids of the texts that changed: their cached layout
/// bounds were cleared and need recomputing.
/// Resolve the inline graphics of every text object in the document (after opening a document
/// or changing its symbols), without laying the type out again: see
/// [`Self::resolve_inline_art_with`].
pub fn resolve_inline_art(&mut self) -> Vec<NodeId> {
let mut stale = vec![];
self.walk(|n| {
if let NodeKind::Text(t) = &n.kind
&& t.runs.iter().any(|r| r.inline.is_some())
&& self.inline_stale(t)
{
stale.push(n.id);
}
});
self.resolve_inline_art_with(&mut |_| {})
}
/// Resolve the inline graphics of every text object in the document: in the layers, the art
/// of symbols, graph designs and pattern tiles, and the opacity masks and live objects in
/// them. Each text whose inline graphics changed has its cached layout cleared and is passed
/// to `layout` to be laid out again. The symbols are resolved first, each after the symbols its
/// inline graphics and symbol instances show, so a symbol's art is measured with its type, and
/// the type in the art of the symbols its instances show, already laid out; a
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
let mut out = vec![];
for id in stale {
let Some(mut t) = self.node(id).and_then(|n| match &n.kind {
NodeKind::Text(t) => Some(t.clone()),
_ => None,
}) else {
continue;
};
if self.resolve_text_inline(&mut t)
&& let Some(n) = self.node_mut(id)
{
n.kind = NodeKind::Text(t);
out.push(id);
let mut unused = vec![];
let graph = InlineGraph::of(self);
let measured = Measured::default();
for &i in &graph.order {
let mut art = self.symbols[i].art.clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.symbols[i].art = art;
}
}
for i in 0..self.layers.len() {
let mut layer = self.layers[i].clone();
if resolve_tree(&mut layer, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut out) {
self.layers[i] = layer;
}
}
for i in 0..self.graph_designs.len() {
let mut art = self.graph_designs[i].art.clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.graph_designs[i].art = art;
}
}
for i in 0..self.patterns.len() {
for j in 0..self.patterns[i].art.len() {
let mut art = self.patterns[i].art[j].clone();
if resolve_tree(&mut art, &|n| measured.get(n, || graph.bounds(self, n)), layout, &mut unused) {
self.patterns[i].art[j] = art;
}
}
}
out
}
}
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
}
/// Gives `t`'s inline graphics the bounds `bounds` gives their symbols; returns whether any changed
/// (the text's cached layout is then cleared).
fn resolve_runs(t: &mut TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
let mut changed = false;
for a in t.runs.iter_mut().filter_map(|r| r.inline.as_mut()) {
let b = bounds(&a.symbol);
if a.bounds != b {
a.bounds = b;
changed = true;
}
}
if changed {
t.cached_bounds = None;
t.cached_baselines.clear();
t.cached_ink = None;
}
changed
}
/// Resolves the inline graphics of the type in tree `n` (opacity mask art included) with
/// `bounds`, passing each text that changed to `layout` and adding its id to `changed`; returns
/// whether the tree changed. Each node is visited once, and only the nodes on the way to changed
/// type are copied.
fn resolve_tree(
n: &mut Arc<Node>,
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
let mut copied = false;
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
let node = Arc::make_mut(n);
if let NodeKind::Text(t) = &mut node.kind
&& resolve_runs(t, bounds)
{
layout(t);
changed.push(node.id);
}
copied = true;
}
let mask = n.extras().mask.as_deref().and_then(|m| {
let mut art = m.art.clone();
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
});
let mut kids = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut c = c.clone();
if resolve_tree(&mut c, bounds, layout, changed) {
kids.push((i, c));
}
}
if mask.is_none() && kids.is_empty() {
return copied;
}
let node = Arc::make_mut(n);
if let Some(art) = mask
&& let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_deref_mut())
{
m.art = art;
}
if let Some(ch) = node.children_mut() {
for (i, c) in kids {
ch[i] = c;
}
}
true
}
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
/// A symbol is first asked for after its own type is resolved (the pass goes in
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
#[derive(Default)]
struct Measured(RefCell<HashMap<String, Option<Rect>>>);
impl Measured {
/// The bounds kept for `name`, or `measure`'s, kept for later.
fn get(&self, name: &str, measure: impl FnOnce() -> Option<Rect>) -> Option<Rect> {
if let Some(&b) = self.0.borrow().get(name) {
return b;
}
let b = measure();
self.0.borrow_mut().insert(name.to_owned(), b);
b
}
}
/// The names of the symbols the inline graphics in tree `n` show (opacity mask art included).
fn inline_symbols(n: &Node) -> Vec<String> {
fn collect(n: &Node, out: &mut Vec<String>) {
if let NodeKind::Text(t) = &n.kind {
out.extend(t.runs.iter().filter_map(|r| r.inline.as_ref().map(|a| a.symbol.clone())));
}
if let Some(m) = n.extras().mask.as_deref() {
collect(&m.art, out);
}
for c in n.children().into_iter().flatten() {
collect(c, out);
}
}
let mut out = vec![];
collect(n, &mut out);
out
}
/// The symbols of a document as their sizes depend on each other: a symbol's art depends on the
/// symbols its type shows inline, and on the symbols its instances show when those instances are
/// measured by their symbols' art ([`crate::SymbolBoxes`]).
struct InlineGraph {
/// Every symbol index, each after the symbols its art depends on (except along a cycle).
order: Vec<usize>,
/// The names of the symbols that reach themselves through inline graphics. Instances alone make
/// no cycle: an instance of a symbol that holds an instance of itself is measured by the
/// 20 × 20 square, so every cycle passes through an inline graphic.
cyclic: HashSet<String>,
/// Each symbol name → the index of the first symbol of that name, which stay the same while
/// [`Document::resolve_inline_art_with`] changes the symbols' art.
names: Arc<SymbolNames>,
}
impl InlineGraph {
/// The graph of `d`'s symbols: each symbol's art is walked once, and, when the art of any
/// symbol holds an inline graphic, measured once with the art boxes of the symbols its
/// instances show measured once in all ([`SymbolBoxes::consulted`]: an instance that does not
/// size the art, such as one a clipping path hides, adds nothing). The order and cycles are
/// found in time linear in the symbols and their inline references and instances (Tarjan's
/// strongly connected components, without recursion).
fn of(d: &Document) -> Self {
let names = Arc::new(d.symbol_names());
let boxes = d.symbol_boxes().quick().with_names(&names);
let inline: Vec<Vec<String>> = d.symbols.iter().map(|s| inline_symbols(&s.art)).collect();
// Without inline graphics in symbol art, no symbol's type depends on another symbol.
let any_inline = inline.iter().any(|v| !v.is_empty());
let edges: Vec<Vec<usize>> = d
.symbols
.iter()
.zip(inline)
.map(|(s, inline)| {
let measured = if any_inline {
boxes.consulted(|| {
art_extent(&s.art, &boxes);
})
} else {
HashSet::new()
};
let shows = inline.into_iter().chain(measured);
let mut e: Vec<usize> = shows.filter_map(|n| names.get(n.as_str()).copied()).collect();
e.sort_unstable();
e.dedup();
e
})
.collect();
let (order, cyclic) = components(&edges);
let cyclic = order.iter().filter(|&&i| cyclic[i]).map(|&i| d.symbols[i].name.clone()).collect();
Self { order, cyclic, names }
}
/// [`Document::inline_art_bounds`] with the cycles found in this graph, for `d` with the
/// symbols' names and order the graph was made with.
fn bounds(&self, d: &Document, name: &str) -> Option<Rect> {
if self.cyclic.contains(name) { None } else { d.symbol_art_bounds_in(name, &d.symbol_boxes().with_names(&self.names)) }
}
}
/// The nodes of the graph `edges` (node → the nodes it depends on), each after the nodes it
/// depends on except within a cycle, and whether each node is on a cycle (a component of more than
/// one node, or an edge to itself).
fn components(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<bool>) {
const UNSEEN: usize = usize::MAX;
let n = edges.len();
let (mut index, mut low, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![false; n]);
let (mut stack, mut order, mut cyclic) = (vec![], Vec::with_capacity(n), vec![false; n]);
let mut next = 0;
// The nodes being visited, each with the position of its next edge.
let mut calls: Vec<(usize, usize)> = vec![];
for root in 0..n {
if index[root] != UNSEEN {
continue;
}
index[root] = next;
low[root] = next;
next += 1;
stack.push(root);
on_stack[root] = true;
calls.push((root, 0));
while let Some(top) = calls.last_mut() {
let v = top.0;
if let Some(&w) = edges[v].get(top.1) {
top.1 += 1;
if index[w] == UNSEEN {
index[w] = next;
low[w] = next;
next += 1;
stack.push(w);
on_stack[w] = true;
calls.push((w, 0));
} else if on_stack[w] {
low[v] = low[v].min(index[w]);
}
continue;
}
calls.pop();
if let Some(&(u, _)) = calls.last() {
low[u] = low[u].min(low[v]);
}
if low[v] == index[v] {
let start = order.len();
while let Some(w) = stack.pop() {
on_stack[w] = false;
order.push(w);
if w == v {
break;
}
}
if order.len() - start > 1 || edges[v].contains(&v) {
for &w in &order[start..] {
cyclic[w] = true;
}
}
}
}
}
(order, cyclic)
}
/// The symbols [`Document::inline_cycles`] last found, with the name of each symbol and a weak
/// pointer to its art. While a weak pointer to an art's allocation is held, nothing else can be at
/// that address, and the art can't be changed in place (`Arc::get_mut` refuses it and
/// `Arc::make_mut` moves it), so any edit inside a symbol's art, and any symbol added, removed,
/// renamed or replaced, gives symbols the cache does not match. Clones of a document share it.
#[derive(Default)]
pub(crate) struct InlineCycles(RwLock<Option<Arc<Found>>>);
/// The names of the symbols on a cycle, and each symbol name → the index of the first symbol of that
/// name.
type Cycles = (Arc<HashSet<String>>, Arc<SymbolNames>);
/// The name and art of each symbol the cycles were found in, and what was found.
type Found = (Vec<(String, Weak<Node>)>, Cycles);
impl InlineCycles {
/// The cached names, when they were found in `symbols`.
fn get(&self, symbols: &[Symbol]) -> Option<Cycles> {
let g = self.0.read().ok()?;
let (from, found) = &**g.as_ref()?;
let same = from.len() == symbols.len()
&& from.iter().zip(symbols).all(|((name, art), s)| *name == s.name && std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)));
same.then(|| found.clone())
}
/// Keep `found`, found in `symbols`.
fn set(&self, symbols: &[Symbol], found: &Cycles) {
if let Ok(mut g) = self.0.write() {
*g = Some(Arc::new((symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), found.clone())));
}
}
}
impl Clone for InlineCycles {
fn clone(&self) -> Self {
InlineCycles(RwLock::new(self.0.read().ok().and_then(|g| g.clone())))
}
}
/// A cache, not document content: two documents are equal whatever their caches hold.
impl PartialEq for InlineCycles {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl std::fmt::Debug for InlineCycles {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("InlineCycles")
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The position of each node in `order`.
fn positions(order: &[usize]) -> Vec<usize> {
let mut at = vec![0; order.len()];
for (p, &i) in order.iter().enumerate() {
at[i] = p;
}
at
}
#[test]
fn components_put_dependencies_first_and_find_every_cycle_member() {
// 0 → 1 → 2 → 0 is a cycle, and 3, reached from 1, joins it through 2.
// 4 depends on 0 and is on no cycle; 5 shows itself.
let edges = vec![vec![1], vec![2, 3], vec![0], vec![2], vec![0], vec![5]];
let (order, cyclic) = components(&edges);
let mut sorted = order.clone();
sorted.sort_unstable();
assert_eq!(sorted, [0, 1, 2, 3, 4, 5]);
assert_eq!(cyclic, [true, true, true, true, false, true]);
let at = positions(&order);
assert!(at[4] > at[0], "{order:?}");
// A chain: each node after the one it depends on.
let (order, cyclic) = components(&[vec![], vec![0], vec![1]]);
assert_eq!(order, [0, 1, 2]);
assert!(cyclic.iter().all(|c| !c));
}
/// Type at the bottom of 2,000 nested groups is checked once, not once for each group above it,
/// and only the groups on the way to it are copied.
#[test]
fn resolving_deeply_nested_type_visits_each_node_once() {
use std::cell::Cell;
use vectorcraft_geom::Point;
let mut t = TextObject::point(Point::ZERO, "Type", crate::CharStyle::default());
t.runs.push(crate::TextRun::new("", crate::CharStyle::default()));
t.runs[1].inline = Some(crate::InlineArt { symbol: "S".into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
let depth = 2_000;
let mut tree = Arc::new(Node::new(NodeId(0), NodeKind::Text(Box::new(t))));
for i in 1..=depth {
let side = Arc::new(Node::group(NodeId(depth + i), vec![]));
tree = Arc::new(Node::group(NodeId(i), vec![side, tree]));
}
let before = tree.clone();
let asked = Cell::new(0);
let r = Rect::new(0.0, 0.0, 10.0, 20.0);
let bounds = |_: &str| {
asked.set(asked.get() + 1);
Some(r)
};
let (mut laid_out, mut changed) = (0, vec![]);
assert!(resolve_tree(&mut tree, &bounds, &mut |_| laid_out += 1, &mut changed));
assert!(asked.get() <= 2, "bounds asked {} times for one inline graphic", asked.get());
assert_eq!(laid_out, 1);
assert_eq!(changed, [NodeId(0)]);
// The bottom of the new tree holds the resolved type; the side groups are shared.
let (mut new, mut old) = (&tree, &before);
while let (Some(n), Some(o)) = (new.children(), old.children()) {
assert!(Arc::ptr_eq(&n[0], &o[0]));
(new, old) = (&n[1], &o[1]);
}
let NodeKind::Text(t) = &new.kind else { panic!("the type is at the bottom") };
assert_eq!(t.runs[1].inline.as_ref().and_then(|a| a.bounds), Some(r));
// Nothing left to change: the tree is kept and the type is checked once.
asked.set(0);
let kept = tree.clone();
assert!(!resolve_tree(&mut tree, &bounds, &mut |_| laid_out += 1, &mut changed));
assert!(Arc::ptr_eq(&tree, &kept));
assert_eq!(asked.get(), 1);
}
#[test]
fn a_symbol_is_measured_once_in_a_pass() {
let measured = Measured::default();
let count = std::cell::Cell::new(0);
let measure = |b: Option<Rect>| {
count.set(count.get() + 1);
b
};
let r = Some(Rect::new(0.0, 0.0, 1.0, 1.0));
for _ in 0..3 {
assert_eq!(measured.get("A", || measure(r)), r);
assert_eq!(measured.get("Missing", || measure(None)), None);
}
assert_eq!(count.get(), 2);
}
/// A rectangle `r` filled black, with a 2 pt black stroke.
fn stroked(d: &mut Document, r: Rect) -> Arc<Node> {
use vectorcraft_color::{Color, Paint};
let look = crate::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
}
fn instance(d: &mut Document, symbol: &str, xf: Affine) -> Arc<Node> {
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf }))
}
/// Symbol `name` holding `art` in a group.
fn symbol(d: &mut Document, name: &str, art: Vec<Arc<Node>>) {
let group = Node::group(d.alloc_id(), art);
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) });
}
#[test]
fn a_symbol_nested_in_symbol_art_is_measured_by_its_own_art() {
// `Far` is a rectangle from (200, 100) to (240, 130) with a 2 pt stroke, far from the
// 20 × 20 square around the origin.
let mut d = Document::new(500.0, 500.0);
let far = stroked(&mut d, Rect::new(200.0, 100.0, 240.0, 130.0));
symbol(&mut d, "Far", vec![far]);
let moved = instance(&mut d, "Far", Affine::translate((-100.0, 0.0)));
symbol(&mut d, "Moved", vec![moved.clone()]);
let scaled = instance(&mut d, "Far", Affine::scale(2.0));
symbol(&mut d, "Scaled", vec![scaled]);
symbol(&mut d, "Sized", vec![moved]);
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "Sized": [40.0, 20.0] }));
assert_eq!(d.symbol_art_bounds("Far"), Some(Rect::new(199.0, 99.0, 241.0, 131.0)));
// The stroke paints 1 pt around the moved rectangle.
assert_eq!(d.symbol_art_bounds("Moved"), Some(Rect::new(99.0, 99.0, 141.0, 131.0)));
// Scaled 2 times, the stroke keeps its weight.
assert_eq!(d.symbol_art_bounds("Scaled"), Some(Rect::new(399.0, 199.0, 481.0, 261.0)));
// At its natural size, 40 × 20 for the 20 × 20 square: 2 times across.
assert_eq!(d.symbol_art_bounds("Sized"), Some(Rect::new(198.0, 99.0, 282.0, 131.0)));
assert_eq!(d.inline_art_bounds("Moved"), d.symbol_art_bounds("Moved"));
}
#[test]
fn nested_instances_without_art_of_their_own_are_measured_by_the_square() {
let mut d = Document::new(500.0, 500.0);
let r = Rect::new(0.0, 0.0, 10.0, 10.0);
// An instance of a missing symbol and one of a symbol with no art, beside a rectangle.
symbol(&mut d, "Empty", vec![]);
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Nowhere", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Missing", pieces);
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Empty", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Holds empty", pieces);
let with_square = Some(Rect::new(-1.0, -10.0, 110.0, 11.0));
assert_eq!(d.symbol_art_bounds("Empty"), None);
assert_eq!(d.symbol_art_bounds("Missing"), with_square);
assert_eq!(d.symbol_art_bounds("Holds empty"), with_square);
// A symbol that holds an instance of itself: the instance is measured by the square, and
// an inline graphic of it is not an empty slot.
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Loop", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Loop", pieces);
assert_eq!(d.symbol_art_bounds("Loop"), with_square);
assert_eq!(d.inline_art_bounds("Loop"), with_square);
// A chain of 40 symbols, each holding a rectangle and an instance of the next one 1 pt to
// the right: symbols nest 39 deep in Link 0's art, past the limit of 32, so its instance of
// Link 1 is measured by the square.
for i in 0..40 {
let unit = stroked(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0));
let next = instance(&mut d, &format!("Link {}", i + 1), Affine::translate((1.0, 0.0)));
symbol(&mut d, &format!("Link {i}"), if i < 39 { vec![unit, next] } else { vec![unit] });
}
assert_eq!(d.symbol_art_bounds("Link 0"), Some(Rect::new(-9.0, -10.0, 11.0, 10.0)));
// Link 8's art nests 31 deep: measured by the art of the links after it.
assert_eq!(d.symbol_art_bounds("Link 8"), Some(Rect::new(-1.0, -1.0, 33.0, 2.0)));
}
/// Type showing the symbol named `symbol` inline.
fn showing(d: &mut Document, symbol: &str) -> Arc<Node> {
let style = crate::CharStyle::default();
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Type", style.clone());
t.runs.push(crate::TextRun::new("", style));
t.runs[1].inline = Some(crate::InlineArt { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
Arc::new(Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))))
}
#[test]
fn only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol() {
// B's type shows A inline. A's art is a clip group: a clipping rectangle, then an instance
// of B that the rectangle clips, so A's size does not depend on B's.
let mut d = Document::new(500.0, 500.0);
let text = showing(&mut d, "A");
symbol(&mut d, "B", vec![text]);
let clip = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
let inner = instance(&mut d, "B", Affine::IDENTITY);
let group = Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children: vec![clip, inner.clone()], clip: true }));
symbol(&mut d, "A", vec![group]);
assert_eq!(d.inline_art_bounds("A"), Some(Rect::new(-1.0, -1.0, 11.0, 11.0)));
// Without the clip, A's size depends on B's and B's on A's: both are empty slots.
let art = Arc::new(Node::group(d.alloc_id(), vec![inner]));
if let Some(a) = d.symbols.iter_mut().find(|s| s.name == "A") {
a.art = art;
}
assert_eq!(d.inline_art_bounds("A"), None);
assert_eq!(d.inline_art_bounds("B"), None);
}
#[test]
fn components_handle_a_long_chain_without_recursion() {
let n = 200_000;
let edges: Vec<Vec<usize>> = (0..n).map(|i| if i + 1 < n { vec![i + 1] } else { vec![] }).collect();
let (order, cyclic) = components(&edges);
assert_eq!(order.first(), Some(&(n - 1)));
assert_eq!(order.last(), Some(&0));
assert!(cyclic.iter().all(|c| !c));
}
}
+20 -4
View File
@@ -33,8 +33,8 @@ pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{
EditedNineSlice, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE, SymbolNineSlice,
charge_symbol_art,
EditedNineSlice, MAX_GUIDE_FRACTION, MAX_SLICE_GROWTH, MIN_CENTER_BAND, NineSliceGuide, NineSliceMap, PAINTED_EFFECTS, SYMBOL_NINE_SLICE,
SymbolNineSlice, charge_symbol_art,
};
pub use symbol_overrides::SymbolOverride;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
@@ -55,12 +55,14 @@ mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod ppi;
pub mod profiles;
pub mod puppet;
pub mod range;
pub mod rastersettings;
mod reach;
pub mod recolor;
pub mod resample;
pub mod selection;
pub mod separated;
pub mod setup;
@@ -92,8 +94,8 @@ pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, PiePosition,
PieSort, SeriesPaint, TickLength, ValueAxisSide,
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
@@ -117,6 +119,8 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
pub use style_libs::StyleLibrary;
pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::GlyphForm;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
@@ -142,6 +146,7 @@ mod graphic_style;
mod guides;
mod limits;
mod records;
mod stored_art;
mod units;
pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, RetiredArtboardId, VIDEO_PIXEL_ASPECT_RANGE, VIDEO_SAFE_INSETS};
@@ -154,6 +159,7 @@ pub use guides::{GridPrefs, Guide, RulerMode};
use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use stored_art::{StoredPlace, StoredRoot};
pub use units::{ColorMode, Unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -360,6 +366,16 @@ pub struct Document {
/// The ruler guides as [`Document::ruler_guides`] lists them: a cache, never saved.
#[serde(skip)]
guide_cache: document_guides::GuideCache,
/// The symbols that show themselves inline ([`Document::inline_art_bounds`]): a cache, never
/// saved.
#[serde(skip)]
inline_cycles: inline::InlineCycles,
/// Art kept elsewhere in the document's data (the art of the stored brushes, which
/// `vectorcraft-brush` reads from [`Self::unknown`]) while it is set here, each root with the
/// `owner` the Links panel names for it, so the stored-art lookups ([`StoredRoot::Mounted`])
/// find its objects too. Empty otherwise; never saved.
#[serde(skip)]
pub mounted_art: Vec<(Arc<Node>, serde_json::Value)>,
}
fn ppi72() -> f64 {
+26 -6
View File
@@ -229,7 +229,8 @@ fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
/// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG.
fn proxy_of(img: &image::DynamicImage) -> Option<Vec<u8>> {
let small = img.thumbnail(PROXY_SIZE, PROXY_SIZE);
let (w, h) = crate::resample::fit_size(img.width(), img.height(), PROXY_SIZE, PROXY_SIZE);
let small = crate::resample::averaged(img, w, h);
let mut png = Vec::new();
small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
@@ -248,14 +249,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
impl Document {
/// Visit every image object: in the layers, then in symbol definitions and pattern swatches,
/// opacity-mask art included.
/// then in [`Document::mounted_art`], opacity-mask art included.
pub fn visit_images<'a>(&'a self, mut f: impl FnMut(&'a Node, &'a ImageObject)) {
let roots = self
.layers
.iter()
.chain(self.symbols.iter().map(|s| &s.art))
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| &p.art));
.chain(self.patterns.iter().flat_map(|p| &p.art))
.chain(self.mounted_art.iter().map(|(n, _)| n));
for root in roots {
walk_all(root, &mut |n| {
if let NodeKind::Image(im) = &n.kind {
@@ -384,7 +386,8 @@ impl Align {
impl Document {
/// Rewrite linked file locations in both raster images and placed VectorCraft documents,
/// including those inside symbols, patterns and opacity masks. Used to make packages portable.
/// including those inside symbols, patterns, opacity masks and [`Document::mounted_art`]. Used to
/// make packages portable.
pub fn update_links(&mut self, mut f: impl FnMut(&mut LinkInfo)) {
fn walk(n: &mut Arc<Node>, f: &mut dyn FnMut(&mut LinkInfo)) {
let n = Arc::make_mut(n);
@@ -409,7 +412,8 @@ impl Document {
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n));
for root in roots {
walk(root, &mut f);
}
@@ -471,7 +475,8 @@ impl Document {
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n));
for root in roots {
update(root, &pick, &mut f);
}
@@ -728,4 +733,19 @@ mod tests {
image(&mut d, "c", None);
assert_eq!(d.linked_only_images().into_iter().collect::<Vec<_>>(), ["a"]);
}
/// The preview of an image with clear pixels keeps the color of its opaque ones: the clear
/// black beside them does not darken them, whichever way the preview is made.
#[test]
fn a_preview_keeps_the_color_beside_clear_pixels() {
let mut full = vec![];
image::RgbaImage::from_fn(1024, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })
.write_to(&mut Cursor::new(&mut full), image::ImageFormat::Png)
.unwrap();
for blob in [ImageBlob::png(full.clone()).with_proxy(), ImageBlob::png(full.clone()).checked_with_proxy(true).unwrap()] {
let p = image::load_from_memory(blob.proxy.as_ref().unwrap()).unwrap().into_rgba8();
assert_eq!(p.dimensions(), (PROXY_SIZE, 1));
assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0));
}
}
}
+217 -17
View File
@@ -39,7 +39,7 @@ fn fifty() -> f64 {
// =====================================================================================
pub use crate::blend::{
Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
steps_knockout_shows,
};
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
use blend_spec::{blend_color_shift, blend_ramp};
pub use envelope::{
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
envelope_content_boxes, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin,
set_type_ink, smooth_handles,
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
};
pub(crate) use expand::max_outset;
pub use expand::{
@@ -568,23 +568,167 @@ mod tests {
}
}
/// The outline of a 200 × 100 box whose top side is `pieces`, end to end from (0, 0) to
/// (200, 0), and whose other sides are straight.
fn top_of_pieces(pieces: &[CubicBez]) -> PathData {
let pt = |p: Point| (p.x, p.y);
let mut knots: Vec<Knot> = vec![];
for (k, c) in pieces.iter().enumerate() {
let h_in = if k == 0 { pt(c.p0) } else { pt(pieces[k - 1].p2) };
knots.push((pt(c.p0), h_in, pt(c.p1)));
}
let last = pieces.last().unwrap();
knots.push(((200.0, 0.0), pt(last.p2), (200.0, 0.0)));
knots.extend([((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))]);
outline(&knots)
}
/// A top curve whose parameter runs fast at its start and slow at its end.
const UNEVEN_TOP: CubicBez =
CubicBez { p0: Point::new(0.0, 0.0), p1: Point::new(120.0, -60.0), p2: Point::new(190.0, -30.0), p3: Point::new(200.0, 0.0) };
#[test]
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
// new anchor lands at the first piece's share, not at u = 0.3.
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
let path = outline(&[
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
(a.p3.into(), a.p2.into(), b.p1.into()),
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
]);
let c = Coons::from_top_object(&path, None).unwrap();
fn a_split_curve_keeps_the_top_object_patch() {
// Splitting the top curve at t = 0.3, or into thirds, keeps its shape, and the patch stays
// the unsplit curve's: the new anchors land at u = 0.3, 1/3 and 2/3 (to within how finely
// the side is sampled), where the pieces' control polygons would have put them several
// points away.
let whole = Coons::from_top_object(&top_of_pieces(&[UNEVEN_TOP]), None).unwrap();
for cuts in [vec![0.3], vec![1.0 / 3.0, 2.0 / 3.0]] {
let ends: Vec<f64> = std::iter::once(0.0).chain(cuts.iter().copied()).chain([1.0]).collect();
let pieces: Vec<CubicBez> = ends.windows(2).map(|w| UNEVEN_TOP.subsegment(w[0]..w[1])).collect();
let c = Coons::from_top_object(&top_of_pieces(&pieces), None).unwrap();
let total: f64 = pieces.iter().map(|p| polygon(*p)).sum();
for (k, t) in cuts.iter().enumerate() {
let anchor = pieces[k].p3;
assert!(c.eval(*t, 0.0).distance(anchor) < 0.02, "{cuts:?}: u {t} → {:?}, want {anchor:?}", c.eval(*t, 0.0));
let share: f64 = pieces[..=k].iter().map(|p| polygon(*p)).sum::<f64>() / total;
assert!(c.eval(share, 0.0).distance(anchor) > 2.0, "{cuts:?}: the polygon share {share} lands on the anchor");
}
for (u, v) in [(0.1, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
let (p, q) = (c.eval(u, v), whole.eval(u, v));
assert!(p.distance(q) < 1e-9, "{cuts:?}: ({u}, {v}) → {p:?}, unsplit {q:?}");
}
}
}
#[test]
fn a_split_curve_keeps_the_top_object_patch_when_split_at_a_cusp() {
// The top curve stops at t = 0.25 (a cusp), and an anchor splits it there: both handles at
// the split lie on the anchor, and the patch with the corners given stays the unsplit
// curve's.
let cusp = CubicBez::new((0.0, 0.0), (30.0, -40.0), (-58.0, 24.0), (200.0, 0.0));
let pieces = [cusp.subsegment(0.0..0.25), cusp.subsegment(0.25..1.0)];
assert!(pieces[0].p2.distance(pieces[0].p3) < 1e-9 && pieces[1].p1.distance(pieces[1].p0) < 1e-9);
let whole = Coons::from_top_object(&top_of_pieces(&[cusp]), Some([0, 1, 2, 3])).unwrap();
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
let (p, q) = (c.eval(u, v), whole.eval(u, v));
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
}
}
#[test]
fn a_split_curve_keeps_the_top_object_patch_where_it_barely_moves_and_runs_straight() {
// A straight top curve that barely moves at t = 0.25 and doesn't bend there: split there,
// the handles at the split are a few thousandths of a point long and the pieces don't bend
// at all, and the patch with the corners given stays the unsplit curve's.
let slow = CubicBez::new((0.0, 0.0), (28.578125, 0.0), (-57.109375, 0.0), (200.0, 0.0));
let pieces = [slow.subsegment(0.0..0.25), slow.subsegment(0.25..1.0)];
let (into, out) = (pieces[0].p3.distance(pieces[0].p2), pieces[1].p0.distance(pieces[1].p1));
assert!(into > 0.0 && out > 0.0 && into.max(out) < 0.01, "{into} {out}");
let whole = Coons::from_top_object(&top_of_pieces(&[slow]), Some([0, 1, 2, 3])).unwrap();
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
let (p, q) = (c.eval(u, v), whole.eval(u, v));
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
}
}
#[test]
fn a_top_object_joins_a_split_curve_saved_with_rounded_coordinates() {
// A file saves the pieces of a curve split into thirds, or into tenths, with its
// coordinates rounded to 0.001 pt, on an outline 5, 200 or 5,000 pt wide: the side is
// still that curve, to within 0.02 pt.
let round = |p: Point| Point::new((p.x * 1000.0).round() / 1000.0, (p.y * 1000.0).round() / 1000.0);
for cuts in [3u32, 10] {
let pieces: Vec<CubicBez> =
(0..cuts).map(|k| UNEVEN_TOP.subsegment(f64::from(k) / f64::from(cuts)..f64::from(k + 1) / f64::from(cuts))).collect();
for scale in [0.025, 1.0, 25.0] {
let mut split = top_of_pieces(&pieces);
split.transform(Affine::scale(scale));
for a in split.subpaths.iter_mut().flat_map(|sp| sp.anchors.iter_mut()) {
(a.p, a.h_in, a.h_out) = (round(a.p), round(a.h_in), round(a.h_out));
}
let mut whole = top_of_pieces(&[UNEVEN_TOP]);
whole.transform(Affine::scale(scale));
let (c, whole) = (Coons::from_top_object(&split, None).unwrap(), Coons::from_top_object(&whole, None).unwrap());
for (u, v) in [(1.0 / 6.0, 0.0), (1.0 / 3.0, 0.0), (0.45, 0.0), (0.5, 0.5), (2.0 / 3.0, 0.0), (0.9, 0.3)] {
let (p, q) = (c.eval(u, v), whole.eval(u, v));
assert!(p.distance(q) < 0.02, "{cuts} pieces at {scale}x: ({u}, {v}) → {p:?}, unsplit {q:?}");
}
}
}
}
#[test]
fn a_top_object_keeps_smoothly_joined_curves_apart() {
// The top side's second piece leaves the split anchor in line with the first piece's
// handle, but its far handle is 1 pt off the split curve's: the pieces are two curves, and
// each takes the share of its control polygon.
let (a, b) = (UNEVEN_TOP.subsegment(0.0..0.3), UNEVEN_TOP.subsegment(0.3..1.0));
let b = CubicBez::new(b.p0, b.p1, b.p2 + Vec2::new(0.0, 1.0), b.p3);
let c = Coons::from_top_object(&top_of_pieces(&[a, b]), None).unwrap();
let share = polygon(a) / (polygon(a) + polygon(b));
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
assert!((share - 0.3).abs() > 0.01, "{share}");
assert!((share - 0.3).abs() > 0.02, "{share}");
}
#[test]
fn a_top_object_side_partly_of_one_curve_keeps_the_polygon_shares() {
// The top side is a curve split at t = 0.3, then a straight segment: not all of it is one
// curve, so each piece keeps the share of its control polygon.
let curve = CubicBez::new((0.0, 0.0), (90.0, -45.0), (142.5, -22.5), (150.0, 0.0));
let (a, b) = (curve.subsegment(0.0..0.3), curve.subsegment(0.3..1.0));
let line = CubicBez::new((150.0, 0.0), (150.0 + 50.0 / 3.0, 0.0), (200.0 - 50.0 / 3.0, 0.0), (200.0, 0.0));
let c = Coons::from_top_object(&top_of_pieces(&[a, b, line]), None).unwrap();
let share = polygon(a) / (polygon(a) + polygon(b) + polygon(line));
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
// Joined into their curve, the two pieces would have put the anchor 0.3 of the way along
// their part of the side.
let joined = 0.3 * (polygon(a) + polygon(b)) / (polygon(a) + polygon(b) + polygon(line));
assert!(c.eval(joined, 0.0).distance(a.p3) > 1.0, "{share} vs {joined}");
}
#[test]
fn a_top_object_side_of_many_arcs_stays_on_them() {
// A 120° arc of radius 500 drawn as `n` circular arcs, each close to a piece of one cubic
// while the whole arc is not one: the side stays on the circle, and the content's middle
// stays on the middle anchor, as the arcs' polygon shares put it.
let centre = Point::new(300.0, 600.0);
for n in [64u32, 128, 256] {
let step = 120f64.to_radians() / f64::from(n);
let reach = 500.0 * 4.0 / 3.0 * (step / 4.0).tan();
let on = |a: f64| centre + Vec2::new(a.cos(), a.sin()) * 500.0;
let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()) * reach;
let mut anchors: Vec<Anchor> = (0..=n)
.map(|i| {
let a = (-150f64).to_radians() + step * f64::from(i);
let p = on(a);
let h_in = if i == 0 { p } else { p - tangent(a) };
let h_out = if i == n { p } else { p + tangent(a) };
Anchor { p, h_in, h_out, ..Anchor::corner(p) }
})
.collect();
let (start, end) = (on((-150f64).to_radians()), on((-30f64).to_radians()));
anchors.extend([Anchor::corner(Point::new(end.x, 800.0)), Anchor::corner(Point::new(start.x, 800.0))]);
let path = PathData::single(SubPath::new(anchors, true));
let c = Coons::from_top_object(&path, Some([0, n, n + 1, n + 2])).unwrap();
let off = (0..=4000).map(|k| (c.eval(f64::from(k) / 4000.0, 0.0).distance(centre) - 500.0).abs()).fold(0.0, f64::max);
assert!(off < 0.001, "{n} arcs: the side lies {off} pt off the circle");
let mid = c.eval(0.5, 0.0);
assert!(mid.distance(Point::new(300.0, 100.0)) < 0.001, "{n} arcs: the middle lands at {mid:?}");
}
}
#[test]
@@ -1103,4 +1247,60 @@ mod tests {
assert_eq!(m, before);
}
}
/// The pieces of a mesh-warped image make a knockout group, each knocking out its triangle
/// (clipping path or opacity mask art); the group keeps the image's transparency.
#[test]
fn mesh_warp_image_pieces_knock_out_by_their_triangles() {
let im = crate::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone())));
n.opacity = 0.5;
n.blend = crate::color::BlendMode::Multiply;
let same = |p: Point| p;
for masked in [false, true] {
let g = mesh_warp_image(&n, &im, &same, 2, false, masked);
assert_eq!((g.knockout, g.opacity, g.blend, g.isolate), (crate::Knockout::On, 0.5, crate::color::BlendMode::Multiply, false));
let NodeKind::Group { children, clip: false } = &g.kind else { panic!("a group") };
assert_eq!(children.len(), 8);
for c in children {
assert!(c.extras().warp_piece);
let outline = c.knockout_outline().unwrap_or_else(|| panic!("masked {masked}: an outline"));
let NodeKind::Path { path, .. } = &outline.kind else { panic!("a path") };
assert_eq!(path.anchor_count(), 3);
}
}
// A clip group or masked image that is not a piece knocks out by what it paints.
let mut plain = mesh_warp_image(&n, &im, &same, 1, false, false);
let NodeKind::Group { children, .. } = &mut plain.kind else { panic!("a group") };
let piece = Arc::make_mut(&mut children[0]);
piece.extras_mut().warp_piece = false;
assert!(piece.knockout_outline().is_none());
}
/// More cells than the objects live art may make cut no pieces (the count overflowed).
#[test]
fn mesh_warp_image_past_the_budget_makes_an_empty_group() {
let im = crate::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone())));
for cells in [usize::MAX, 1000] {
let g = mesh_warp_image(&n, &im, &|p| p, cells, false, false);
assert!(matches!(&g.kind, NodeKind::Group { children, .. } if children.is_empty()), "{cells}");
}
}
}
+293 -28
View File
@@ -149,20 +149,31 @@ impl EnvelopeOptions {
/// its glyph outlines (see [`envelope_content_bounds`]). Strokes scale with the frame as
/// [`Node::transform`] scales them.
pub fn envelope_content_boxes(content: &[Arc<Node>], frame: Affine) -> Option<(Rect, Rect)> {
envelope_content_boxes_with(content, frame, false).or_else(|| envelope_content_boxes_with(content, frame, true))
}
/// [`envelope_content_boxes`] with type that draws nothing given its laid-out box when
/// `blank_type_box` is set and no box when it is not. A caller that measures the members of an
/// envelope's contents one at a time passes `true` only when the whole contents have no box with
/// `false`, so each member is measured as the whole contents measure it.
pub fn envelope_content_boxes_with(content: &[Arc<Node>], frame: Affine, blank_type_box: bool) -> Option<(Rect, Rect)> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let (stroked, plain) = content.iter().fold((None, None), |(stroked, plain), c| {
(vectorcraft_geom::union_opt(stroked, content_box(c, true, to_frame)), vectorcraft_geom::union_opt(plain, content_box(c, false, to_frame)))
});
Some((stroked?, plain?))
Some((content_set_box(content, true, to_frame, blank_type_box)?, content_set_box(content, false, to_frame, blank_type_box)?))
}
/// The geometric bounds an envelope around `content` on the page axes maps from: type, alone or
/// in groups and layers, is measured by its glyph outlines, underlines and strikethroughs instead
/// of its laid-out box. Type keeps its laid-out box while nothing is registered with
/// [`set_type_ink`], and when it draws nothing.
/// [`set_type_ink`]. Type that draws nothing adds no box while other content has one; when
/// nothing else has a box, it keeps its laid-out box.
pub fn envelope_content_bounds(content: &[Arc<Node>]) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, Affine::IDENTITY)))
content_set_box(content, false, Affine::IDENTITY, false).or_else(|| content_set_box(content, false, Affine::IDENTITY, true))
}
/// The union of the boxes [`content_box`] gives each of `content`.
fn content_set_box(content: &[Arc<Node>], stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, stroked, to, blank_type_box)))
}
/// The box of type's glyph outlines, underlines and strikethroughs with its text space mapped by
@@ -367,15 +378,16 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
/// or with `stroked` its visual bounds (strokes scaled by `to` as [`Node::transform`] scales them),
/// with type measured by its glyph outlines ([`type_ink`]) instead of its laid-out box, in groups
/// and layers too. Type is laid out as it is on the page, and its outlines are then taken into
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine) -> Option<Rect> {
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
let mut typed = std::collections::HashSet::new();
find_type(n, &mut typed);
content_box_in(n, stroked, to, &typed)
content_box_in(n, stroked, to, &typed, blank_type_box)
}
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>) -> Option<Rect> {
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
// `n` in the axes of `to`.
let moved = || {
if to == Affine::IDENTITY {
@@ -395,10 +407,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
let ink = match n.projection() {
None => type_ink(n, t, to * t.xf, None),
Some(h) => type_ink(n, t, t.xf, Some((h, to))),
}
.flatten();
};
let m = moved();
let Some(ink) = ink else { return own(&m) };
let ink = match ink {
Some(Some(ink)) => ink,
Some(None) if !blank_type_box => return None,
_ => return own(&m),
};
if !stroked {
return Some(ink);
}
@@ -413,7 +428,13 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
// A clipping path that paints strokes over the clip edge, as in `Node::visual_bounds`.
let clip = children.first()?;
content_box_in(clip, stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)), to, typed)
content_box_in(
clip,
stroked && matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)),
to,
typed,
blank_type_box,
)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
let layer = matches!(n.kind, NodeKind::Layer { .. });
@@ -424,9 +445,11 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
own_strokes.appearance = n.appearance.clone();
own_strokes.transform(to, true);
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed)))
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
} else {
members.filter(|c| c.visible || !layer).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed)))
members
.filter(|c| c.visible || !layer)
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box_in(c, false, to, typed, blank_type_box)))
}
}
_ => own(&moved()),
@@ -525,21 +548,106 @@ pub fn envelope_of(doc: &crate::Document, id: NodeId) -> Option<&Node> {
doc.ancestry(id)?.into_iter().rev().find_map(|a| doc.node(a).filter(|n| matches!(n.kind, NodeKind::Envelope { .. })))
}
/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on a 4×4 grid,
/// a mesh envelope's own grid) or its top object's outline, and for a mesh envelope the grid to
/// edit (its points and handles).
/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on its
/// [`warp_grid`], a mesh envelope's own grid) or its top object's outline, and for a warp or mesh
/// envelope the grid to edit (its points and handles; none while its contents are edited).
pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
let NodeKind::Envelope { kind, .. } = &n.kind else { return None };
let NodeKind::Envelope { kind, editing, .. } = &n.kind else { return None };
let points = |grid: GradientMesh| (!*editing).then_some(grid);
match &**kind {
EnvelopeKind::Mesh { rows, cols, points, handles } => {
let grid = envelope_grid(*rows, *cols, points, handles)?;
Some((grid.lines(), Some(grid)))
EnvelopeKind::Mesh { rows, cols, points: at, handles } => {
let grid = envelope_grid(*rows, *cols, at, handles)?;
Some((grid.lines(), points(grid)))
}
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
EnvelopeKind::Warp { .. } => match warp_grid(n) {
Some(grid) => Some((grid.lines(), points(grid))),
None => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
},
EnvelopeKind::TopObject { path, .. } => Some((path.clone(), None)),
}
}
/// The grid sizes [`warp_grid`] tries, in order: patches per row and per column.
const WARP_GRIDS: [u32; 3] = [4, 8, 16];
/// How far a [`warp_grid`] may draw from the warp it replaces, as a share of the diagonal of the
/// warp's bounds.
const WARP_GRID_TOLERANCE: f64 = 1e-3;
/// The grid a warp envelope's points and handles are edited on: its surface sampled on the first
/// of 4×4, 8×8 and 16×16 patches whose curves draw within [`WARP_GRID_TOLERANCE`] of the warp, with
/// handles along it, as a gradient mesh with black points. Editing a point makes the envelope a
/// mesh envelope with this grid. `None` for other nodes, for content with no bounds, and for a warp
/// that no such grid follows closely enough or whose grid isn't finite.
/// Built again only when the envelope's content objects, warp, frame or options change, or what
/// type is measured with ([`set_type_ink`]).
pub fn warp_grid(n: &Node) -> Option<GradientMesh> {
let NodeKind::Envelope { content, kind, frame, options, .. } = &n.kind else { return None };
if !matches!(**kind, EnvelopeKind::Warp { .. }) {
return None;
}
// `None` until a measure is registered, so a grid kept before then is built again after.
let inputs = TYPE_INK.get().map(|(_, inputs)| inputs());
let key: Vec<usize> = content.iter().map(|c| Arc::as_ptr(c) as usize).collect();
let same = |k: &KeptGrid| k.kind == **kind && k.frame == **frame && k.options == *options && k.inputs == inputs;
if let Some(grid) = WARP_GRIDS_KEPT.with_borrow(|kept| kept.get(&key).filter(|k| same(k)).map(|k| k.grid.clone())) {
return grid;
}
let grid = build_warp_grid(n);
WARP_GRIDS_KEPT.with_borrow_mut(|kept| {
if kept.len() >= WARP_GRID_KEPT {
// Entries for content that no longer exists go first, then one entry at a time.
kept.retain(|_, k| k.content.iter().all(|c| c.strong_count() > 0));
if kept.len() >= WARP_GRID_KEPT
&& let Some(any) = kept.keys().next().cloned()
{
kept.remove(&any);
}
}
// The weak pointers keep the content's addresses from being reused while the entry is kept.
let kept_content = content.iter().map(Arc::downgrade).collect();
kept.insert(key, KeptGrid { content: kept_content, kind: (**kind).clone(), frame: **frame, options: *options, inputs, grid: grid.clone() });
});
grid
}
/// A grid [`warp_grid`] built, with what it was built from.
struct KeptGrid {
content: Vec<std::sync::Weak<Node>>,
kind: EnvelopeKind,
frame: Affine,
options: EnvelopeOptions,
inputs: Option<u64>,
grid: Option<GradientMesh>,
}
/// How many grids [`warp_grid`] keeps on one thread.
const WARP_GRID_KEPT: usize = 1024;
std::thread_local! {
/// The grids [`warp_grid`] built on this thread, by the addresses of their envelopes' content.
static WARP_GRIDS_KEPT: std::cell::RefCell<std::collections::HashMap<Vec<usize>, KeptGrid>> = Default::default();
}
/// [`warp_grid`], built from scratch.
fn build_warp_grid(n: &Node) -> Option<GradientMesh> {
let map = EnvelopeMap::of(n)?;
let bounds = map.bounds()?;
let tol = bounds.width().hypot(bounds.height()) * WARP_GRID_TOLERANCE;
if !tol.is_finite() {
return None;
}
WARP_GRIDS.into_iter().find_map(|k| {
let m = map.surface_mesh(k, k, Color::BLACK);
let finite = m.points.iter().all(|q| q.p.is_finite() && q.handles.iter().all(|h| h.is_finite()));
// Each patch is checked at its corners, the middles of its sides and its middle.
let steps = 2 * k as usize;
let at = |i: usize| i as f64 / steps as f64;
let fits = || (0..=steps).all(|j| (0..=steps).all(|i| mesh_at(&m, at(i), at(j)).distance(map.at(at(i), at(j))) <= tol));
(finite && fits()).then_some(m)
})
}
/// The frame an envelope keeps after transform `m` (its frame so far composed with the
/// transform): identity when its axes stay square to the page, unflipped, since evaluating on
/// the page axes gives the same result then.
@@ -564,7 +672,7 @@ impl<'a> EnvelopeMap<'a> {
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine, options: EnvelopeOptions) -> Option<Self> {
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
let to_frame = frame.inverse();
let src = content.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, content_box(c, false, to_frame)))?;
let src = content_set_box(content, false, to_frame, false).or_else(|| content_set_box(content, false, to_frame, true))?;
let src = options.source_box(src);
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
}
@@ -750,14 +858,171 @@ mod tests {
let to = Affine::scale(2.0);
let mut moved = (*group).clone();
moved.transform(to, true);
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to)));
let want = moved.visual_of_members(std::iter::once(content_box(&text, true, to, true)));
assert!(want.is_some());
assert_eq!(content_box(&group, true, to), want);
assert_eq!(content_box(&group, true, to, true), want);
let mut nested = group;
for i in 0..300 {
nested = Arc::new(Node::group(NodeId(10 + i), vec![nested]));
}
assert!(content_box(&nested, false, Affine::IDENTITY).is_some());
assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some());
}
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
/// (100, 50).
fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node {
let rect = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 50.0, 300.0, 150.0));
let content = Arc::new(Node::path(NodeId(1), rect, crate::Appearance::default_art()));
let kind = EnvelopeKind::Warp { style: style.into(), bend, h, v: 0.0, horizontal: true, version };
Node::new(
NodeId(2),
NodeKind::Envelope {
content: vec![content],
kind: Box::new(kind),
fidelity: 50.0,
editing: false,
options: EnvelopeOptions::NEW,
frame: Box::new(Affine::IDENTITY),
},
)
}
const STYLES: [&str; 15] = [
"arc",
"arcLower",
"arcUpper",
"arch",
"bulge",
"shellLower",
"shellUpper",
"flag",
"wave",
"fish",
"rise",
"fisheye",
"inflate",
"squeeze",
"twist",
];
/// Every warp style's Bézier net has a grid to edit: its points lie on the warp, and the grid
/// draws within a thousandth of the warp's diagonal of it, between the grid lines too. The
/// overlay shows that grid's lines and points.
#[test]
fn every_warp_style_has_a_grid_that_keeps_its_shape() {
for style in STYLES {
for (bend, h) in [(50.0, 0.0), (100.0, 0.0), (-100.0, 60.0)] {
let n = warp_node(style, bend, h, crate::live::WARP_NET);
let grid = warp_grid(&n).unwrap_or_else(|| panic!("{style} {bend} {h}: no grid"));
assert!(WARP_GRIDS.contains(&grid.rows) && grid.rows == grid.cols, "{style}: {}×{}", grid.rows, grid.cols);
let map = EnvelopeMap::of(&n).unwrap();
let b = map.bounds().unwrap();
let tol = b.width().hypot(b.height()) * 1e-3;
let k = grid.cols as usize;
for (i, q) in grid.points.iter().enumerate() {
let want = map.at((i % (k + 1)) as f64 / k as f64, (i / (k + 1)) as f64 / k as f64);
assert!(q.p.distance(want) < 1e-9, "{style}: point {i} at {:?}, the warp at {want:?}", q.p);
}
for j in 0..=20 {
for i in 0..=20 {
let (u, v) = (i as f64 / 20.0, j as f64 / 20.0);
let off = mesh_at(&grid, u, v).distance(map.at(u, v));
assert!(off <= tol, "{style} {bend} {h}: {off} off at ({u}, {v})");
}
}
let (lines, shown) = envelope_overlay(&n).unwrap();
assert_eq!(shown.as_ref(), Some(&grid), "{style}");
assert_eq!(lines, grid.lines(), "{style}");
}
}
}
/// A kept warp grid is built again when the content, the warp, the frame or the options change,
/// and is the grid built from scratch otherwise.
#[test]
fn a_kept_warp_grid_follows_changes() {
let n = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
let first = warp_grid(&n);
assert!(first.is_some());
assert_eq!(warp_grid(&n), first);
assert_eq!(build_warp_grid(&n), first);
let changed = |f: &dyn Fn(&mut Node)| {
let mut m = n.clone();
f(&mut m);
let grid = warp_grid(&m);
assert_eq!(grid, build_warp_grid(&m));
assert_ne!(grid, first);
};
changed(&|m| {
if let NodeKind::Envelope { content, .. } = &mut m.kind {
Arc::make_mut(&mut content[0]).transform(Affine::translate((40.0, 0.0)), true);
}
});
changed(&|m| {
if let NodeKind::Envelope { kind, .. } = &mut m.kind
&& let EnvelopeKind::Warp { bend, .. } = &mut **kind
{
*bend = -30.0;
}
});
changed(&|m| {
if let NodeKind::Envelope { frame, .. } = &mut m.kind {
**frame = Affine::rotate(0.3);
}
});
changed(&|m| {
if let NodeKind::Envelope { options, .. } = &mut m.kind {
options.bounds_margin = [0.1; 4];
}
});
}
/// The table of kept warp grids stays bounded: full of envelopes that still exist, it drops one
/// entry at a time instead of emptying, and it drops the entries of envelopes that are gone
/// first.
#[test]
fn the_kept_warp_grids_stay_bounded() {
let nodes: Vec<Node> = (0..WARP_GRID_KEPT + 10).map(|i| warp_node("arc", (i % 100) as f64, 0.0, crate::live::WARP_NET)).collect();
for n in &nodes {
assert!(warp_grid(n).is_some());
}
assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), WARP_GRID_KEPT);
// Once the envelopes are gone, their entries are the ones dropped.
drop(nodes);
assert!(warp_grid(&warp_node("arc", 10.0, 0.0, crate::live::WARP_NET)).is_some());
assert_eq!(WARP_GRIDS_KEPT.with_borrow(|kept| kept.len()), 1);
}
/// A warp drawn by the old point map that no grid of up to 16×16 patches follows closely
/// enough, content without bounds and other envelopes have no warp grid; the overlay still
/// draws the old warp's lines. While an envelope's contents are edited, it shows no points.
#[test]
fn a_warp_no_grid_follows_has_no_grid_to_edit() {
let n = warp_node("fisheye", 100.0, 0.0, 0);
assert!(warp_grid(&n).is_none());
let (lines, grid) = envelope_overlay(&n).unwrap();
assert!(grid.is_none());
assert!(lines.anchor_count() > 0);
// The same style on its Bézier net has one.
assert!(warp_grid(&warp_node("fisheye", 100.0, 0.0, crate::live::WARP_NET)).is_some());
let mut empty = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
if let NodeKind::Envelope { content, .. } = &mut empty.kind {
content.clear();
}
assert!(warp_grid(&empty).is_none());
let mut mesh = warp_node("arc", 50.0, 0.0, crate::live::WARP_NET);
if let NodeKind::Envelope { kind, .. } = &mut mesh.kind {
**kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points: grid_points(Rect::new(0.0, 0.0, 1.0, 1.0), 1, 1), handles: vec![] };
}
assert!(warp_grid(&mesh).is_none());
// While the contents are edited, a warp's and a mesh envelope's lines show without points.
for mut n in [warp_node("arc", 50.0, 0.0, crate::live::WARP_NET), mesh] {
if let NodeKind::Envelope { editing, .. } = &mut n.kind {
*editing = true;
}
let (lines, grid) = envelope_overlay(&n).unwrap();
assert!(grid.is_none() && lines.anchor_count() > 0);
}
}
/// A table that fills up is emptied instead of growing, and what is looked up after that is
+19 -7
View File
@@ -207,9 +207,21 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past
/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the
/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name,
/// transparency, opacity mask and appearance.
/// transparency, opacity mask and appearance. It is a knockout group and each piece is a
/// [`crate::NodeExtras::warp_piece`], so where pieces overlap only the top one draws and a
/// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects
/// allow make an empty group.
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
let k = cells.max(1);
let mut g = n.clone();
g.kind = NodeKind::Group { children: vec![], clip: false };
g.knockout = crate::Knockout::On;
if let Some(e) = g.extras_if_any() {
e.colorize = None;
}
if mesh_warp_cost(k) > MAX_GENERATED {
return g;
}
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
let colorize = n.extras().colorize.clone();
// Each piece shows what the image shows: its color mask's masked pixels.
@@ -243,22 +255,22 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
// white opacity mask) instead of its clipping path.
let white = Node::path(n.id, shape, Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0));
pieces.push(Arc::new(image.with_mask(Some(Box::new(crate::OpacityMask::new(white, true))))));
let mut piece = image.with_mask(Some(Box::new(crate::OpacityMask::new(white, true))));
piece.extras_mut().warp_piece = true;
pieces.push(Arc::new(piece));
continue;
}
let mut clip = Node::path(n.id, shape, Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
pieces.push(Arc::new(Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })));
let mut piece = Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true });
piece.extras_mut().warp_piece = true;
pieces.push(Arc::new(piece));
}
}
}
let mut g = n.clone();
g.kind = NodeKind::Group { children: pieces, clip: false };
if let Some(e) = g.extras_if_any() {
e.colorize = None;
}
g
}
+93 -15
View File
@@ -147,14 +147,18 @@ impl Coons {
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
/// left, as a saved file gives them. They stay on those anchors when they run the way the
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
/// A straight segment closes an open subpath, and segments of no length are left out. A top
/// object's envelope maps onto this patch.
/// curve parameter. A side whose pieces, from corner to corner, are all one cubic curve split at
/// anchors (each within 0.02 pt of that curve's piece) runs along that curve instead, by its
/// parameter: splitting the curve of such a side at more anchors, without changing its shape,
/// leaves how the side shares out the content as it was (corners found from the outline can
/// still move). A segment without handles counts as a cubic with its handles a third of the way
/// along, so the content spreads evenly along it. `corners` are the anchors (indices into the
/// outline, in its own order) at the top left, top right, bottom right and bottom left, as a
/// saved file gives them. They stay on those anchors when they run the way the outline does or
/// the opposite way, so a reflected outline keeps them; without them, or when they don't fit
/// the outline, each corner is found from the outline ([`top_object_corner`]). A straight
/// segment closes an open subpath, and segments of no length are left out. A top object's
/// envelope maps onto this patch.
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
let mut sp = sp.clone();
@@ -212,11 +216,12 @@ impl Coons {
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
};
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
// by the length of its control polygon and holds points at even steps of its parameter
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
// or one for each piece when it has more pieces than that.
// through pieces of segments, split at `a` and `b`; when all of them are one curve split
// at anchors ([`one_curve`]), it runs along that curve instead. Each piece takes its share
// of the side by the length of its control polygon and holds points at even steps of its
// parameter (at least 16, and at least `SIDE` points on the side), its ends included. A
// side of many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS`
// points, or one for each piece when it has more pieces than that.
let side = |a: f64, b: f64| {
let span = (b - a).rem_euclid(n);
if !(span.is_finite() && span > 0.0) {
@@ -232,8 +237,11 @@ impl Coons {
}
s = next;
}
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
let pieces = match one_curve(&pieces) {
Some(one) => vec![one],
None => pieces,
};
let mut weights: Vec<f64> = pieces.iter().map(control_polygon).collect();
let mut total: f64 = weights.iter().sum();
if !(total.is_finite() && total > 0.0) {
weights.iter_mut().for_each(|w| *w = 1.0);
@@ -336,6 +344,76 @@ impl Coons {
/// anchors.
const MAX_SIDE_POINTS: usize = 1 << 16;
/// How far, in points, each control point of each piece of a top object's side may lie from the
/// matching piece of one cubic curve for the side to run along that curve ([`one_curve`]); the side
/// then lies within this of the pieces it is drawn with. A curve split into thirds or tenths and
/// saved with its coordinates rounded to 0.001 pt stays within it, on outlines from 5 to 5,000 pt
/// wide; coarser rounding, or a piece of a much smaller share of the curve, can take it past this.
/// A smooth side that isn't one curve, such as an arc of a circle drawn in many pieces, lies
/// further off as a whole, even where each pair of its pieces would not.
const ONE_CURVE: f64 = 0.02;
/// The length of `c`'s control polygon.
fn control_polygon(c: &CubicBez) -> f64 {
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
}
/// The cubic curve that `pieces`, two or more end to end, are all pieces of, split at the anchors
/// between them, when each control point of each piece lies within [`ONE_CURVE`] of the matching
/// piece of that curve; `None` otherwise. Split at parameter `t`, a curve's handles on either side
/// of the split lie in line, their lengths in proportion to the spans of its parameter the two
/// pieces take; split where the curve stops (a cusp), both handles lie on the anchor, and the
/// pieces' second derivatives there, in proportion to the squares of the spans, give the proportion
/// instead (whichever of the two pairs is the longer). Those proportions give each piece's span, and the curve follows from the first
/// piece's start and its handle, and the last piece's end and its handle, scaled up by their spans.
/// Every piece is then checked against that curve's piece over its span, so error can't build up
/// from one split to the next (the first piece's start and handle, and the last piece's end and
/// handle, match by construction).
fn one_curve(pieces: &[CubicBez]) -> Option<CubicBez> {
let (first, last) = (pieces.first()?, pieces.last()?);
if pieces.len() < 2 {
return None;
}
let mut spans = Vec::with_capacity(pieces.len());
spans.push(1.0);
for pair in pieces.windows(2) {
let [a, b] = pair else { return None };
let (into, out) = (a.p3.distance(a.p2), b.p0.distance(b.p1));
// How far each piece bends away from the anchor goes with the squares of the spans. Split
// where the curve stops (a cusp), both handles lie on the anchor and say nothing of the
// spans, and the bends say it; where the curve runs straight through the split, the bends
// are nothing and the handles say it. Whichever pair is the longer is the one to go by.
let bend_in = ((a.p3 - a.p2) - (a.p2 - a.p1)).hypot();
let bend_out = ((b.p2 - b.p1) - (b.p1 - b.p0)).hypot();
let ratio = if into.min(out) >= bend_in.min(bend_out) { out / into } else { (bend_out / bend_in).sqrt() };
let next = spans.last().copied().unwrap_or(1.0) * ratio;
if !(next.is_finite() && next > 0.0) {
return None;
}
spans.push(next);
}
let total: f64 = spans.iter().sum();
let (head, tail) = (spans.first().copied().unwrap_or(1.0) / total, spans.last().copied().unwrap_or(1.0) / total);
if !(total.is_finite() && head > 0.0 && tail > 0.0) {
return None;
}
let one = CubicBez::new(first.p0, first.p0 + (first.p1 - first.p0) / head, last.p3 + (last.p2 - last.p3) / tail, last.p3);
if ![one.p1, one.p2].iter().all(|p| p.is_finite()) {
return None;
}
let near = |p: Point, q: Point| p.distance(q) <= ONE_CURVE;
let mut from = 0.0;
for (k, (piece, span)) in pieces.iter().zip(&spans).enumerate() {
let to = if k + 1 == pieces.len() { 1.0 } else { (from + span / total).min(1.0) };
let part = one.subsegment(from..to);
if !(near(part.p0, piece.p0) && near(part.p1, piece.p1) && near(part.p2, piece.p2) && near(part.p3, piece.p3)) {
return None;
}
from = to;
}
Some(one)
}
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
/// of a top object looks for an anchor.
const CORNER_REACH: f64 = 0.475;
+1
View File
@@ -32,6 +32,7 @@ pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_b
pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
pub(crate) use ops::{held_guides, map_held, strip_held};
use wire::NodeWire;
pub(crate) use wire::counted_list;
pub use wire::{MAX_READ_NODES, with_node_budget};
+5
View File
@@ -75,6 +75,10 @@ pub struct NodeExtras {
/// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are
/// ([`crate::color_mask`]).
pub color_mask: Option<Box<crate::color_mask::ColorMask>>,
/// A piece of an image a raster mesh warp cut up ([`crate::live::mesh_warp_image`]): in a
/// knockout group its knockout shape is the whole area of its triangle, not only where the
/// image is opaque ([`Node::knockout_outline`]).
pub warp_piece: bool,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -103,6 +107,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
envelope_edit_margin: None,
pixel_aligned: false,
color_mask: None,
warp_piece: false,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+100 -21
View File
@@ -211,7 +211,9 @@ impl Node {
/// A quick box round everything the object can paint, for culling clicks: paths and compound
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
/// clipping layer's box takes in the region that the live geometry effects of its clipping
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
@@ -261,6 +263,11 @@ impl Node {
NodeKind::Blend { children, spec } => {
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
}
// The live geometry effects of a clipping path can move or grow the region it clips to
// past its plain shape ([`crate::hit::set_clip_region`]).
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
_ => self.visual(symbols),
}
}
@@ -716,6 +723,37 @@ impl Node {
out
}
/// As a piece of a mesh-warped image ([`crate::NodeExtras::warp_piece`]), the art whose area is its
/// knockout shape at full coverage: the art of its opacity mask (on and not inverted), or the
/// clipping path of its clip group. `None` for other objects, whose knockout shape is what they
/// paint.
pub fn knockout_outline(&self) -> Option<&Arc<Node>> {
let e = self.extras();
if !e.warp_piece {
return None;
}
if let Some(m) = e.mask.as_deref() {
return (!m.disabled && !m.invert).then_some(&m.art);
}
match &self.kind {
NodeKind::Group { children, clip: true } => children.first(),
_ => None,
}
}
/// The image a piece of a mesh-warped image draws ([`Self::knockout_outline`]): the piece itself
/// when an opacity mask cuts it, else the image its clip group clips. `None` for other objects.
pub fn warp_piece_image(&self) -> Option<&Node> {
if !self.extras().warp_piece {
return None;
}
match &self.kind {
NodeKind::Image(_) => Some(self),
NodeKind::Group { children, clip: true } => children.get(1).map(|c| &**c).filter(|c| matches!(c.kind, NodeKind::Image(_))),
_ => None,
}
}
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
/// A layer whose first child is a ruler guide holds no art, so a guide never clips it.
pub fn clips(&self) -> bool {
@@ -732,33 +770,19 @@ impl Node {
children.iter().rposition(|c| !c.is_ruler_guide()).map_or(0, |i| i + 1)
}
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none.
/// Remove the ruler guides of this layer and of its sublayers. Other nodes hold none. Only
/// layers that hold one are copied.
pub fn strip_ruler_guides(&mut self) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
ch.retain(|c| !c.is_ruler_guide());
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides()) {
Arc::make_mut(c).strip_ruler_guides();
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
strip_held(self, held);
}
}
/// Call `f` on the position (along the axis it crosses) of each ruler guide of this layer and
/// of its sublayers, with whether the guide is vertical. Only layers that hold one are copied.
pub fn map_ruler_guide_positions(&mut self, f: &mut impl FnMut(bool, &mut f64)) {
if !self.holds_ruler_guides() {
return;
}
if let Some(ch) = self.children_mut() {
for c in ch.iter_mut().filter(|c| c.is_ruler_guide() || c.holds_ruler_guides()) {
let c = Arc::make_mut(c);
match &mut c.kind {
NodeKind::RulerGuide { vertical, pos, .. } => f(*vertical, pos),
_ => c.map_ruler_guide_positions(f),
}
}
if let Some(held) = held_guides(self, &Self::is_ruler_guide) {
map_held(self, held, f);
}
}
@@ -803,6 +827,61 @@ impl Node {
}
}
/// The ruler guides a layer holds: its children that are one, by index in order (each with
/// nothing inside), and its sublayers holding one (with what they hold).
#[derive(Debug, Default)]
pub(crate) struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds
/// none. `is_guide` looks at each child of `n` and of its sublayers once.
pub(crate) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
let held: Vec<_> = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if is_guide(c) { Some((i, HeldGuides::default())) } else { held_guides(c, is_guide).map(|h| (i, h)) })
.collect();
(!held.is_empty()).then_some(HeldGuides(held))
}
/// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`).
/// Only the sublayers holding one are copied, and only those are visited.
pub(crate) fn strip_held(layer: &mut Node, held: HeldGuides) {
let Some(ch) = layer.children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a ruler guide has nothing inside.
if inner.0.is_empty() {
return false;
}
strip_held(Arc::make_mut(c), inner);
true
});
}
/// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its
/// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers
/// holding one, and the guides, are copied, and only those sublayers are visited.
pub(crate) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = layer.children_mut() else { return };
for (i, inner) in held.0 {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.0.is_empty() {
map_held(Arc::make_mut(c), inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
impl Node {
/// The Appearance panel's row for what this object's own fills and strokes paint around:
/// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters"
+207
View File
@@ -23,6 +23,7 @@ fn extras_are_written_flat_in_order() {
e.shape_mode = crate::ShapeMode::Exclude;
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
e.pixel_aligned = true;
e.warp_piece = true;
}
/// The top-level keys of a JSON object, in the order written.
struct Keys(Vec<String>);
@@ -69,10 +70,12 @@ fn extras_are_written_flat_in_order() {
"shape_mode",
"envelope_edit_margin",
"pixel_aligned",
"warp_piece",
];
assert_eq!(keys, order);
assert_eq!(v["shape_mode"], "exclude");
assert_eq!(v["pixel_aligned"], true);
assert_eq!(v["warp_piece"], true);
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
@@ -595,3 +598,207 @@ fn compound_stroke_path_is_its_members_in_order() {
assert_eq!(bp.elements(), expected.elements());
assert!(!bp.elements().is_empty());
}
/// The sublayers in [`guide_layers`]'s chain, each inside the one before.
const GUIDE_CHAIN: u64 = 30;
/// How many children the layers of [`guide_layers`] hold: the layer's 6, 1 in the sublayer
/// without a guide, 2 at each of the two places the shared sublayer lies, the innermost
/// sublayer's 2 and 3 in each sublayer around it.
const GUIDE_LAYER_CHILDREN: usize = 6 + 1 + 2 * 2 + 2 + (GUIDE_CHAIN as usize - 1) * 3;
/// How many ruler guides the layers of [`guide_layers`] hold: one in each sublayer of the chain,
/// one at each place the shared sublayer lies and the layer's own.
const GUIDE_LAYER_GUIDES: usize = GUIDE_CHAIN as usize + 2 + 1;
/// A layer holding, in order: [`GUIDE_CHAIN`] sublayers, each inside the one before and holding an
/// object and a ruler guide; a sublayer with an object only; a sublayer with an object and a
/// guide; an object; that last sublayer again; and a guide. Guides differ in direction, artboard
/// and lock. Returns the layer, the sublayer without a guide and the one that lies twice.
fn guide_layers() -> (Node, Arc<Node>, Arc<Node>) {
let rect = |id| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()));
let guide = |id: u64| {
let kind = NodeKind::RulerGuide { vertical: id.is_multiple_of(2), pos: id as f64, artboard: id.is_multiple_of(3).then_some(7) };
let mut g = Node::new(NodeId(id), kind);
g.locked = id.is_multiple_of(5);
Arc::new(g)
};
let sublayer = |id, children: Vec<Arc<Node>>| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
Arc::new(l)
};
let mut chain = sublayer(100, vec![rect(150), guide(200)]);
for depth in 1..GUIDE_CHAIN {
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth)]);
}
let still = sublayer(500, vec![rect(501)]);
let twice = sublayer(510, vec![rect(511), guide(512)]);
let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
*ch = vec![chain, Arc::clone(&still), Arc::clone(&twice), rect(2), Arc::clone(&twice), guide(3)];
}
(layer, still, twice)
}
/// Whether `a` and `b` hold the same children, none of them copied.
fn same_children(a: &Node, b: &Node) -> bool {
let (a, b) = (a.children().unwrap(), b.children().unwrap());
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b))
}
/// Stripping the ruler guides of a layer looks at each child of the layer and of its sublayers
/// once, however deep the sublayers nest. The art and its order stay, a sublayer without a guide is
/// not copied, and a copy of the layer held elsewhere keeps its guides.
#[test]
fn stripping_ruler_guides_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let ids = |n: &Node| {
let mut out = vec![];
n.walk(&mut |c| out.push(c.id));
out
};
let mut art = vec![];
whole.walk(&mut |c| {
if !c.is_ruler_guide() {
art.push(c.id);
}
});
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
super::ops::strip_held(&mut n, held);
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "removing looks at nothing again");
assert_eq!(ids(&n), art, "the art stays, in its order");
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
assert_eq!(
(ch[2].children().map(Vec::len), ch[4].children().map(Vec::len)),
(Some(1), Some(1)),
"a sublayer lying twice is stripped at both places"
);
// The copies held elsewhere (an undo step's, say) keep their guides.
assert_eq!(twice.children().map(Vec::len), Some(2));
assert_eq!(ids(&whole).len(), art.len() + GUIDE_LAYER_GUIDES);
// The method strips the same guides.
let mut same = whole.clone();
same.strip_ruler_guides();
assert_eq!(same, n);
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// With no guide left there is nothing to remove, and nothing is copied.
let before = n.clone();
n.strip_ruler_guides();
assert!(same_children(&n, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.strip_ruler_guides();
assert_eq!(empty.children().map(Vec::len), Some(0));
// Only a layer holds ruler guides: a group is left as it is, on its own and in a layer.
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
assert!(super::ops::held_guides(&group, &Node::is_ruler_guide).is_none());
group.strip_ruler_guides();
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
let group = Arc::new(group);
let mut around = Node::layer(NodeId(902), "Around", LayerColor::Preset(0));
around.children_mut().unwrap().push(Arc::clone(&group));
around.strip_ruler_guides();
assert!(Arc::ptr_eq(&around.children().unwrap()[0], &group));
}
/// Changing the positions of the ruler guides of a layer looks at each child of the layer and of
/// its sublayers once, however deep the sublayers nest. Each guide is changed once, in the order
/// the guides lie in, and keeps everything else about it; the art is unchanged, a sublayer without
/// a guide is not copied, and a copy of the layer held elsewhere keeps its positions.
#[test]
fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
use std::cell::Cell;
let (whole, still, twice) = guide_layers();
let mut lines = vec![];
whole.walk(&mut |c| {
if let NodeKind::RulerGuide { vertical, pos, .. } = c.kind {
lines.push((vertical, pos));
}
});
assert_eq!(lines.len(), GUIDE_LAYER_GUIDES);
assert!(lines.iter().any(|l| l.0) && lines.iter().any(|l| !l.0), "guides in both directions");
let mut n = whole.clone();
let looked = Cell::new(0_usize);
let pick = |c: &Node| {
looked.set(looked.get() + 1);
c.is_ruler_guide()
};
let held = super::ops::held_guides(&n, &pick).unwrap();
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
super::ops::map_held(&mut n, held, &mut |vertical, pos| {
seen.push((vertical, *pos));
*pos = *pos * 2.0 + 1.0;
});
assert_eq!(looked.get(), GUIDE_LAYER_CHILDREN, "changing looks at nothing again");
assert_eq!(seen, lines, "each guide once, in the order the guides lie in");
// The same nodes in the same order: a guide differs in its position alone, and the art not
// at all.
let (mut was, mut now) = (vec![], vec![]);
whole.walk(&mut |c| was.push(c));
n.walk(&mut |c| now.push(c));
assert_eq!(was.len(), now.len());
for (a, b) in was.into_iter().zip(now) {
if a.is_layer() {
assert_eq!((b.id, b.is_layer(), b.children().map(Vec::len)), (a.id, true, a.children().map(Vec::len)));
continue;
}
let mut want = a.clone();
if let NodeKind::RulerGuide { pos, .. } = &mut want.kind {
*pos = *pos * 2.0 + 1.0;
}
assert_eq!(b, &want);
}
let ch = n.children().unwrap();
assert!(Arc::ptr_eq(&ch[1], &still), "a sublayer without a guide is not copied");
assert!(Arc::ptr_eq(&ch[3], &whole.children().unwrap()[3]), "an object is not copied");
assert!(!Arc::ptr_eq(&ch[2], &twice) && !Arc::ptr_eq(&ch[4], &twice) && !Arc::ptr_eq(&ch[2], &ch[4]));
// The copy held elsewhere keeps its position.
assert!(matches!(twice.children().unwrap()[1].kind, NodeKind::RulerGuide { pos, .. } if pos == 512.0));
// The method changes the same guides, each once.
let mut same = whole.clone();
let mut calls = 0;
same.map_ruler_guide_positions(&mut |_, pos| {
calls += 1;
*pos = *pos * 2.0 + 1.0;
});
assert_eq!((calls, &same), (GUIDE_LAYER_GUIDES, &n));
assert!(Arc::ptr_eq(&same.children().unwrap()[1], &still));
// A function that leaves the positions as they are is still called on each guide.
let mut kept = whole.clone();
let mut calls = 0;
kept.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert_eq!((calls, &kept), (GUIDE_LAYER_GUIDES, &whole));
// A layer without a guide, an empty layer and a group: nothing to change, nothing copied.
let mut bare = whole.clone();
bare.strip_ruler_guides();
let before = bare.clone();
let mut calls = 0;
bare.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(same_children(&bare, &before));
let mut empty = Node::layer(NodeId(900), "Empty", LayerColor::Preset(0));
empty.map_ruler_guide_positions(&mut |_, _| calls += 1);
let mut group = Node::group(NodeId(901), vec![Arc::clone(&twice)]);
group.map_ruler_guide_positions(&mut |_, _| calls += 1);
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
+5
View File
@@ -56,6 +56,7 @@ impl Serialize for Node {
e.envelope_edit_margin.is_none(),
is_default(&e.pixel_aligned),
e.color_mask.is_none(),
is_default(&e.warp_piece),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -100,6 +101,7 @@ impl Serialize for Node {
field!("envelope_edit_margin", &e.envelope_edit_margin);
field!("pixel_aligned", &e.pixel_aligned);
field!("color_mask", &e.color_mask);
field!("warp_piece", &e.warp_piece);
st.end()
}
}
@@ -245,6 +247,8 @@ pub(super) struct NodeWire {
pixel_aligned: bool,
#[serde(default)]
color_mask: Option<Box<crate::color_mask::ColorMask>>,
#[serde(default)]
warp_piece: bool,
}
impl From<NodeWire> for Node {
@@ -274,6 +278,7 @@ impl From<NodeWire> for Node {
envelope_edit_margin: w.envelope_edit_margin,
pixel_aligned: w.pixel_aligned,
color_mask: w.color_mask,
warp_piece: w.warp_piece,
};
Node {
id: w.id,
+156 -33
View File
@@ -121,19 +121,22 @@ impl ObjectsOnPath {
if a.determinant() < 0.0 && self.rotate != 0.0 {
self.rotate = -self.rotate;
}
let along = paths.and_then(|(old, new)| {
let s = path_length(new)?.0 / path_length(old)?.0;
(s.is_finite() && s > 0.0).then_some(s)
});
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
// A move leaves the distances along the path as they are.
let moves = a0 == 1.0 && a1 == 0.0 && a2 == 0.0 && a3 == 1.0;
if !moves && scale.is_finite() && scale > 0.0 {
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
let moved = paths.and_then(|(old, new)| self.moved_along(a, old, new, scale));
let (spacing, start) = moved.unwrap_or((None, None));
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
self.start = start.unwrap_or_else(|| scaled(self.start));
if !moves {
let measured = paths.and_then(|(old, new)| Some((Measured::new(old)?, Measured::new(new)?)));
let along = measured.as_ref().and_then(|(was, is)| {
let s = is.len / was.len;
(s.is_finite() && s > 0.0).then_some(s)
});
let scale = along.unwrap_or_else(|| a.determinant().abs().sqrt());
if scale.is_finite() && scale > 0.0 {
let scaled = |v: f64| Some(v * scale).filter(|s| s.is_finite()).unwrap_or(v);
let moved = measured.as_ref().and_then(|(was, is)| self.moved_along(a, was, is, scale));
let (spacing, start) = moved.unwrap_or((None, None));
self.spacing = self.spacing.map(|g| spacing.unwrap_or_else(|| scaled(g)));
self.start = start.unwrap_or_else(|| scaled(self.start));
}
}
let after = tilt(self.rotate);
for m in &mut self.members {
@@ -150,11 +153,10 @@ impl ObjectsOnPath {
/// point on `old`, mapped by `a`, measured along `new` near `scale` times its distance along
/// `old`. Either one is `None` when it cannot be followed that way: a start before or beyond the
/// ends of an open path, or a Space value of 0, one the path has no room for, or one with fewer
/// than two objects. `None` for a path without length or a start that is not finite.
fn moved_along(&self, a: Affine, old: &PathData, new: &PathData, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
let (was, is) = (Spine::new(old)?, Spine::new(new)?);
let (len, closed) = path_length(old)?;
let (new_len, _) = path_length(new)?;
/// than two objects. `None` for a start that is not finite.
fn moved_along(&self, a: Affine, old: &Measured, new: &Measured, scale: f64) -> Option<(Option<f64>, Option<f64>)> {
let (was, is) = (&old.spine, &new.spine);
let (len, closed, new_len) = (old.len, old.closed, new.len);
if !self.start.is_finite() {
return None;
}
@@ -230,10 +232,16 @@ pub fn is_objects_on_path(n: &Node) -> bool {
}
/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path
/// (not a guide) whose first subpath has some length.
/// (not a guide) whose first subpath has a length ([`path_length`]).
pub fn attachable_path(n: &Node) -> Option<&PathData> {
attachable(n).map(|(path, _)| path)
}
/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks
/// its length.
pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if Spine::new(path).is_some_and(|s| s.length() > 1e-9) => Some(path),
NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)),
_ => None,
}
}
@@ -292,11 +300,58 @@ pub fn upright_frame(n: &Node) -> Affine {
}
/// The length of `path`'s first subpath and whether it is closed. `None` for a path without
/// length.
/// length, or with a length too large to be finite.
pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
let len = Spine::new(path)?.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some((len, closed))
Measured::new(path).map(|m| (m.len, m.closed))
}
/// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that
/// one flattening serves both measuring the path and finding points along it.
pub struct Measured {
spine: Spine,
len: f64,
closed: bool,
}
impl std::fmt::Debug for Measured {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive()
}
}
impl Measured {
/// `None` for a path without length, or with a length too large to be finite.
pub fn new(path: &PathData) -> Option<Self> {
let spine = Spine::new(path)?;
let len = spine.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed })
}
/// The flattened first subpath, to measure along.
pub fn spine(&self) -> &Spine {
&self.spine
}
/// The length of the first subpath (points), as [`path_length`] gives it.
pub fn length(&self) -> f64 {
self.len
}
/// Is the first subpath closed?
pub fn closed(&self) -> bool {
self.closed
}
/// [`stops`] on this path.
pub fn stops(&self, n: usize, spacing: Option<f64>, start: f64) -> Vec<(Point, f64)> {
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
(0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect()
}
/// [`stop`] on this path: `None` for an `i` of `n` or more.
pub fn stop(&self, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
if i >= n {
return None;
}
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i)))
}
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
@@ -341,18 +396,16 @@ fn wrap(s: f64, len: f64) -> f64 {
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
Some(Measured::new(path)?.stops(n, spacing, start))
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
/// `None` for an `i` of `n` or more, without measuring the path.
pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
let spine = Spine::new(path)?;
let (len, closed) = path_length(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
(i < n).then(|| spine.at_length(nth_length(len, closed, start, gap, i)))
if i >= n {
return None;
}
Measured::new(path)?.stop(n, spacing, start, i)
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
@@ -400,11 +453,15 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
let old = rec.clone();
let NodeKind::Group { children, .. } = &mut g.kind else { return false };
let path_id = rec.path;
let Some(path) = children.iter().find(|c| c.id == path_id).filter(|c| matches!(c.kind, NodeKind::Path { .. })) else {
let Some(path) = children.iter().find(|c| c.id == path_id).filter(|c| matches!(c.kind, NodeKind::Path { .. })).cloned() else {
g.extras_mut().objects_on_path = None;
return true;
};
let path = attachable_path(path).cloned();
// `stops` measures the path: on a path without length no object moves.
let path = match &path.kind {
NodeKind::Path { path, guide: false, .. } => Some(path),
_ => None,
};
let at: HashMap<NodeId, usize> = children.iter().enumerate().map(|(i, c)| (c.id, i)).collect();
rec.members.retain(|m| m.id != path_id && at.contains_key(&m.id));
let mut listed: HashSet<NodeId> = rec.members.iter().map(|m| m.id).collect();
@@ -414,7 +471,7 @@ pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool {
}
}
let mut moved = false;
if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len(), rec.spacing, rec.start)) {
if let Some(stops) = path.and_then(|p| stops(p, rec.members.len(), rec.spacing, rec.start)) {
let turn = tilt(rec.rotate);
for (m, (p, dir)) in rec.members.iter_mut().zip(stops) {
let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue };
@@ -709,6 +766,72 @@ mod tests {
assert!((back.angle - 0.5).abs() < 1e-12, "{back:?}");
}
/// What `f` returns, and how many times it flattened a path ([`Spine::new`]).
fn flattenings<T>(f: impl FnOnce() -> T) -> (T, usize) {
crate::blend::SPINES_BUILT.with(|n| n.set(0));
let out = f();
(out, crate::blend::SPINES_BUILT.with(|n| n.get()))
}
#[test]
fn stops_and_stop_flatten_the_path_once() {
let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
for path in [&open, &closed] {
let (all, count) = flattenings(|| stops(path, 4, Some(40.0), 25.0));
let all = all.unwrap();
assert_eq!((all.len(), count), (4, 1));
for (i, s) in all.iter().enumerate() {
assert_eq!(flattenings(|| stop(path, 4, Some(40.0), 25.0, i)), (Some(*s), 1), "object {i}");
}
assert_eq!(flattenings(|| stop(path, 4, Some(40.0), 25.0, 4)), (None, 0), "an index past the last object");
assert_eq!(flattenings(|| stop(path, 0, None, 0.0, 0)), (None, 0), "no objects");
}
let point = shapes::line(Point::ZERO, Point::ZERO);
assert!(stops(&point, 2, None, 0.0).is_none() && stop(&point, 2, None, 0.0, 0).is_none());
}
#[test]
fn transforming_the_group_flattens_each_path_once() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
let b = rect(3, Rect::new(20.0, 0.0, 30.0, 10.0));
let level = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let stretch = Affine::scale_non_uniform(2.0, 1.0);
let wide = level.transformed(stretch);
let mut rec = ObjectsOnPath { spacing: Some(40.0), start: 10.0, ..ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0) };
let ((), count) = flattenings(|| rec.transform(stretch, Some((&level, &wide))));
assert_eq!(count, 2, "the path before the transform and after it");
assert!((rec.start - 20.0).abs() < 1e-9 && (rec.spacing.unwrap() - 80.0).abs() < 1e-9, "{rec:?}");
let moved = level.transformed(Affine::translate((5.0, 5.0)));
let ((), count) = flattenings(|| rec.transform(Affine::translate((5.0, 5.0)), Some((&level, &moved))));
assert_eq!(count, 0, "a move leaves the distances along the path as they are");
}
#[test]
fn placing_the_objects_flattens_the_path_once() {
let line = Node::path(NodeId(1), shapes::line(Point::new(0.0, 100.0), Point::new(300.0, 100.0)), Default::default());
let (a, b) = (rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)), rect(3, Rect::new(20.0, 0.0, 30.0, 10.0)));
let mut g = Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(line), Arc::new(a.clone()), Arc::new(b.clone())], clip: false });
g.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath::new(NodeId(1), &[&a, &b], CENTER, 0.0)));
let empty = crate::Document::new(1.0, 1.0);
let symbols = empty.symbol_boxes();
assert_eq!(flattenings(|| place(&mut g, &symbols)), (true, 1));
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
assert!((x(NodeId(2))).abs() < 1e-9 && (x(NodeId(3)) - 300.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
}
/// A path whose length adds up past the largest finite number cannot be measured, so nothing
/// attaches to it.
#[test]
fn a_path_too_long_to_measure_is_not_attachable() {
let huge = Node::path(NodeId(1), shapes::line(Point::new(-1e308, 0.0), Point::new(1e308, 0.0)), Default::default());
let NodeKind::Path { path, .. } = &huge.kind else { panic!("a path") };
assert!(path_length(path).is_none() && stops(path, 2, None, 0.0).is_none());
assert!(attachable_path(&huge).is_none());
let square = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
assert!(attachable_path(&square).is_some());
}
#[test]
fn a_group_without_its_path_is_a_plain_group() {
let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0));
+68
View File
@@ -3,6 +3,8 @@
//! square to it: scaling by a side handle stretches it along its own width or height. Path
//! geometry is still baked; Object ▸ Transform ▸ Reset Bounding Box sets the angle back to 0.
use std::sync::Arc;
use vectorcraft_geom::{Affine, Point, Rect, Vec2, normalize_deg, union_opt};
use crate::{Document, Node, NodeId, NodeKind, SymbolBoxes};
@@ -84,7 +86,35 @@ pub fn transformed_angle(angle: f64, a: Affine) -> f64 {
}
}
/// The turn (counter-clockwise degrees) from the boxes of art placed by a symbol instance's
/// transform `xf` to the instance's own box at `angle`: 0 while the box turns with the transform,
/// otherwise the change Reset Bounding Box made to it. Under a mirroring `xf` the instance's box can
/// stand 180° from the one `xf` gives in one step ([`transformed_angle`] keeps the angle nearer the
/// one before at each step); the turn is then 180°, so the art's boxes match the instance's.
pub fn placed_turn(angle: f64, xf: Affine) -> f64 {
let turn = normalize_deg(angle - transformed_angle(0.0, xf));
if turn.is_finite() && turn.abs() > EPS_DEG { turn } else { 0.0 }
}
impl Node {
/// Turns the box of this object, and of every object that turns with it ([`Node::transform`]:
/// its children and the art of a linked opacity mask), by `by` degrees counter-clockwise.
/// Layers have no box.
pub fn turn_boxes(&mut self, by: f64) {
if !self.is_layer() {
let a = normalize_deg(self.bbox_angle + by);
self.bbox_angle = if a.abs() <= EPS_DEG { 0.0 } else { a };
}
for c in self.children_mut().into_iter().flatten() {
Arc::make_mut(c).turn_boxes(by);
}
if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut())
&& m.linked
{
Arc::make_mut(&mut m.art).turn_boxes(by);
}
}
/// Bounds of this object as `a` would place it (geometric, or `visual` with its strokes),
/// without changing it, symbol instances measured by their art from `symbols`
/// ([`Node::geometric_bounds_with`]).
@@ -185,6 +215,44 @@ mod tests {
assert_eq!(transformed_angle(30.0, Affine::scale(0.0)), 30.0);
}
#[test]
fn placed_turn_is_what_reset_bounding_box_took_off_the_instance() {
let xf = Affine::translate((40.0, 10.0)) * rot(20.0) * Affine::scale_non_uniform(2.0, 0.5);
// The box turns with the transform: no turn.
assert_eq!(placed_turn(transformed_angle(0.0, xf), xf), 0.0);
assert_eq!(placed_turn(0.0, Affine::scale(3.0)), 0.0);
// Reset to 0: the placed art turns back by the 20°.
assert!(close(placed_turn(0.0, xf), -20.0));
// Mirrored: turned 170° and then flipped, the instance's box stands 180° from the box the
// whole transform gives in one step, and the art turns the half turn to match it.
let flip = Affine::scale_non_uniform(1.0, -1.0);
let flipped = flip * rot(170.0);
let stepwise = transformed_angle(transformed_angle(0.0, rot(170.0)), flip);
assert!(close(stepwise, -170.0) && close(transformed_angle(0.0, flipped), 10.0));
assert!(close(placed_turn(stepwise, flipped).abs(), 180.0));
assert!(close(normalize_deg(placed_turn(0.0, flipped) + transformed_angle(0.0, flipped)), 0.0));
// Degenerate and non-finite transforms turn nothing.
assert_eq!(placed_turn(0.0, Affine::scale(0.0)), 0.0);
assert_eq!(placed_turn(f64::NAN, xf), 0.0);
}
#[test]
fn turn_boxes_turns_children_and_linked_mask_art_but_not_layers() {
let mut d = Document::new(500.0, 500.0);
let a = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let mut g = Node::group(d.alloc_id(), vec![Arc::new(a.clone())]);
g.bbox_angle = 170.0;
g.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(a.clone(), true)));
let mut layer = (*d.layers[0]).clone();
layer.children_mut().unwrap().push(Arc::new(g));
layer.turn_boxes(20.0);
assert_eq!(layer.bbox_angle, 0.0);
let g = &layer.children().unwrap()[0];
assert!(close(g.bbox_angle, -170.0), "wraps to (-180, 180]");
assert!(close(g.children().unwrap()[0].bbox_angle, 20.0));
assert!(close(g.extras().mask.as_ref().unwrap().art.bbox_angle, 20.0));
}
#[test]
fn oriented_bounds_hug_a_rotated_rectangle() {
let mut d = Document::new(500.0, 500.0);
+35
View File
@@ -194,6 +194,27 @@ impl ImageBlob {
.collect();
Some((w, h, cover))
}
/// The pixels as straight RGBA, row by row from the top, with the width and the height;
/// `None` when the image can't be decoded within [`MAX_RASTER_ALLOC`].
pub fn rgba(&self) -> Option<(u32, u32, Vec<u8>)> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
Some((w, h, img.into_raw()))
}
/// The width and height in pixels the image's file says it has; `None` for data that isn't an
/// image the decoder reads. Reads only its header.
pub fn pixel_size(&self) -> Option<(u32, u32)> {
image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok()
}
/// Whether the image's file is a PNG that stores palette indices (an indexed-color image).
/// Reads only its header.
pub fn indexed_png(&self) -> bool {
// The signature, then the IHDR chunk: length, type, width, height, bit depth, color type.
self.bytes.starts_with(b"\x89PNG\r\n\x1a\n") && self.bytes.get(12..16) == Some(b"IHDR".as_slice()) && self.bytes.get(25) == Some(&3)
}
}
impl ImageBlob {
@@ -266,6 +287,20 @@ impl ImageBlob {
Some(out)
}
/// Whether any pixel of the image is less than fully opaque. `false` when the image can't be
/// decoded. The last image decoded is kept, as for [`Self::sample`].
pub fn has_transparency(&self) -> bool {
self.decoded().is_some_and(|img| img.pixels().any(|p| p.0[3] < 255))
}
/// The alpha of each pixel, row by row from the top: the width, the height and one byte a
/// pixel. `None` when the image can't be decoded. The last image decoded is kept, as for
/// [`Self::sample`].
pub fn alpha(&self) -> Option<(u32, u32, Vec<u8>)> {
let img = self.decoded()?;
Some((img.width(), img.height(), img.pixels().map(|p| p.0[3]).collect()))
}
/// The decoded pixels (the last image decoded is kept for the next sample).
fn decoded(&self) -> Option<Arc<image::RgbaImage>> {
thread_local! {
+4 -1
View File
@@ -166,13 +166,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
}
}
/// The roots of `d`'s art: layers, symbol definitions and pattern swatches.
/// The roots of `d`'s art: layers, symbol definitions, pattern swatches and
/// [`Document::mounted_art`].
fn roots(d: &Document) -> impl Iterator<Item = &Arc<Node>> {
d.layers
.iter()
.chain(d.symbols.iter().map(|s| &s.art))
.chain(d.graph_designs.iter().map(|g| &g.art))
.chain(d.patterns.iter().flat_map(|p| &p.art))
.chain(d.mounted_art.iter().map(|(n, _)| n))
}
fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
@@ -181,6 +183,7 @@ fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
.chain(d.symbols.iter_mut().map(|s| &mut s.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(d.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(d.mounted_art.iter_mut().map(|(n, _)| n))
}
impl Document {
+287
View File
@@ -0,0 +1,287 @@
//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`,
//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image
//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]).
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads?
pub fn reads(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(&[0xff, 0xd8])
|| bytes.starts_with(b"II*\0")
|| bytes.starts_with(b"MM\0*")
|| (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP")
|| bytes.starts_with(b"BM")
}
/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each
/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files.
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else {
None
};
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
}
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
b.get(at..at.checked_add(n)?)
}
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi
/// in the stored pixels' axes, unchecked; `None` without an absolute unit.
pub fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = slice(b, at + 8, len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
pub fn pixels_per_metre(ppi: f64) -> u32 {
(ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32
}
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
fn crc32(parts: &[&[u8]]) -> u32 {
let mut crc = !0u32;
for &b in parts.iter().flat_map(|p| p.iter()) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
}
}
!crc
}
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
// x, y, unit 1 = metre.
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
let mut out = Vec::with_capacity(21);
out.extend_from_slice(&9u32.to_be_bytes());
out.extend_from_slice(b"pHYs");
out.extend_from_slice(&data);
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
out
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there.
#[test]
fn a_png_takes_its_resolution_and_still_decodes() {
let png = png_of(4, 3);
assert_eq!(resolution(&png), None);
let tagged = with_png_resolution(&png, (300.0, 150.0));
assert_eq!(resolution(&tagged), Some((300.0, 150.0)));
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
// Every PNG ends with this IEND chunk CRC.
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
}
/// RIFF chunk `ty` holding `data`, padded to an even length.
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
if data.len() % 2 == 1 {
out.push(0);
}
out
}
fn webp_of(chunks: &[Vec<u8>]) -> Vec<u8> {
let body = chunks.concat();
let size = u32::try_from(body.len() + 4).unwrap();
[b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat()
}
/// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose
/// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to
/// an offset) gives no resolution.
#[test]
fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() {
// Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch.
let mut tiff = b"II*\0".to_vec();
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&2u16.to_le_bytes());
for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&ty.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
}
tiff.extend_from_slice(&0u32.to_le_bytes());
tiff.extend_from_slice(&300u32.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
let exif = [b"Exif\0\0".as_slice(), &tiff].concat();
let exif_len = u32::try_from(exif.len()).unwrap();
let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]);
assert_eq!(resolution(&ok), Some((300.0, 300.0)));
for len in [u32::MAX, u32::MAX - 7, 1_000] {
let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]);
assert_eq!(resolution(&bad), None, "chunk length {len}");
}
}
}
+259
View File
@@ -0,0 +1,259 @@
//! Scaling images whose pixels carry straight (not premultiplied) alpha.
//!
//! `image`'s filtered resampling filters each channel on its own, which is correct only for
//! premultiplied pixels, and its thumbnail averages each channel on its own too, so on
//! straight-alpha pixels the color under clear pixels bleeds into the opaque ones next to them
//! (clear black darkens a cut-out's edge). [`resized`], [`fitted`] and [`averaged`] weight each
//! pixel's color by its alpha while scaling, as the streaming shrink in the renderer does.
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
/// How [`resized`] makes each new pixel from the old ones.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Resample {
/// `image`'s filtered resampling with this filter.
Filter(FilterType),
/// The mean of the old pixels each new one covers ([`averaged`]).
Average,
}
/// `img` scaled to `w` × `h` pixels as `how` says, each pixel's color weighted by its alpha.
/// Filtered or averaged, an image with clear or partly clear pixels comes back as 8-bit RGBA
/// whatever its own pixel format, and a pixel that ends up wholly clear is transparent black. An
/// image without clear pixels is scaled as `image` scales it, in its own pixel format.
/// Nearest-neighbor picking leaves the pixels as they are, in their own format, and is not
/// weighted. Filtered, the colors keep the precision of premultiplied 8-bit pixels, and an 8-bit
/// RGBA image is premultiplied in place.
pub fn resized(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
if (w, h) == (img.width(), img.height()) {
return img;
}
let f = match how {
Resample::Average => return averaged(&img, w, h),
Resample::Filter(f) => f,
};
if f == FilterType::Nearest || opaque(&img) {
return img.resize_exact(w, h, f);
}
let mut rgba = img.into_rgba8();
for p in rgba.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = times_alpha(*c, *a);
}
}
let mut out = image::imageops::resize(&rgba, w, h, f);
for p in out.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = over_alpha(*c, *a);
}
}
DynamicImage::ImageRgba8(out)
}
/// [`resized`] to the largest size that fits `w` × `h` pixels and keeps `img`'s proportions, the
/// size `image`'s own `resize` and `thumbnail` pick.
pub fn fitted(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
let (nw, nh) = fit_size(img.width(), img.height(), w, h);
resized(img, nw, nh, how)
}
/// `img` scaled to `w` × `h` pixels, each new pixel the mean of the old pixels it covers, each old
/// pixel counted by the area of it covered and its color weighted by its alpha. `img` is read one
/// row at a time, so besides the result this takes one row of 8-bit RGBA at most. An image
/// without clear pixels is scaled as `image`'s thumbnail scales it.
pub fn averaged(img: &DynamicImage, w: u32, h: u32) -> DynamicImage {
let (sw, sh) = (img.width(), img.height());
if opaque(img) || w == 0 || h == 0 || sw == 0 || sh == 0 {
return img.thumbnail_exact(w, h);
}
// Per new pixel of the row being made: red, green and blue times alpha, alpha (all times the
// area covered), and the area covered.
let mut sums = vec![([0f64; 4], 0f64); w as usize];
let mut out = Vec::with_capacity(w as usize * h as usize * 4);
for ty in 0..h {
for (y, wy) in covered(ty, sh, h) {
let row = rgba_row(img, y as u32);
for ((s, area), tx) in sums.iter_mut().zip(0..w) {
for (x, wx) in covered(tx, sw, w) {
let Some(p) = row.get(x * 4..x * 4 + 4) else { continue };
let k = wx * wy;
let a = f64::from(p[3]) * k;
s[0] += f64::from(p[0]) * a;
s[1] += f64::from(p[1]) * a;
s[2] += f64::from(p[2]) * a;
s[3] += a;
*area += k;
}
}
}
let byte = |v: f64| v.round().clamp(0.0, 255.0) as u8;
for (s, area) in &mut sums {
out.extend(if s[3] <= 0.0 { [0; 4] } else { [byte(s[0] / s[3]), byte(s[1] / s[3]), byte(s[2] / s[3]), byte(s[3] / *area)] });
(*s, *area) = ([0.0; 4], 0.0);
}
}
RgbaImage::from_raw(w, h, out).map_or_else(|| img.thumbnail_exact(w, h), DynamicImage::ImageRgba8)
}
/// Row `y` of `img` as 8-bit RGBA: borrowed from an 8-bit RGBA image, converted from others.
fn rgba_row(img: &DynamicImage, y: u32) -> std::borrow::Cow<'_, [u8]> {
let n = img.width() as usize * 4;
match img {
DynamicImage::ImageRgba8(b) => std::borrow::Cow::Borrowed(b.as_raw().get(y as usize * n..(y as usize + 1) * n).unwrap_or_default()),
other => std::borrow::Cow::Owned(other.crop_imm(0, y, other.width(), 1).into_rgba8().into_raw()),
}
}
/// The old pixels that new pixel `t` of `tn` covers along a side of `n` old pixels, each with the
/// length of it covered (in old pixels), worked out as they are read so that nothing is stored.
fn covered(t: u32, n: u32, tn: u32) -> impl Iterator<Item = (usize, f64)> {
let scale = f64::from(n) / f64::from(tn);
let (a, b) = (f64::from(t) * scale, (f64::from(t) + 1.0) * scale);
let (first, end) = (a.floor() as u32, (b.ceil() as u32).min(n));
(first..end.max(first + 1).min(n)).filter_map(move |i| {
let len = b.min(f64::from(i) + 1.0) - a.max(f64::from(i));
(len > 0.0).then_some((i as usize, len))
})
}
/// Each 4-channel pixel of `px` with all four channels multiplied by its value in `alpha` (one
/// sample a pixel, 0 to 255): ink amounts or colors made ready for scaling beside a separate alpha
/// channel. Pixels past the end of `alpha` are left as they are.
pub fn premultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = times_alpha(*c, a);
}
}
}
/// [`premultiply`] undone after scaling: each 4-channel pixel of `px` divided by its value in the
/// scaled `alpha`, and 0 where that is 0.
pub fn unpremultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = over_alpha(*c, a);
}
}
}
/// Does `img` have no alpha channel, or is every pixel of it opaque?
fn opaque(img: &DynamicImage) -> bool {
match img {
DynamicImage::ImageRgba8(b) => b.pixels().all(|p| p[3] == u8::MAX),
DynamicImage::ImageLumaA8(b) => b.pixels().all(|p| p[1] == u8::MAX),
DynamicImage::ImageRgba16(b) => b.pixels().all(|p| p[3] == u16::MAX),
DynamicImage::ImageLumaA16(b) => b.pixels().all(|p| p[1] == u16::MAX),
DynamicImage::ImageRgba32F(b) => b.pixels().all(|p| p[3] >= 1.0),
other => !other.color().has_alpha(),
}
}
/// Channel `c` times alpha `a`, both 0 to 255.
fn times_alpha(c: u8, a: u8) -> u8 {
((u16::from(c) * u16::from(a) + 127) / 255) as u8
}
/// Premultiplied channel `c` divided by alpha `a` (0 when `a` is 0).
fn over_alpha(c: u8, a: u8) -> u8 {
if a == 0 {
return 0;
}
let a = u32::from(a);
((u32::from(c) * 255 + a / 2) / a).min(255) as u8
}
/// The largest size of at most `nw` × `nh` with the proportions of `w` × `h`, at least a pixel a
/// side.
pub fn fit_size(w: u32, h: u32, nw: u32, nh: u32) -> (u32, u32) {
if w == 0 || h == 0 {
return (nw.max(1), nh.max(1));
}
let ratio = (f64::from(nw) / f64::from(w)).min(f64::from(nh) / f64::from(h));
let side = |n: u32| ((f64::from(n) * ratio).round() as u32).max(1);
(side(w), side(h))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 4 × 2 image whose left half is opaque red and whose right half is clear black.
fn half_clear() -> DynamicImage {
DynamicImage::ImageRgba8(RgbaImage::from_fn(4, 2, |x, _| if x < 2 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }))
}
/// Is the color of `p`, premultiplied by its alpha, within a step of `rgb` premultiplied by the
/// same alpha (the precision of premultiplied 8-bit pixels)?
fn close(p: [u8; 4], rgb: [u8; 3]) -> bool {
p[..3].iter().zip(rgb).all(|(&c, want)| times_alpha(c, p[3]).abs_diff(times_alpha(want, p[3])) <= 1)
}
#[test]
fn averaging_keeps_the_color_of_the_opaque_pixels() {
let p = resized(half_clear(), 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0;
assert!(close(p, [200, 30, 30]) && p[3].abs_diff(128) <= 1, "{p:?}");
}
/// Three pixels averaged into two: each new pixel takes one old pixel whole and half of the
/// clear one in the middle.
#[test]
fn averaging_counts_the_part_of_a_pixel_covered() {
let img = RgbaImage::from_fn(3, 1, |x, _| if x == 1 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([200, 30, 30, 255]) });
let out = averaged(&DynamicImage::ImageRgba8(img), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 30, 30, 170], [200, 30, 30, 170]].concat());
// Gray with alpha is read the same way.
let gray = image::GrayAlphaImage::from_fn(3, 1, |x, _| image::LumaA(if x == 1 { [0, 0] } else { [200, 255] }));
let out = averaged(&DynamicImage::ImageLumaA8(gray), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 200, 200, 170], [200, 200, 200, 170]].concat());
}
#[test]
fn filtering_keeps_the_color_of_the_opaque_pixels() {
for f in [FilterType::Triangle, FilterType::CatmullRom, FilterType::Lanczos3] {
let out = resized(half_clear(), 2, 1, Resample::Filter(f)).into_rgba8();
for x in 0..2 {
let p = out.get_pixel(x, 0).0;
assert!(p[3] == 0 || close(p, [200, 30, 30]), "{f:?} pixel {x}: {p:?}");
}
}
}
#[test]
fn fitted_keeps_proportions() {
let img = DynamicImage::ImageRgba8(RgbaImage::new(400, 100));
let out = fitted(img, 64, 64, Resample::Average);
assert_eq!((out.width(), out.height()), (64, 16));
}
#[test]
fn opaque_and_alpha_free_images_scale_as_image_scales_them() {
let rgb = DynamicImage::ImageRgb8(image::RgbImage::from_fn(5, 3, |x, y| image::Rgb([x as u8 * 40, y as u8 * 60, 7])));
let ours = resized(rgb.clone(), 2, 2, Resample::Filter(FilterType::Triangle));
assert_eq!(ours, rgb.resize_exact(2, 2, FilterType::Triangle));
let opaque = DynamicImage::ImageRgba8(rgb.to_rgba8());
assert_eq!(resized(opaque.clone(), 2, 2, Resample::Average), opaque.thumbnail_exact(2, 2));
}
#[test]
fn a_wholly_clear_result_is_transparent_black() {
let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 0])));
assert_eq!(resized(img, 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0, [0, 0, 0, 0]);
}
#[test]
fn premultiply_and_unpremultiply_scale_beside_a_separate_alpha() {
// Two pixels of inks, the second clear: averaged, the first one's inks remain.
let mut px = vec![40, 80, 120, 160, 0, 0, 0, 0];
premultiply(&mut px, &[255, 0]);
let img = RgbaImage::from_raw(2, 1, px).unwrap();
let mut out = image::imageops::thumbnail(&img, 1, 1).into_raw();
let alpha = image::imageops::thumbnail(&image::GrayImage::from_raw(2, 1, vec![255, 0]).unwrap(), 1, 1).into_raw();
unpremultiply(&mut out, &alpha);
let want = [40, 80, 120, 160];
assert!(out.iter().zip(want).all(|(&c, w)| times_alpha(c, alpha[0]).abs_diff(times_alpha(w, alpha[0])) <= 1), "{out:?} {alpha:?}");
}
}
+19
View File
@@ -144,6 +144,25 @@ impl Selection {
self.key = None;
}
}
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
let ids: HashSet<NodeId> = ids.into_iter().collect();
if ids.is_empty() {
return;
}
self.target = None;
self.slices.clear();
self.symbol_part = None;
self.on_path_member = None;
self.objects.retain(|x| !ids.contains(x));
for id in &ids {
self.anchors.remove(id);
self.segments.remove(id);
}
if self.key.is_some_and(|k| ids.contains(&k)) {
self.key = None;
}
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
+29
View File
@@ -16,6 +16,35 @@ fn basic_ops() {
assert!(s.is_empty());
}
#[test]
fn remove_all_does_what_removing_each_does() {
let mut s = Selection::default();
for i in 1..=6 {
s.add(NodeId(i));
}
for i in [2, 4, 5] {
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
}
s.key = Some(NodeId(4));
s.target = Some(NodeId(3));
s.slices = vec![NodeId(9)];
s.guides = vec![NodeId(10)];
s.on_path_member = Some(NodeId(11));
let mut one_by_one = s.clone();
for id in [NodeId(4), NodeId(1), NodeId(4), NodeId(7)] {
one_by_one.remove(id);
}
let mut all = s.clone();
all.remove_all([NodeId(4), NodeId(1), NodeId(4), NodeId(7)]);
assert_eq!(all, one_by_one);
assert_eq!(all.objects, [NodeId(2), NodeId(3), NodeId(5), NodeId(6)]);
// Removing nothing leaves the selection as it was.
let mut none = s.clone();
none.remove_all([]);
assert_eq!(none, s);
}
#[test]
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
+428
View File
@@ -0,0 +1,428 @@
//! Every object a document stores, wherever it is kept: in the layers, in opacity-mask art, and in
//! the art of symbols, graph designs and pattern swatches. [`Document::node`] finds objects in the
//! layer tree only; the lookups here find the others by their ids too, which
//! [`Document::fix_next_id`] keeps unique across all of them.
use std::collections::HashSet;
use std::sync::Arc;
use super::limits::MAX_NEXT_ID;
use super::{Document, Node, NodeId};
/// The art a stored object belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StoredRoot {
/// Layer `index` of [`Document::layers`].
Layer(usize),
/// Symbol `index` of [`Document::symbols`].
Symbol(usize),
/// Graph design `index` of [`Document::graph_designs`].
GraphDesign(usize),
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
Pattern { pattern: usize, art: usize },
/// Root `index` of [`Document::mounted_art`].
Mounted(usize),
}
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
/// to (the innermost one when masks hold masks).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StoredPlace {
pub root: StoredRoot,
pub mask_of: Option<NodeId>,
}
impl StoredPlace {
/// Is the object in the layer tree itself, where [`Document::node`] finds it and the canvas
/// draws it as itself?
pub fn in_layers(self) -> bool {
matches!(self.root, StoredRoot::Layer(_)) && self.mask_of.is_none()
}
}
/// One step down from a node: to its child at an index, or to its opacity-mask art.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Child(usize),
Mask,
}
/// `n` and everything below it with its place, the opacity-mask art right after the object it
/// masks, then the children.
fn visit<'a>(n: &'a Arc<Node>, place: StoredPlace, f: &mut dyn FnMut(&'a Arc<Node>, StoredPlace)) {
f(n, place);
if let Some(m) = &n.extras().mask {
visit(&m.art, StoredPlace { mask_of: Some(n.id), ..place }, f);
}
for c in n.children().into_iter().flatten() {
visit(c, place, f);
}
}
/// The steps from `n` to the first node in [`visit`] order with id `id`, and the object whose mask
/// holds it last on the way.
fn find(n: &Node, id: NodeId, steps: &mut Vec<Step>, mask_of: &mut Option<NodeId>) -> bool {
if n.id == id {
return true;
}
if let Some(m) = &n.extras().mask {
steps.push(Step::Mask);
let before = *mask_of;
*mask_of = Some(n.id);
if find(&m.art, id, steps, mask_of) {
return true;
}
*mask_of = before;
steps.pop();
}
for (i, c) in n.children().into_iter().flatten().enumerate() {
steps.push(Step::Child(i));
if find(c, id, steps, mask_of) {
return true;
}
steps.pop();
}
false
}
/// The node `steps` below `n`.
fn at<'a>(mut n: &'a Arc<Node>, steps: &[Step]) -> Option<&'a Arc<Node>> {
for s in steps {
n = match s {
Step::Mask => &n.extras().mask.as_ref()?.art,
Step::Child(i) => n.children()?.get(*i)?,
};
}
Some(n)
}
/// The node `steps` below `n` to change, the nodes on the way copied when shared.
fn at_mut<'a>(mut n: &'a mut Arc<Node>, steps: &[Step]) -> Option<&'a mut Node> {
for s in steps {
let node = Arc::make_mut(n);
n = match s {
Step::Mask => &mut node.extras_if_any()?.mask.as_mut()?.art,
Step::Child(i) => node.children_mut()?.get_mut(*i)?,
};
}
Some(Arc::make_mut(n))
}
/// Gives every node from `n` down that `fresh` names a new id from `next`, counting nodes in
/// [`visit`] order from `*count`; only the nodes on the way to one are copied. Each part below is
/// renumbered through a second handle, so a new pointer marks a change.
fn renumber(n: &mut Arc<Node>, fresh: &HashSet<usize>, count: &mut usize, next: &mut u64) {
let own = fresh.contains(count);
*count += 1;
let mask = n.extras().mask.as_ref().and_then(|m| {
let mut art = Arc::clone(&m.art);
renumber(&mut art, fresh, count, next);
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
});
let mut slots = vec![];
// Children's new ids by their old ones, for an Objects on Path group, which names its path and
// members by id. An id another child keeps still names that child.
let mut renamed = std::collections::HashMap::new();
let mut kept = HashSet::new();
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut new = Arc::clone(c);
renumber(&mut new, fresh, count, next);
if new.id == c.id {
kept.insert(c.id);
} else {
renamed.insert(c.id, new.id);
}
if !Arc::ptr_eq(&new, c) {
slots.push((i, new));
}
}
renamed.retain(|old, _| !kept.contains(old));
if !own && mask.is_none() && slots.is_empty() {
return;
}
let node = Arc::make_mut(n);
if own {
node.id = NodeId(*next);
*next += 1;
}
if let (Some(art), Some(m)) = (mask, node.extras_if_any().and_then(|e| e.mask.as_mut())) {
m.art = art;
}
if let Some(children) = node.children_mut() {
for (i, c) in slots {
if let Some(slot) = children.get_mut(i) {
*slot = c;
}
}
}
if !renamed.is_empty()
&& let Some(on_path) = node.extras_if_any().and_then(|e| e.objects_on_path.as_mut())
{
on_path.rename(&renamed);
}
}
impl Document {
/// The roots of the art kept outside the layers, each with its [`StoredRoot`].
fn definition_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
let symbols = self.symbols.iter().enumerate().map(|(i, s)| (&s.art, StoredRoot::Symbol(i)));
let designs = self.graph_designs.iter().enumerate().map(|(i, g)| (&g.art, StoredRoot::GraphDesign(i)));
let patterns = self
.patterns
.iter()
.enumerate()
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
let mounted = self.mounted_art.iter().enumerate().map(|(i, (n, _))| (n, StoredRoot::Mounted(i)));
symbols.chain(designs).chain(patterns).chain(mounted)
}
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns,
/// then [`Document::mounted_art`].
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
}
/// The root `root` names, to change.
fn stored_root_mut(&mut self, root: StoredRoot) -> Option<&mut Arc<Node>> {
match root {
StoredRoot::Layer(i) => self.layers.get_mut(i),
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
StoredRoot::Mounted(i) => self.mounted_art.get_mut(i).map(|(n, _)| n),
}
}
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
/// once each, never the copies instances and tiles draw), then [`Document::mounted_art`].
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
self.visit_stored_arcs(|n, place| f(n, place));
}
/// [`Self::visit_stored`] with each object's shared handle, which keeps its identity from one
/// look to the next while the object is unchanged (for caches such as thumbnails).
pub fn visit_stored_arcs<'a>(&'a self, mut f: impl FnMut(&'a Arc<Node>, StoredPlace)) {
for (root, r) in self.stored_roots() {
visit(root, StoredPlace { root: r, mask_of: None }, &mut f);
}
}
/// Where object `id` is stored: the root, and the steps from it.
fn stored_path(&self, id: NodeId) -> Option<(StoredPlace, Vec<Step>)> {
if let Some(path) = self.index_path(id) {
let (first, rest) = path.split_first()?;
return Some((StoredPlace { root: StoredRoot::Layer(*first), mask_of: None }, rest.iter().map(|i| Step::Child(*i)).collect()));
}
// Not in the layer tree: in mask art (in the layers too) or in a definition's art.
for (root, r) in self.stored_roots() {
let (mut steps, mut mask_of) = (vec![], None);
if find(root, id, &mut steps, &mut mask_of) {
return Some((StoredPlace { root: r, mask_of }, steps));
}
}
None
}
/// Stored object `id` (see [`Self::visit_stored`]) with its place: one in the layer tree as
/// [`Self::node`] finds it, else the first in visiting order.
pub fn stored_node(&self, id: NodeId) -> Option<(&Arc<Node>, StoredPlace)> {
let (place, steps) = self.stored_path(id)?;
let root = self.stored_roots().find(|(_, r)| *r == place.root)?.0;
Some((at(root, &steps)?, place))
}
/// [`Self::stored_node`] to change; the nodes on the way are copied when shared.
pub fn stored_node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
let (place, steps) = self.stored_path(id)?;
at_mut(self.stored_root_mut(place.root)?, &steps)
}
/// Gives the objects outside the layer tree (in opacity-mask art and in the art of symbols,
/// graph designs and patterns) whose id is 0, past the id range, or already taken by an object
/// visited before them (the layer tree's own objects first) a new id, so every stored object
/// can be named by its id. Returns how many changed; the id counter then stands above them.
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
self.renumber_duplicates_in(|_| true)
}
/// Raises the id counter above the ids of [`Document::mounted_art`]'s objects, then gives those
/// objects whose id is 0, past the id range, or already taken by an object visited before them
/// (every other stored object first) a new id, as [`Self::renumber_stored_duplicates`] gives
/// them. Returns how many changed.
pub fn number_mounted_art(&mut self) -> usize {
let mut max = 0;
for (i, (root, _)) in self.mounted_art.iter().enumerate() {
visit(root, StoredPlace { root: StoredRoot::Mounted(i), mask_of: None }, &mut |n, _| {
if n.id.0 < MAX_NEXT_ID {
max = max.max(n.id.0);
}
});
}
self.raise_next_id(max.saturating_add(1));
self.renumber_duplicates_in(|r| matches!(r, StoredRoot::Mounted(_)))
}
/// [`Self::renumber_stored_duplicates`] for the roots `pick` holds for only; the objects of the
/// others still count as taken.
fn renumber_duplicates_in(&mut self, pick: impl Fn(StoredRoot) -> bool) -> usize {
let mut seen: HashSet<NodeId> = HashSet::new();
for l in &self.layers {
l.walk(&mut |n| {
seen.insert(n.id);
});
}
self.slices.iter().for_each(|s| {
seen.insert(s.id);
});
// Per root, the visiting indices of the nodes that take a new id.
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
for (root, r) in self.stored_roots() {
let (mut i, mut here, take) = (0, HashSet::new(), pick(r));
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) && take {
here.insert(i);
}
i += 1;
});
if !here.is_empty() {
fresh.push((r, here));
}
}
let total = fresh.iter().map(|(_, f)| f.len()).sum();
if total == 0 {
return 0;
}
// No id left to give: the objects keep theirs rather than share one given out later.
if self.peek_next_id().saturating_add(total as u64) > MAX_NEXT_ID {
return 0;
}
let mut next = self.peek_next_id();
for (r, f) in fresh {
if let Some(root) = self.stored_root_mut(r) {
renumber(root, &f, &mut 0, &mut next);
}
}
self.raise_next_id(next);
total
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{GraphDesign, OpacityMask, PatternDef, Symbol};
use vectorcraft_geom::Rect;
fn rect(id: u64) -> Node {
Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), crate::Appearance::default_art())
}
fn masked(id: u64, art: Node) -> Node {
rect(id).with_mask(Some(Box::new(OpacityMask::new(art, true))))
}
/// A document with object 10 in its layer, mask art 11 on it, and one object in a symbol,
/// a graph design and a pattern (ids `defs`).
fn doc(defs: [u64; 3]) -> Document {
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, masked(10, rect(11))).unwrap();
d.symbols.push(Symbol { name: "S".into(), art: Arc::new(rect(defs[0])), dynamic: false });
d.graph_designs.push(GraphDesign { name: "G".into(), art: Arc::new(rect(defs[1])) });
d.patterns.push(PatternDef::new("P", vec![Arc::new(rect(defs[2]))]));
d.raise_next_id(20);
d
}
#[test]
fn stored_objects_are_found_in_every_art() {
let d = doc([12, 13, 14]);
let place = |id: u64| d.stored_node(NodeId(id)).map(|(n, p)| (n.id.0, p));
assert!(place(10).unwrap().1.in_layers());
assert_eq!(place(11).unwrap().1, StoredPlace { root: StoredRoot::Layer(0), mask_of: Some(NodeId(10)) });
assert_eq!(place(12).unwrap().1.root, StoredRoot::Symbol(0));
assert_eq!(place(13).unwrap().1.root, StoredRoot::GraphDesign(0));
assert_eq!(place(14).unwrap().1.root, StoredRoot::Pattern { pattern: 0, art: 0 });
assert!(d.node(NodeId(11)).is_none() && d.node(NodeId(12)).is_none(), "the layer lookup stays the layer tree's");
assert!(d.stored_node(NodeId(99)).is_none());
let mut seen = vec![];
d.visit_stored(|n, _| seen.push(n.id.0));
assert_eq!(seen, [d.layers[0].id.0, 10, 11, 12, 13, 14]);
}
#[test]
fn stored_objects_change_by_id() {
let mut d = doc([12, 13, 14]);
let before = d.clone();
d.stored_node_mut(NodeId(13)).unwrap().name = Some("changed".into());
assert_eq!(d.graph_designs[0].art.name.as_deref(), Some("changed"));
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art), "other art is not copied");
assert_eq!(before.graph_designs[0].art.name, None, "the earlier document is unchanged");
d.stored_node_mut(NodeId(11)).unwrap().name = Some("mask".into());
assert_eq!(d.stored_node(NodeId(11)).unwrap().0.name.as_deref(), Some("mask"));
}
#[test]
fn fix_next_id_gives_nested_duplicates_new_ids() {
// The symbol's object repeats the layer's object, the design's has no id, and the pattern's
// repeats the mask art's.
let mut d = doc([10, 0, 11]);
d.next_id = 1;
d.fix_next_id();
let mut ids = vec![];
d.visit_stored(|n, _| ids.push(n.id.0));
let unique: HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
assert!(!ids.contains(&0));
assert_eq!(&ids[..3], &[d.layers[0].id.0, 10, 11], "the layer tree and the first mask art keep theirs");
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
// Ids already unique are kept, and a second pass changes nothing.
let again = d.clone();
assert_eq!(d.renumber_stored_duplicates(), 0);
assert_eq!(d, again);
}
/// Mounted art is found and changed by id after the other stored art, and numbering it gives
/// its objects that repeat another stored object's id, or have none, new ids above the counter,
/// leaving every other object's id and its own unique ones as they are.
#[test]
fn mounted_art_is_found_and_numbered_after_the_rest() {
let mut d = doc([12, 13, 14]);
let owner = serde_json::json!({ "kind": "brush" });
d.mounted_art = vec![(Arc::new(masked(10, rect(0))), owner.clone()), (Arc::new(rect(15)), owner)];
assert_eq!(d.stored_node(NodeId(15)).map(|(_, p)| p.root), Some(StoredRoot::Mounted(1)));
let before = d.clone();
assert_eq!(d.number_mounted_art(), 2);
let mut ids = vec![];
d.visit_stored(|n, _| ids.push(n.id.0));
let unique: HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
assert_eq!(&ids[..6], &[d.layers[0].id.0, 10, 11, 12, 13, 14], "the other art keeps its ids");
assert_eq!(ids[8], 15, "a unique id is kept");
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art) && Arc::ptr_eq(&d.mounted_art[1].0, &before.mounted_art[1].0));
d.stored_node_mut(NodeId(15)).unwrap().name = Some("changed".into());
assert_eq!(d.mounted_art[1].0.name.as_deref(), Some("changed"));
assert_eq!(d.number_mounted_art(), 0, "a second pass changes nothing");
}
#[test]
fn renumbered_objects_on_path_keep_their_path_and_members() {
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
// member has no id.
let mut d = doc([12, 13, 14]);
let (path, member) = (rect(10), rect(0));
let rec = crate::objects_on_path::ObjectsOnPath::new(path.id, &[&member], crate::objects_on_path::CENTER, 0.0);
let mut g = Node::new(NodeId(15), crate::NodeKind::Group { children: vec![Arc::new(path), Arc::new(member)], clip: false });
g.extras_mut().objects_on_path = Some(Box::new(rec));
d.symbols[0].art = Arc::new(g);
d.fix_next_id();
let art = &d.symbols[0].art;
let kids: Vec<NodeId> = art.children().unwrap().iter().map(|c| c.id).collect();
assert!(kids.iter().all(|id| id.0 != 10 && id.0 != 0), "{kids:?}");
let on_path = art.extras().objects_on_path.as_ref().unwrap();
assert_eq!(on_path.path, kids[0]);
assert_eq!(on_path.members.iter().map(|m| m.id).collect::<Vec<_>>(), [kids[1]]);
}
}
+94 -8
View File
@@ -206,11 +206,13 @@ impl Document {
impl Document {
/// Visit every paint held by the art (opacity masks included), symbol definitions, pattern
/// tiles and graphic styles (fills, strokes and text runs), and the colour of every
/// gradient-mesh point as a solid paint.
/// gradient-mesh point as a solid paint. A graph's default black legend fill is left out.
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
let default_legend = default_legend_fill(m);
graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p));
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -388,7 +390,9 @@ pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
let g = n.extras().graph.as_deref();
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke]))
let l = g.map(|g| &g.label_styles);
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten())
}
/// Mutable [`graph_paints`] of graph `g`, in the same order.
@@ -396,7 +400,23 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
let l = &mut g.label_styles;
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
series.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten();
series
.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
}
/// The place in [`graph_paints`] of the legend fill graph `n` keeps when it is the default black of a graph that picks
/// its legend labels' fill ([`crate::graph::GraphSpec::picks_legend_fill`]). Other graphs draw the kept fill as it is,
/// so it is visited and mapped.
fn default_legend_fill(n: &Node) -> Option<usize> {
let g = n.extras().graph.as_deref()?;
let l = &g.label_styles;
if l.legend.is_none() || !g.picks_legend_fill() {
return None;
}
let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum();
Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some())))
}
/// Mutable [`node_paints`], in the same order.
@@ -441,11 +461,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
// The default black legend fill, which is not the legend labels' own, stays black.
let default_legend = default_legend_fill(n);
let graph: Vec<(usize, Paint)> =
graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
// A legend fill of the labels' own stays theirs when the change makes it black.
spec.label_styles.mark_own_legend_fill();
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
@@ -689,6 +714,10 @@ mod tests {
series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }],
label_styles: crate::graph::LabelStyles {
legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }),
values_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() },
..Default::default()
}),
..Default::default()
},
..Default::default()
@@ -696,20 +725,77 @@ mod tests {
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == red));
assert_eq!(seen, 4, "the fill and the graph's series fill, series stroke and legend fill");
assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row");
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
assert_eq!(d.map_solid_paints(&mut to_blue), 4);
assert_eq!(d.map_solid_paints(&mut to_blue), 5);
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
let legend = g.label_styles.legend.unwrap();
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand")));
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
assert_eq!(d.map_paints(&mut cleared), 4, "the fill and the graph's three");
assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four");
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn a_legend_fill_mapped_to_black_stays_the_labels_own() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() },
..Default::default()
};
assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark");
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut to_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| {
s.as_deref() == Some("Brand") && {
*c = Color::BLACK;
*s = None;
true
}
};
assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK));
assert!(styles.legend_fill_set, "the black fill is still the labels' own");
}
#[test]
fn the_default_black_legend_fill_is_left_as_it_is() {
use crate::graph::GraphKind;
// Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black.
for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] {
let (mut d, a, _) = doc();
let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() };
let spec = crate::graph::GraphSpec {
kind,
legend: true,
pie_legend_in_wedges: in_wedges,
series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }],
label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() },
..Default::default()
};
let blacks = |d: &Document| {
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK)));
seen
};
let before = blacks(&d);
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let want = if picks { 2 } else { 3 };
assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited");
let mut link_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none();
assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") };
assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill");
assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black"));
}
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
+223 -49
View File
@@ -10,9 +10,19 @@
//! The cells are sized along the symbol's own axes, and the instance's rotation, shear, reflection
//! and position then apply to them.
//!
//! The guides are stored as fractions (0..1) of the symbol's natural size, measured from the left
//! and top edges and from the right and bottom edges, so they survive resizing the art. Stored
//! under [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry.
//! A guide may lie outside the art, and the instance still scales, by the slices the art falls in
//! ([the help page](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf),
//! Use 9-slice scaling section). VectorCraft's own rules for that: a guide past an edge of the art
//! cuts the art at that edge, so the outer cell on its side holds no art; with both guides of an
//! axis past opposite edges the art scales as a whole along it; with both past the same edge the
//! art lies in the outer cell at the other edge and keeps its size, from that edge of the instance,
//! or shrinks to the instance's width or height when the instance is smaller than the art.
//!
//! The guides are stored as fractions of the symbol's natural size, measured from the left and top
//! edges and from the right and bottom edges, so they survive resizing the art. A fraction below 0
//! puts a guide past its own edge, and one above 1 past the opposite edge; each lies within
//! ±[`MAX_GUIDE_FRACTION`], and the two guides of an axis keep their order. Stored under
//! [`SYMBOL_NINE_SLICE`] keyed by symbol name; symbols without 9-slice have no entry.
//!
//! [`NineSliceMap`] places such an instance's art for the canvas, bounds, Break Link, Expand and
//! the exporters ([`Document::place_symbol_art`]).
@@ -49,11 +59,16 @@ impl Default for SymbolNineSlice {
}
}
/// The farthest a guide may lie from its edge, as a fraction of the symbol's width or height, in
/// either direction (VectorCraft's own rule).
pub const MAX_GUIDE_FRACTION: f64 = 16.0;
impl SymbolNineSlice {
/// Guides from `[left, top, right, bottom]`; `None` unless each is finite, within 0..1, and the
/// two on each axis leave a gap between them.
/// Guides from `[left, top, right, bottom]`; `None` unless each is finite and within
/// ±[`MAX_GUIDE_FRACTION`], and the two on each axis leave a gap between them
/// (`left + right < 1`, `top + bottom < 1`).
pub fn new(left: f64, top: f64, right: f64, bottom: f64) -> Option<Self> {
let ok = |v: f64| v.is_finite() && (0.0..=1.0).contains(&v);
let ok = |v: f64| v.is_finite() && (-MAX_GUIDE_FRACTION..=MAX_GUIDE_FRACTION).contains(&v);
(ok(left) && ok(top) && ok(right) && ok(bottom) && left + right < 1.0 && top + bottom < 1.0).then_some(Self { left, top, right, bottom })
}
@@ -102,7 +117,8 @@ pub struct EditedNineSlice {
}
impl EditedNineSlice {
/// Guide `g` as a line across the art's box, from one edge to the other, in the document.
/// Guide `g` as a line across the art's box, from one edge to the other, in the document. A
/// guide outside the art spans the art's height or width beside it.
pub fn line(&self, g: NineSliceGuide) -> (Point, Point) {
let (b, s) = (self.art, self.guides);
let (a, c) = match g {
@@ -126,14 +142,17 @@ impl EditedNineSlice {
})
}
/// The guides with guide `g` moved across its axis to document point `p`. The guide stays
/// within the art's box, and [`MIN_CENTER_BAND`] short of the opposite guide, or where it is
/// when the guides are already closer than that. A point that is not finite leaves the guides
/// as they are.
/// The guides with guide `g` moved across its axis to document point `p`. The guide may pass
/// either edge of the art, up to [`MAX_GUIDE_FRACTION`] from its own edge, and stops
/// [`MIN_CENTER_BAND`] short of the opposite guide, or where it is when the guides are already
/// closer than that. A point that is not finite, or that gives a fraction that is not, leaves
/// the guides as they are.
pub fn moved(&self, g: NineSliceGuide, p: Point) -> SymbolNineSlice {
let (b, mut out) = (self.art, self.guides);
let q = self.to_doc.inverse() * p;
let fit = |v: f64, other: f64, now: f64| if v.is_finite() { v.clamp(0.0, (1.0 - other - MIN_CENTER_BAND).max(now)) } else { now };
let fit = |v: f64, other: f64, now: f64| {
if v.is_finite() { v.clamp(-MAX_GUIDE_FRACTION, (1.0 - other - MIN_CENTER_BAND).min(MAX_GUIDE_FRACTION).max(now)) } else { now }
};
match g {
NineSliceGuide::Left => out.left = fit((q.x - b.x0) / b.width(), out.right, out.left),
NineSliceGuide::Right => out.right = fit((b.x1 - q.x) / b.width(), out.left, out.right),
@@ -181,20 +200,27 @@ const MAX_SLICE_DEPTH: u32 = 64;
/// One axis of a 9-slice map: the three cells between the cuts and where each one goes.
#[derive(Clone, Copy, Debug, PartialEq)]
struct AxisMap {
/// The cuts in the art at its natural size: its start, the two guides, its end.
/// The cuts in the art at its natural size: its start, the two guides, its end. A guide
/// outside the art cuts it at the nearer end, so a cell can be empty.
src: [f64; 4],
/// Where the cuts go. The outer cells keep their length unless the scaled length is shorter
/// than both together; then both shrink in proportion and the middle cell is empty.
/// than both together; then both shrink in proportion and the middle cell is empty. An empty
/// cell's start is where the cell before it ends, so the map stays continuous.
dst: [f64; 4],
}
impl AxisMap {
/// The axis from `lo` to `hi` with guides `near` and `far` (fractions of its length in from
/// each end), scaled by `k` (above 0).
/// The axis from `lo` to `hi` (`lo < hi`) with guides `near` and `far` (fractions of its
/// length in from each end, `near + far < 1`; either may lie past an end), scaled by `k`
/// (above 0). With both guides past the far end the art keeps its length from the scaled
/// start, and with both past the near end it keeps its length up to the scaled end; when the
/// scaled length is shorter than the art, the art shrinks to the scaled length.
fn new(lo: f64, hi: f64, near: f64, far: f64, k: f64) -> Self {
let len = hi - lo;
let (a, b) = (near * len, far * len);
let src = [lo, lo + a, hi - b, hi];
let c1 = (lo + near * len).clamp(lo, hi);
let c2 = (hi - far * len).clamp(c1, hi);
let src = [lo, c1, c2, hi];
let (a, b) = (c1 - lo, hi - c2);
let (t0, t3) = (k * lo, k * hi);
let room = t3 - t0;
let (a, b) = if a + b <= room {
@@ -203,9 +229,15 @@ impl AxisMap {
let f = (room / (a + b)).max(0.0);
(a * f, b * f)
};
let t1 = t0 + a;
let t2 = (t3 - b).max(t1);
Self { src, dst: [t0, t1, t2, t3] }
let dst = if c2 > c1 {
let t1 = t0 + a;
[t0, t1, (t3 - b).max(t1), t3]
} else if a > 0.0 {
[t0, t0 + a, t0 + a, t3]
} else {
[t3 - b, t3 - b, t3 - b, t3]
};
Self { src, dst }
}
/// The cell `v` lies in; values outside the art belong to the outer cells.
@@ -279,10 +311,11 @@ pub struct NineSliceMap {
impl NineSliceMap {
/// The map for an instance placed by `xf` that shows art with natural-size transform
/// `natural` and geometric bounds `art` (in symbol space). `None` when the art or the
/// transform is degenerate, or when the instance is at its natural size on both axes (then
/// `xf` places the art as it is).
/// `natural` and geometric bounds `art` (in symbol space). `None` when the guides are not ones
/// [`SymbolNineSlice::new`] accepts, when the art or the transform is degenerate, or when the
/// instance is at its natural size on both axes (then `xf` places the art as it is).
pub fn new(guides: SymbolNineSlice, art: Rect, natural: Affine, xf: Affine) -> Option<Self> {
let guides = SymbolNineSlice::new(guides.left, guides.top, guides.right, guides.bottom)?;
let b = natural.transform_rect_bbox(art);
if ![b.x0, b.y0, b.x1, b.y1].into_iter().all(f64::is_finite) || b.width() <= 1e-9 || b.height() <= 1e-9 {
return None;
@@ -430,8 +463,13 @@ impl NineSliceMap {
///
/// Strokes keep their weight, as they do for any instance.
pub fn place(&self, art: &Node, doc: &Document) -> Node {
let boxes = doc.symbol_boxes().quick();
self.place_at(art, &boxes, 0)
self.place_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node {
self.place_at(art, boxes, 0)
}
/// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF):
@@ -447,16 +485,25 @@ impl NineSliceMap {
/// object drawn in clip groups counts one group plus a clip path and a copy for each cell its
/// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`.
pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 {
let boxes = doc.symbol_boxes().quick();
self.most_at(art, &boxes, 0)
self.most_placed_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 {
self.most_at(art, boxes, 0)
}
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
/// origin when it has no box. `None` when its box crosses a guide.
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
let boxes = doc.symbol_boxes().quick();
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
self.one_cell_with(n, &doc.symbol_boxes().quick())
}
/// [`Self::one_cell`] with the instances in `n` measured by `boxes`.
pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option<Affine> {
let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
return Some(self.cell_at(Point::ZERO));
};
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
@@ -468,6 +515,11 @@ impl NineSliceMap {
Self { clips: false, ..*self }.most_placed(art, doc)
}
/// This map placing without clip groups, as [`Self::place_unclipped`] does.
pub(crate) fn unclipped(&self) -> Self {
Self { clips: false, ..*self }
}
/// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`].
fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let whole = n.count_with_masks() as u64;
@@ -581,6 +633,8 @@ impl NineSliceMap {
/// `n`, whose box at the natural size is `b`, drawn in each cell it reaches: a clip group of
/// the cell around a copy placed by the cell's map, all in a group with `n`'s id. `n` placed
/// by `center` when it draws symbol art ([`draws_symbol_art`]), and in [`Self::place_unclipped`].
/// The clip groups and clip paths take the angle of the cell map that places them. The group
/// and each copy keep `n`'s box angle, turned by the map that places them.
///
/// The drop shadows, outer glows and blurs ([`PAINTED_EFFECTS`]) at the end of `n`'s own
/// effects, after its last other visible effect, go on that group with its opacity, blending
@@ -614,11 +668,15 @@ impl NineSliceMap {
area.transform(local);
let mut clip = Node::new(NodeId(0), NodeKind::Path { path: area, rule: FillRule::NonZero, live: None, clipping: true, guide: false });
clip.appearance = Appearance::default().into();
clip.bbox_angle = crate::orient::transformed_angle(0.0, local);
let copy = transformed(n, local * self.natural);
cells.push(Arc::new(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(copy)], clip: true })));
let mut cell = Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(copy)], clip: true });
cell.bbox_angle = crate::orient::transformed_angle(0.0, local);
cells.push(Arc::new(cell));
}
}
let mut out = Node::group(n.id, cells);
out.bbox_angle = crate::orient::transformed_angle(n.bbox_angle, center);
out.visible = n.visible;
out.locked = n.locked;
out.name = n.name.clone();
@@ -632,7 +690,7 @@ impl NineSliceMap {
}
/// `n` moved by `a`, its strokes at their own weight.
fn transformed(n: &Node, a: Affine) -> Node {
pub(crate) fn transformed(n: &Node, a: Affine) -> Node {
let mut out = n.clone();
out.transform(a, false);
out
@@ -726,10 +784,7 @@ impl Document {
/// `None` when the symbol has no guides or the instance is at its natural size. The guides cut
/// the art's box with the instances in it measured by their own art.
pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.symbol_nine_slice(name)?;
let sym = self.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?;
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
self.symbol_boxes().quick().slice_map(name, xf)
}
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
@@ -743,9 +798,10 @@ impl Document {
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
/// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]).
pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf) {
Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
@@ -756,8 +812,8 @@ impl Document {
pub fn edited_nine_slice(&self) -> Option<EditedNineSlice> {
let se = self.symbol_edit.as_ref()?;
let guides = self.symbol_nine_slice(&se.symbol)?;
let sym = self.symbols.iter().find(|s| s.name == se.symbol)?;
let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?;
let boxes = self.symbol_boxes().quick();
let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?;
let natural = self.symbol_natural_xf(&se.symbol);
let b = natural.transform_rect_bbox(art);
if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 {
@@ -772,8 +828,9 @@ impl Document {
/// [`Self::place_symbol_art`] for writers that do not apply clipping
/// ([`NineSliceMap::place_unclipped`]).
pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf).map(|m| m.unclipped()) {
Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
@@ -894,6 +951,113 @@ mod tests {
assert!(got.iter().all(|b| finite(*b)), "{got:?}");
}
/// Guides may lie outside the art, up to 16 times its size from their edge, as long as the
/// two on each axis keep their order; values that are not finite are refused.
#[test]
fn guides_outside_the_art_are_accepted_in_order_and_within_the_limit() {
let ok = |l, t, r, b| SymbolNineSlice::new(l, t, r, b).is_some();
assert!(ok(-0.25, 0.25, 0.25, 0.25));
assert!(ok(1.25, 0.25, -0.5, 0.25), "both past the right edge");
assert!(ok(0.25, -16.0, 0.25, 16.0) && ok(-16.0, 0.25, -16.0, 0.25));
assert!(!ok(-16.5, 0.25, 0.25, 0.25) && !ok(0.25, 0.25, 0.25, 17.0));
assert!(!ok(f64::NAN, 0.25, 0.25, 0.25) && !ok(0.25, f64::INFINITY, 0.25, 0.25) && !ok(0.25, 0.25, f64::NEG_INFINITY, 0.25));
assert!(!ok(1.2, 0.25, -0.2, 0.25), "the left guide on the right one");
assert!(!ok(0.25, 0.6, 0.25, 0.6), "crossed");
let g = SymbolNineSlice::from_value(&json!([-0.25, 1.5, 0.5, -1.0])).unwrap();
assert_eq!(g, SymbolNineSlice { left: -0.25, top: 1.5, right: 0.5, bottom: -1.0 });
assert_eq!(SymbolNineSlice::from_value(&g.to_value()), Some(g));
assert!(SymbolNineSlice::from_value(&json!([-0.25, 0.1, 1.5])).is_none());
assert!(SymbolNineSlice::from_value(&json!([-20.0, 0.1, 0.5, 0.1])).is_none());
// Guides built without the check are not used to place art.
let bad = SymbolNineSlice { left: f64::NAN, ..SymbolNineSlice::default() };
assert!(NineSliceMap::new(bad, Rect::new(0.0, 0.0, 100.0, 100.0), Affine::IDENTITY, Affine::scale(2.0)).is_none());
// Art without width or height has no map, whatever the guides.
let out = SymbolNineSlice::new(-0.25, 1.25, 0.25, -0.5).unwrap();
for art in [Rect::new(0.0, 0.0, 0.0, 100.0), Rect::new(0.0, 0.0, 100.0, 0.0)] {
assert!(NineSliceMap::new(out, art, Affine::IDENTITY, Affine::scale(2.0)).is_none(), "{art:?}");
}
}
/// At 200 × 150, a left guide 25 % outside the art leaves the art in the center and right
/// columns: the left column holds no art, the center one (0..75) stretches to 0..175 and the
/// right one keeps its 25. Both guides outside on opposite sides scale the art as a whole on
/// that axis; both past the same side keep the art at its size in the outer cell at the other
/// side, from that side of the instance.
#[test]
fn art_scales_by_the_cells_it_falls_in_when_guides_lie_outside_it() {
let xf = Affine::scale_non_uniform(2.0, 1.5);
let d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25));
let got = boxes(&d, xf);
let k = 175.0 / 75.0;
assert!(near(got[0], Rect::new(0.0, 0.0, 200.0, 150.0)), "{:?}", got[0]);
assert!(near(got[1], Rect::new(0.0, 0.0, 10.0 * k, 10.0)), "the top-left square stretches: {:?}", got[1]);
assert!(near(got[2], Rect::new(190.0, 0.0, 200.0, 10.0)), "the top-right corner keeps its size: {:?}", got[2]);
assert!(near(got[5], Rect::new(45.0 * k, 65.0, 55.0 * k, 85.0)), "{:?}", got[5]);
// Both vertical guides outside, on opposite sides: the art scales as a whole across.
let d = markers(SymbolNineSlice::new(-0.25, 0.25, -1.0, 0.25));
let got = boxes(&d, xf);
assert!(near(got[1], Rect::new(0.0, 0.0, 20.0, 10.0)) && near(got[2], Rect::new(180.0, 0.0, 200.0, 10.0)), "{got:?}");
assert!(near(got[5], Rect::new(90.0, 65.0, 110.0, 85.0)), "{:?}", got[5]);
// Both past the right edge: the art keeps its width from the instance's left edge.
let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25));
let got = boxes(&d, xf);
assert!(near(got[0], Rect::new(0.0, 0.0, 100.0, 150.0)), "{:?}", got[0]);
assert!(near(got[2], Rect::new(90.0, 0.0, 100.0, 10.0)) && near(got[5], Rect::new(45.0, 65.0, 55.0, 85.0)), "{got:?}");
// Both past the left edge: the art keeps its width up to the instance's right edge.
let d = markers(SymbolNineSlice::new(-0.5, 0.25, 1.2, 0.25));
let got = boxes(&d, xf);
assert!(near(got[0], Rect::new(100.0, 0.0, 200.0, 150.0)), "{:?}", got[0]);
assert!(near(got[1], Rect::new(100.0, 0.0, 110.0, 10.0)), "{:?}", got[1]);
// The same rules apply to rows: both horizontal guides above the art keep its height up to
// the instance's bottom edge.
let d = markers(SymbolNineSlice::new(0.25, -0.5, 0.25, 1.2));
let got = boxes(&d, xf);
assert!(near(got[0], Rect::new(0.0, 50.0, 200.0, 150.0)), "{:?}", got[0]);
assert!(near(got[3], Rect::new(0.0, 140.0, 10.0, 150.0)), "{:?}", got[3]);
// Smaller than the art, an art-covered outer cell shrinks in proportion.
let d = markers(SymbolNineSlice::new(1.2, 0.25, -0.5, 0.25));
let got = boxes(&d, Affine::scale_non_uniform(0.5, 1.5));
assert!(near(got[0], Rect::new(0.0, 0.0, 50.0, 150.0)) && near(got[1], Rect::new(0.0, 0.0, 5.0, 10.0)), "{got:?}");
}
/// With guides outside the art, the map stays finite, never runs backward, and does not jump
/// at the art's edges or at the guides; objects keep to the cells that hold art.
#[test]
fn the_map_with_guides_outside_the_art_is_continuous_and_monotone() {
let cases = [(-0.25, 0.25), (-0.25, -1.0), (1.2, -0.5), (-0.5, 1.2), (0.0, -16.0), (-16.0, 16.0), (0.25, 0.25)];
for (l, r) in cases {
let d = markers(SymbolNineSlice::new(l, 0.25, r, 0.25));
for sx in [0.3, 2.0, 1e6] {
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(sx, 1.5)).unwrap();
let at = |x: f64| m.map_point(Point::new(x, 40.0)).x;
let mut last = f64::NEG_INFINITY;
for i in 0..=1200 {
let x = -10.0 + i as f64 * 0.1;
let v = at(x);
assert!(v.is_finite() && v >= last - 1e-12 * last.abs().max(1.0), "{l} {r} {sx}: {x} → {v} after {last}");
last = v;
}
for edge in [0.0, 75.0, 100.0] {
let jump = (at(edge + 1e-9) - at(edge - 1e-9)).abs();
assert!(jump < 1e-6 * sx.max(1.0), "{l} {r} {sx}: a jump of {jump} at {edge}");
}
}
}
// A gradient bar across the art with the left guide outside is drawn in the two columns
// that hold art, not three.
let mut d = markers(SymbolNineSlice::new(-0.25, 0.25, 0.25, 0.25));
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let bar = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 40.0, 100.0, 60.0)), Appearance::basic(gradient, Paint::None, 0.0));
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap();
assert_eq!(m.place(&bar, &d).children().map(Vec::len), Some(2));
assert_eq!(m.most_placed(&bar, &d), 7);
// With both guides outside on opposite sides, the bar lies in one cell and is moved whole.
let d = markers(SymbolNineSlice::new(-0.25, 0.25, -0.25, 0.25));
let m = d.symbol_slice_map("S", Affine::scale_non_uniform(2.0, 1.5)).unwrap();
assert!(matches!(m.place(&bar, &d).kind, NodeKind::Path { .. }));
assert_eq!(m.most_placed(&bar, &d), 1);
}
/// A negative scale reflects the sized cells; a rotation turns them, the corners keeping
/// their size along the symbol's own axes.
#[test]
@@ -1456,27 +1620,37 @@ mod tests {
assert!(d.edited_nine_slice().is_none());
}
/// Moving a guide changes that guide alone, follows the pointer across its axis only, stays
/// within the art's box and stops short of the opposite guide.
/// Moving a guide changes that guide alone, follows the pointer across its axis only, may pass
/// either edge of the art up to [`MAX_GUIDE_FRACTION`], and stops short of the opposite guide.
#[test]
fn a_moved_guide_stays_in_the_art_and_short_of_the_opposite_guide() {
fn a_moved_guide_passes_the_arts_edges_and_stops_short_of_the_opposite_guide() {
let xf = Affine::translate((10.0, 20.0)) * Affine::scale(2.0);
let e = editing(Some(SymbolNineSlice::default()), xf).edited_nine_slice().unwrap();
let q = SymbolNineSlice { left: 0.25, top: 0.25, right: 0.25, bottom: 0.25 };
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(30.0, 999.0)), SymbolNineSlice { left: 0.1, ..q });
assert_eq!(e.moved(NineSliceGuide::Bottom, Point::new(-50.0, 180.0)), SymbolNineSlice { bottom: 0.2, ..q });
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: 0.0, ..q });
assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: 0.0, ..q });
// Past the art's near edges: the art spans 10..210 across and 20..220 down.
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-40.0, 50.0)), SymbolNineSlice { left: -0.25, ..q });
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, -500.0)), SymbolNineSlice { top: -2.6, ..q });
assert_eq!(e.moved(NineSliceGuide::Right, Point::new(1e6, 0.0)), SymbolNineSlice { right: -MAX_GUIDE_FRACTION, ..q });
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(-1e300, 0.0)), SymbolNineSlice { left: -MAX_GUIDE_FRACTION, ..q });
let crossed = e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0));
assert!((crossed.left - (0.75 - MIN_CENTER_BAND)).abs() < 1e-12, "{crossed:?}");
assert!(SymbolNineSlice::new(crossed.left, crossed.top, crossed.right, crossed.bottom).is_some());
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(f64::NAN, f64::NAN)), q);
assert_eq!(e.moved(NineSliceGuide::Top, Point::new(0.0, f64::INFINITY)), q);
// With the right guide past the art's right edge, the left one may pass that edge too.
let wide = SymbolNineSlice { right: -0.5, ..q };
let e = editing(Some(wide), xf).edited_nine_slice().unwrap();
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(260.0, 50.0)), SymbolNineSlice { left: 1.25, ..wide });
assert!(near_point(e.line(NineSliceGuide::Right).0, Point::new(310.0, 20.0)));
assert!(near_point(e.line(NineSliceGuide::Right).1, Point::new(310.0, 220.0)));
// Saved guides closer than the minimum center band keep their place when a drag does not
// move them closer.
let narrow = SymbolNineSlice::new(0.00005, 0.25, 0.9999, 0.25).unwrap();
let e = editing(Some(narrow), xf).edited_nine_slice().unwrap();
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(200.0, 50.0)), narrow);
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: 0.0, ..narrow });
assert_eq!(e.moved(NineSliceGuide::Left, Point::new(0.0, 50.0)), SymbolNineSlice { left: -0.05, ..narrow });
// A mirrored placement measures along the symbol's own axes.
let e = editing(Some(SymbolNineSlice::default()), Affine::scale_non_uniform(-1.0, 1.0)).edited_nine_slice().unwrap();
assert!(near_point(e.line(NineSliceGuide::Left).0, Point::new(-25.0, 0.0)));
+50 -4
View File
@@ -2,14 +2,15 @@
//! symbol keeps appearance changes of its own to objects in the symbol's art, while the art stays
//! the symbol's. Editing the symbol reshapes every instance and each keeps its changes; Reset drops
//! them. The changes are stored on the instance ([`crate::node::NodeExtras::symbol_overrides`]) and
//! applied wherever an instance is drawn or exported ([`dynamic_art`]).
//! applied wherever an instance is drawn or exported ([`dynamic_art`]), and an instance's fill
//! stains the art after them ([`instance_art`]).
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_color::{BlendMode, Color, Paint};
use crate::{Node, NodeKind};
use crate::{AppearanceItem, Node, NodeKind};
/// Deepest object an override may name: groups nested this deep in the symbol's art.
pub const MAX_PATH_DEPTH: usize = 64;
@@ -150,6 +151,52 @@ pub fn dynamic_art(art: &Node, inst: &Node) -> Node {
a
}
/// Mix every solid paint under `n` towards `color` by `amount` (0..1): the Symbol Stainer.
pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
let amount = amount.clamp(0.0, 1.0);
for it in &mut n.appearance.items {
let p = match it {
AppearanceItem::Fill(f) => &mut f.paint,
AppearanceItem::Stroke(s) => &mut s.paint,
};
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
for p in [&mut r.style.fill, &mut r.style.stroke] {
if let Paint::Solid { color: c, .. } = p {
*p = Paint::solid(c.lerp(color, amount));
}
}
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
tint_node(Arc::make_mut(c), color, amount);
}
}
}
/// The stain instance `inst` puts on its symbol's art: its visible fill color and that fill's
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
Some((f.paint.color()?, f.opacity))
}
/// A symbol's art for instance `inst`, as the canvas draws it: with the instance's own appearance
/// changes to it ([`dynamic_art`]), stained by the instance's fill ([`stain`]).
pub fn instance_art(art: &Node, inst: &Node) -> Node {
let mut a = dynamic_art(art, inst);
if let Some((c, amount)) = stain(inst) {
tint_node(&mut a, &c, amount);
}
a
}
/// Keep the overrides that name an object of `art` (a symbol's new art), dropping the rest.
pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
overrides.retain(|o| part(art, &o.path).is_some());
@@ -159,7 +206,6 @@ pub fn retain_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
mod tests {
use super::*;
use crate::{Appearance, NodeId};
use vectorcraft_color::Color;
use vectorcraft_geom::{Rect, shapes};
fn square(id: u64) -> Arc<Node> {
+158 -34
View File
@@ -2,13 +2,14 @@
//! the document and measures it once, and an instance's bounds are its art's box placed by the
//! instance's transform ([`Node::geometric_bounds_with`]).
use std::cell::{Cell, RefCell};
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -26,6 +27,9 @@ const MAX_REACHES: usize = 4096;
/// A symbol's name and the bits of the linear part of a transform that places its art.
type Placing = (String, [u64; 4]);
/// Each symbol name of a document → the index of the first symbol of that name.
pub(crate) type SymbolNames = HashMap<String, usize>;
/// A symbol's art measured in symbol space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ArtBox {
@@ -51,6 +55,10 @@ pub(crate) struct ArtBox {
/// symbols change.
pub struct SymbolBoxes<'a> {
doc: &'a Document,
/// Each symbol name of the document → the index of the first symbol of that name (the one a
/// name finds), made the first time a name is looked up ([`Self::symbol_art`]) or given by
/// [`Self::with_names`].
names: OnceCell<Arc<SymbolNames>>,
/// The art boxes measured so far, by symbol name (`None` for a symbol whose instances are
/// measured by [`SYMBOL_SQUARE`]).
measured: RefCell<HashMap<String, Option<ArtBox>>>,
@@ -87,6 +95,11 @@ pub struct SymbolBoxes<'a> {
sliced_placed: Cell<u64>,
/// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`].
sliced_most: u64,
/// The widths [`Self::measured_width`] has measured, by kind and symbol name.
widths: RefCell<HashMap<(&'static str, String), Option<f64>>>,
/// While [`Self::consulted`] runs: the symbols whose art boxes [`Self::art`] has given outside
/// the measuring of symbol art.
consulted: RefCell<Option<HashSet<String>>>,
}
impl Document {
@@ -94,6 +107,7 @@ impl Document {
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
SymbolBoxes {
doc: self,
names: OnceCell::new(),
measured: RefCell::default(),
depths: RefCell::default(),
quick: Cell::new(false),
@@ -107,8 +121,28 @@ impl Document {
sliced: RefCell::default(),
sliced_placed: Cell::new(0),
sliced_most: MAX_SYMBOL_NODES,
widths: RefCell::default(),
consulted: RefCell::default(),
}
}
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
names.entry(s.name.clone()).or_insert(i);
}
names
}
}
#[cfg(test)]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
}
impl<'a> SymbolBoxes<'a> {
@@ -117,6 +151,26 @@ impl<'a> SymbolBoxes<'a> {
self.doc
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
let _ = self.names.set(names.clone());
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
}
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -157,21 +211,37 @@ impl<'a> SymbolBoxes<'a> {
/// art boxes. Returns `None` when [`Self::depth`] is `None` and when the art has no finite
/// bounds: instances of the symbol are then measured by [`SYMBOL_SQUARE`].
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
if let Some(b) = self.measured.borrow().get(name) {
return *b;
let cached = self.measured.borrow().get(name).copied();
let b = cached.unwrap_or_else(|| {
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
});
if b.is_some()
&& let Some(seen) = self.consulted.borrow_mut().as_mut()
&& !seen.contains(name)
{
seen.insert(name.to_string());
}
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
}
/// Runs `measure`, and returns the names of the symbols whose art boxes it took from these
/// boxes, the art of symbols it measured left out: the symbols whose art the instances it
/// measured are measured by.
pub(crate) fn consulted(&self, measure: impl FnOnce()) -> HashSet<String> {
let was = self.consulted.replace(Some(HashSet::new()));
measure();
self.consulted.replace(was).unwrap_or_default()
}
/// Runs `measure` on the art of the symbol named `name`. Returns `None` when [`Self::depth`]
/// is `None`, without running it.
pub fn measure_art<R>(&self, name: &str, measure: impl FnOnce(&Arc<Node>) -> R) -> Option<R> {
self.depth(name)?;
let sym = self.doc.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_art(name)?;
self.runs.set(self.runs.get() + 1);
Some(measure(&sym.art))
Some(measure(art))
}
/// How many times [`Self::measure_art`] has run a measure on symbol art for these boxes, the
@@ -247,6 +317,18 @@ impl<'a> SymbolBoxes<'a> {
self.art(name)?.brush
}
/// The width `measure` gives for the symbol named `name`, measured once for these boxes for each
/// `kind`, which names what `measure` measures. `measure` may call this again for other names.
pub fn measured_width(&self, kind: &'static str, name: &str, measure: impl FnOnce() -> Option<f64>) -> Option<f64> {
let key = (kind, name.to_string());
if let Some(w) = self.widths.borrow().get(&key) {
return *w;
}
let w = measure();
self.widths.borrow_mut().insert(key, w);
w
}
/// How far the visual box of an instance of the symbol named `name` grows in boxes made by
/// [`Self::with_brush_art`]: `16 × max(w, 1) + 8` for the widest stroke `w` that
/// [`Self::brush_width`] finds, as far as the renderer grows the cull bounds of a brushed path
@@ -282,10 +364,9 @@ impl<'a> SymbolBoxes<'a> {
/// other symbols it reaches: the depth of each one it walks to the end, and `None` for those on
/// the way down to a symbol that holds an instance of itself or nests too deep.
fn find_depth(&self, name: &str, learned: &mut HashMap<String, Option<usize>>) -> Option<usize> {
let art = |n: &str| self.doc.symbols.iter().find(|s| s.name == n).map(|s| &s.art);
// The symbols on the way down from `name`: each with the symbols its art shows that are
// still to be walked, and the deepest nesting found under it so far.
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), shown(self.doc, art(name)?), 0)];
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), self.shown(self.symbol_art(name)?), 0)];
loop {
let (_, todo, _) = path.last_mut()?;
let Some(next) = todo.pop() else {
@@ -315,8 +396,8 @@ impl<'a> SymbolBoxes<'a> {
// Symbols nested MAX_DEPTH deep under `name`.
None if path.len() >= MAX_DEPTH => return None,
None => {
if let Some(a) = art(&next) {
let todo = shown(self.doc, a);
if let Some(a) = self.symbol_art(&next) {
let todo = self.shown(a);
path.push((next, todo, 0));
}
}
@@ -364,9 +445,9 @@ impl<'a> SymbolBoxes<'a> {
None => {
// The most objects placing makes, the art of opacity masks included, is set aside
// while the art is placed and measured, and what placing did not make is given back.
let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art;
let most = match self.doc.symbol_slice_map(name, linear) {
Some(m) => m.most_placed(art, self.doc),
let art = self.symbol_art(name)?;
let most = match self.slice_map(name, linear) {
Some(m) => self.in_art(|| m.most_placed_with(art, self)),
None => art.count_with_masks() as u64,
};
let used = self.sliced_placed.get();
@@ -383,6 +464,14 @@ impl<'a> SymbolBoxes<'a> {
v.map(|v| moved.transform_rect_bbox(v))
}
/// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for
/// the symbol (its geometric part, which does not depend on the mode of the boxes).
pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.doc.symbol_nine_slice(name)?;
let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?;
NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf)
}
/// The box [`Self::placed_visual_within`] returns outside quick boxes.
fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
self.place_and_count(name, xf, most).and_then(|(v, _)| v)
@@ -392,10 +481,10 @@ impl<'a> SymbolBoxes<'a> {
/// opacity masks included. `None` when the art is not placed.
fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option<Rect>, u64)> {
self.measure_art(name, |art| {
let art = match self.doc.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self.doc) > most => return None,
Some(m) => m.place(art, self.doc),
None => self.doc.place_symbol_art(name, art, xf)?,
let art = match self.slice_map(name, xf) {
Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None,
Some(m) => self.in_art(|| m.place_with(art, self)),
None => transformed(art, xf),
};
Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64))
})
@@ -416,11 +505,28 @@ impl<'a> SymbolBoxes<'a> {
fn in_art<R>(&self, f: impl FnOnce() -> R) -> R {
let pad = self.brush_art.replace(false);
let strokes = self.art_strokes.replace(true);
let consulted = self.consulted.take();
let r = self.quickly(f);
self.brush_art.set(pad);
self.art_strokes.set(strokes);
*self.consulted.borrow_mut() = consulted;
r
}
/// The names of the symbols of the document that the instances in `art` show, each once.
fn shown(&self, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& self.symbol_art(symbol).is_some()
{
names.push(symbol.clone());
}
});
names
}
}
/// Records every symbol on `path` in `learned` as one whose instances are measured by
@@ -432,21 +538,6 @@ fn give_up(path: &[(String, Vec<String>, usize)], learned: &mut HashMap<String,
None
}
/// The names of the symbols of `doc` that the instances in `art` show, each once.
fn shown(doc: &Document, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& doc.symbols.iter().any(|s| s.name == *symbol)
{
names.push(symbol.clone());
}
});
names
}
/// Measures symbol art `art`, with the instances in it measured by `symbols`.
fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite());
@@ -615,6 +706,39 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
// scaled 2 times across, each shown by 200 instances scaled by different amounts.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Dot {i}"), vec![dot]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default()));
let scaled = |d: &mut Document, name: &str| -> Vec<Node> {
(1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect()
};
let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder"));
// What each instance measures in boxes of its own.
let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect();
let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect();
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), exact);
let s = d.symbol_boxes().quick();
assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), quick);
// Each set of boxes reads the list once to find symbols by name.
let symbols = d.symbols.len();
assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before);
}
#[test]
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
let mut d = Document::new(200.0, 200.0);
+4 -1
View File
@@ -17,7 +17,10 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use char_style::{
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+220 -1
View File
@@ -44,6 +44,14 @@ pub struct CharStyle {
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Tsume (Character panel, East Asian options): the percentage of the blank space on each side
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
/// after it. Horizontal type only.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub tsume: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -145,6 +153,29 @@ pub struct CharStyle {
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "standardVerticalRoman", skip_serializing_if = "crate::skip::is_default")]
pub standard_vertical_roman: bool,
/// Warichu (Character panel menu, East Asian options): these characters are set at
/// [`Self::warichu_scale`] percent of their size and stacked on [`Self::warichu_lines`] lines
/// inside their line, one above the other in horizontal type and side by side in vertical type.
/// A stretch of marked characters is one block that takes the settings of its first character
/// and stays whole on one line. Type on a path sets them at their own size on the path.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub warichu: bool,
/// Warichu Settings › Lines: how many lines a warichu block is stacked on, within
/// [`WARICHU_LINES`]. Saved only when not 2.
#[serde(default = "two", rename = "warichuLines", skip_serializing_if = "is_two")]
pub warichu_lines: u8,
/// Warichu Settings › Line Gap, in points from 0 to [`MAX_WARICHU_GAP`]: the space between the
/// lines of a warichu block. Saved only when not 0.
#[serde(default, rename = "warichuGap", skip_serializing_if = "crate::skip::is_default")]
pub warichu_gap: f64,
/// Warichu Settings › Scale: the size of warichu characters as a percentage of their size,
/// within [`WARICHU_SCALE`]. Saved only when not 50.
#[serde(default = "fifty", rename = "warichuScale", skip_serializing_if = "is_fifty")]
pub warichu_scale: f64,
/// Warichu Settings › Alignment: how the lines of a warichu block line up along the block.
#[serde(default, rename = "warichuAlign", skip_serializing_if = "crate::skip::is_default")]
pub warichu_align: WarichuAlign,
/// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of
/// these characters are drawn in, whatever digits were typed.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
@@ -174,6 +205,99 @@ pub struct CharStyle {
/// default glyph otherwise. Saved only when set.
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
pub glyph_alternate: Option<GlyphChoice>,
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
/// font's default glyphs. The text keeps its characters. Saved only when set.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
pub glyph_form: GlyphForm,
}
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GlyphForm {
/// The font's default glyphs.
#[default]
Default,
/// Traditional forms (`trad`).
Traditional,
/// Expert forms (`expt`).
Expert,
/// JIS 2004 forms (`jp04`).
Jis04,
/// JIS 90 forms (`jp90`).
Jis90,
/// JIS 78 forms (`jp78`).
Jis78,
/// JIS 83 forms (`jp83`).
Jis83,
/// Monospaced full-width forms (`fwid`).
FullWidth,
/// Monospaced half-width forms (`hwid`).
HalfWidth,
/// Monospaced third-width forms (`twid`).
ThirdWidth,
/// Monospaced quarter-width forms (`qwid`).
QuarterWidth,
}
impl GlyphForm {
/// Every form, in menu order, the default last.
pub const ALL: [GlyphForm; 11] = [
GlyphForm::Traditional,
GlyphForm::Expert,
GlyphForm::Jis04,
GlyphForm::Jis90,
GlyphForm::Jis78,
GlyphForm::Jis83,
GlyphForm::FullWidth,
GlyphForm::HalfWidth,
GlyphForm::ThirdWidth,
GlyphForm::QuarterWidth,
GlyphForm::Default,
];
/// The name files and commands give this form (as it is saved).
pub fn id(self) -> &'static str {
match self {
GlyphForm::Default => "default",
GlyphForm::Traditional => "traditional",
GlyphForm::Expert => "expert",
GlyphForm::Jis04 => "jis04",
GlyphForm::Jis90 => "jis90",
GlyphForm::Jis78 => "jis78",
GlyphForm::Jis83 => "jis83",
GlyphForm::FullWidth => "fullWidth",
GlyphForm::HalfWidth => "halfWidth",
GlyphForm::ThirdWidth => "thirdWidth",
GlyphForm::QuarterWidth => "quarterWidth",
}
}
/// The form [`GlyphForm::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<GlyphForm> {
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
}
/// The OpenType feature that draws this form; `None` for the default glyphs.
pub fn feature(self) -> Option<&'static [u8; 4]> {
Some(match self {
GlyphForm::Default => return None,
GlyphForm::Traditional => b"trad",
GlyphForm::Expert => b"expt",
GlyphForm::Jis04 => b"jp04",
GlyphForm::Jis90 => b"jp90",
GlyphForm::Jis78 => b"jp78",
GlyphForm::Jis83 => b"jp83",
GlyphForm::FullWidth => b"fwid",
GlyphForm::HalfWidth => b"hwid",
GlyphForm::ThirdWidth => b"twid",
GlyphForm::QuarterWidth => b"qwid",
})
}
}
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
@@ -417,6 +541,85 @@ fn hundred() -> f64 {
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
/// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink.
pub const MAX_TSUME: f64 = 100.0;
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
/// The largest Warichu Settings Line Gap ([`CharStyle::warichu_gap`]), in points.
pub const MAX_WARICHU_GAP: f64 = 100.0;
/// The Warichu Settings Scale ([`CharStyle::warichu_scale`]) range, in percent of the size.
pub const WARICHU_SCALE: std::ops::RangeInclusive<f64> = 10.0..=100.0;
fn two() -> u8 {
2
}
fn is_two(v: &u8) -> bool {
*v == 2
}
fn fifty() -> f64 {
50.0
}
fn is_fifty(v: &f64) -> bool {
*v == 50.0
}
/// How the lines of a warichu block line up along the block ([`CharStyle::warichu_align`]):
/// each line set flush left (top, in vertical type), centered or flush right (bottom), or spread
/// to the block's length with the last line set flush left, centered or flush right, or spread as
/// well. Auto is the default and sets the lines as [`WarichuAlign::JustifyLeft`] does.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarichuAlign {
#[default]
Auto,
Left,
Center,
Right,
JustifyLeft,
JustifyCenter,
JustifyRight,
JustifyAll,
}
impl WarichuAlign {
/// Every alignment, in the order Warichu Settings lists them.
pub const ALL: [WarichuAlign; 8] = [
WarichuAlign::Auto,
WarichuAlign::Left,
WarichuAlign::Center,
WarichuAlign::Right,
WarichuAlign::JustifyLeft,
WarichuAlign::JustifyCenter,
WarichuAlign::JustifyRight,
WarichuAlign::JustifyAll,
];
/// The name files and commands give this alignment (as it is saved).
pub fn id(self) -> &'static str {
match self {
WarichuAlign::Auto => "auto",
WarichuAlign::Left => "left",
WarichuAlign::Center => "center",
WarichuAlign::Right => "right",
WarichuAlign::JustifyLeft => "justifyLeft",
WarichuAlign::JustifyCenter => "justifyCenter",
WarichuAlign::JustifyRight => "justifyRight",
WarichuAlign::JustifyAll => "justifyAll",
}
}
/// The alignment [`WarichuAlign::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<WarichuAlign> {
WarichuAlign::ALL.into_iter().find(|a| a.id() == id)
}
}
pub(super) fn yes() -> bool {
true
}
@@ -435,6 +638,7 @@ impl Default for CharStyle {
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
tsume: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -464,12 +668,18 @@ impl Default for CharStyle {
tcy_up_down: 0.0,
tcy_left_right: 0.0,
standard_vertical_roman: false,
warichu: false,
warichu_lines: 2,
warichu_gap: 0.0,
warichu_scale: 50.0,
warichu_align: WarichuAlign::Auto,
small_caps: None,
digits: Digits::Default,
font_height_reference: FontHeightReference::EmBox,
no_break: false,
language: None,
glyph_alternate: None,
glyph_form: GlyphForm::Default,
}
}
}
@@ -484,7 +694,11 @@ impl CharStyle {
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
/// [`MAX_AKI`], and one that is not a number becomes 0; Tsume is kept from 0 to [`MAX_TSUME`] the
/// same way. The Warichu Settings Lines and Scale
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
/// own units.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -499,6 +713,11 @@ impl CharStyle {
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) };
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
self.warichu_scale =
if self.warichu_scale.is_nan() { default.warichu_scale } else { self.warichu_scale.clamp(*WARICHU_SCALE.start(), *WARICHU_SCALE.end()) };
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+35 -3
View File
@@ -34,10 +34,19 @@ impl TextObject {
style.baseline_shift *= scale.points;
style.tcy_up_down *= scale.points;
style.tcy_left_right *= scale.points;
style.warichu_gap *= scale.points;
style.h_scale *= scale.horizontal;
if ![style.size, style.leading.unwrap_or(0.0), style.baseline_shift, style.tcy_up_down, style.tcy_left_right, style.h_scale]
.iter()
.all(|v| v.is_finite())
if ![
style.size,
style.leading.unwrap_or(0.0),
style.baseline_shift,
style.tcy_up_down,
style.tcy_left_right,
style.warichu_gap,
style.h_scale,
]
.iter()
.all(|v| v.is_finite())
{
return None;
}
@@ -114,6 +123,12 @@ impl TextObject {
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
/// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not
/// on a path, which sets them as they are. Exports that write live text write such type as
/// outlines, as they do ruby: their text can't place the stacked lines.
pub fn stacks_warichu(&self) -> bool {
!matches!(self.kind, TextKind::OnPath { .. }) && self.runs.iter().any(|r| r.style.warichu && !r.text.is_empty())
}
/// Clamp the ruby spans to the plain text, drop empty/empty-reading ones and sort them.
///
/// Called after loading and editing text: ranges from a file or an edit are untrusted, and a
@@ -492,8 +507,24 @@ impl crate::Document {
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.tsume = num("tsume").unwrap_or(st.tsume);
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
st.keep_dimensions_in_range();
// Lines is a whole number: a stored number outside the range, or with a fraction,
// becomes the nearest whole number within it.
if let Some(old) = def.attrs.get_mut("warichuLines")
&& old.is_number()
&& old.as_u64().is_none_or(|v| !super::WARICHU_LINES.contains(&u8::try_from(v).unwrap_or(u8::MAX)))
{
let (lo, hi) = (*super::WARICHU_LINES.start(), *super::WARICHU_LINES.end());
let v = old.as_f64().filter(|v| v.is_finite()).map_or(2.0, |v| v.round().clamp(f64::from(lo), f64::from(hi)));
// Within 1..6 after the clamp, so the cast keeps the value.
*old = (v as u8).into();
}
let kept = [
("warichuGap", Some(st.warichu_gap)),
("warichuScale", Some(st.warichu_scale)),
("size", Some(st.size)),
("h_scale", Some(st.h_scale)),
("v_scale", Some(st.v_scale)),
@@ -502,6 +533,7 @@ impl crate::Document {
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("tsume", Some(st.tsume)),
("leading", st.leading),
];
for (k, v) in kept {
+3 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
/// Insert Aki, Tsume, tate-chu-yoko, warichu, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -368,8 +368,10 @@ impl ParaList {
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
tsume: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
warichu: false,
underline: false,
strikethrough: false,
..first.clone()
+28
View File
@@ -129,6 +129,34 @@ fn insert_aki_is_saved_only_when_set() {
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
}
/// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a
/// value out of range from a file, in a run or a character style, is kept from 0 to 100.
#[test]
fn tsume_is_saved_only_when_set_and_kept_in_range() {
let st = CharStyle::default();
assert_eq!(st.tsume, 0.0);
let saved = serde_json::to_value(&st).unwrap();
assert!(saved.get("tsume").is_none());
let read = serde_json::from_value::<CharStyle>(saved).unwrap();
assert_eq!(read.tsume, 0.0);
let set = CharStyle { tsume: 37.5, ..CharStyle::default() };
let saved = serde_json::to_value(&set).unwrap();
assert_eq!(saved.get("tsume").and_then(serde_json::Value::as_f64), Some(37.5));
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
for (stored, kept) in [(-5.0, 0.0), (250.0, MAX_TSUME), (f64::NAN, 0.0), (f64::INFINITY, MAX_TSUME), (50.0, 50.0)] {
let mut damaged = CharStyle { tsume: stored, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!(damaged.tsume, kept, "{stored}");
}
let mut d = crate::Document::new(100.0, 100.0);
for tsume in [500, -1] {
let attrs = serde_json::json!({ "tsume": tsume });
d.char_styles.push(TextStyleDef { name: format!("Tight {tsume}"), attrs: attrs.as_object().cloned().unwrap_or_default() });
}
d.keep_type_values_in_range();
assert_eq!((d.char_styles[0].attrs["tsume"].as_f64(), d.char_styles[1].attrs["tsume"].as_f64()), (Some(MAX_TSUME), Some(0.0)));
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
+49
View File
@@ -0,0 +1,49 @@
//! A warp grid kept before type's measure is registered is built again once it is, even when the
//! registered inputs number is 0. One test in its own process, so nothing has registered the
//! measure before it runs.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::sync::Arc;
use vectorcraft_doc::live::{EnvelopeOptions, set_type_ink, warp_grid};
use vectorcraft_doc::{CharStyle, EnvelopeKind, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Affine, Point, Rect};
/// A measure that gives every type the same box, well away from its laid-out box.
fn fixed_ink(_: &TextObject, _: Affine, _: Option<(vectorcraft_geom::Homography, Affine)>) -> Option<Rect> {
Some(Rect::new(0.0, 0.0, 400.0, 300.0))
}
fn no_inputs() -> u64 {
0
}
/// An arc warp around `t`, its content in a new `Arc`.
fn warp_of(t: &TextObject) -> Node {
let content = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 1 };
Node::new(
NodeId(2),
NodeKind::Envelope {
content: vec![content],
kind: Box::new(kind),
fidelity: 50.0,
editing: false,
options: EnvelopeOptions::NEW,
frame: Box::new(Affine::IDENTITY),
},
)
}
#[test]
fn a_warp_grid_kept_before_the_type_measure_is_built_again() {
let t = TextObject::point(Point::new(100.0, 100.0), "Type", CharStyle::default());
let n = warp_of(&t);
let before = warp_grid(&n);
set_type_ink(fixed_ink, no_inputs);
let fresh = warp_grid(&warp_of(&t));
assert!(fresh.is_some());
assert_ne!(fresh, before, "the registered measure moves the grid");
assert_eq!(warp_grid(&n), fresh, "the grid kept from before the registration is built again");
}
+2
View File
@@ -29,3 +29,5 @@ serde_json = { workspace = true }
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# Test live-effect plug-ins written in WebAssembly text.
wat = { workspace = true }
+3 -2
View File
@@ -523,13 +523,14 @@ fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) {
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
/// when given, otherwise the symbol's art with the instance's own appearance changes, stained by
/// the instance's fill ([`vectorcraft_doc::symbol_overrides::instance_art`]).
pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>) -> Option<Node> {
let art;
let src = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if has_adjustment(n) => {
let symbol = symbol_art
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n)));
.or_else(|| d.symbols.iter().find(|s| s.name == *symbol).map(|s| vectorcraft_doc::symbol_overrides::instance_art(&s.art, n)));
art = crate::reshape::as_art(Some(d), n, symbol.as_ref())?;
&art
}
Loaded 100 of 999 files, more files were not shown because too many files have changed in this diff. Show more