mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 08:52:45 +01:00
Merge current main before Scissors full local CI
This commit is contained in:
commit
bdae835305
1487 files changed
+313289
-23671
No files matched your search
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
|
||||
@@ -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
+507
-127
File diff suppressed because it is too large.
Load diff
+50
-31
@@ -11,21 +11,40 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# 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" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -83,10 +102,12 @@ wat = "1.228"
|
||||
# Without `text` (glyph runs, through glifo and a second skrifa): the renderer draws the outlines
|
||||
# vectorcraft-text gives it. The other default features stay.
|
||||
vello_cpu = { version = "0.2", default-features = false, features = ["std", "png", "u8_pipeline", "f32_pipeline"] }
|
||||
# The image crate still decodes and encodes for the readers not yet moved to craft-image-codecs
|
||||
# (File › Open's raster path, PDF and SVG images, the renderer's image paint, DIBs). Its format
|
||||
# features stay until the last of those moves, so no file that opens today stops opening.
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp", "tga"] }
|
||||
# Without `text` and the system fonts (fontdb, harfrust and skrifa, at other versions than ours):
|
||||
# SVG import reads `<text>` from the XML itself and never gives usvg a font. A test of the SVG
|
||||
# crate turns `text` on.
|
||||
# SVG import reads `<text>` from the XML itself and never gives usvg a font.
|
||||
usvg = { version = "0.48", default-features = false, features = ["svgz"] }
|
||||
# Without `simple-text` (its text shaping, the only user of rustybuzz and ttf-parser, which are
|
||||
# unmaintained, #1730): the PDF writer places glyphs itself. A test of the PDF crate turns it on.
|
||||
@@ -98,18 +119,9 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
|
||||
rustix = { version = "1.1", default-features = false }
|
||||
# Zstandard decoder (pure Rust, builds for wasm32 too): the editing copy an EPS carries of its art.
|
||||
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
|
||||
# CCITT Group 3 and Group 4 decoder (ITU-T T.4 and T.6): EPS images read through
|
||||
# `CCITTFaxDecode`. The PDF reader's hayro-syntax uses the same version.
|
||||
hayro-ccitt = "0.3"
|
||||
# Substring search for the EPS reader's PostScript `search`.
|
||||
memchr = "2"
|
||||
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
|
||||
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
|
||||
encoding_rs = "0.8.42"
|
||||
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
|
||||
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
|
||||
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
|
||||
# decoders, read directly (the image crate converts CMYK to RGB).
|
||||
# vectorcraft-doc's CMYK TIFF reader and writer (src/cmyk.rs) still use `tiff`. `zune-jpeg` and
|
||||
# `hayro-ccitt` are only the references tests compare craft-image-codecs' CMYK JPEG inks and
|
||||
# craft-stream-codecs' Group 3 rows with (vectorcraft-doc's and vectorcraft-engine's dev-dependencies).
|
||||
tiff = "0.11"
|
||||
zune-jpeg = "0.5"
|
||||
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
|
||||
@@ -122,6 +134,13 @@ jxl-grid = "0.6.2"
|
||||
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
|
||||
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
|
||||
zune-core = "0.5"
|
||||
hayro-ccitt = "0.3"
|
||||
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
|
||||
# Substring search for the EPS reader's PostScript `search`.
|
||||
memchr = "2"
|
||||
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
|
||||
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
|
||||
encoding_rs = "0.8.42"
|
||||
|
||||
# ui
|
||||
egui = "0.37"
|
||||
@@ -165,13 +184,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -146,3 +146,125 @@ Indic hyphenation patterns (crates/text/patterns/):
|
||||
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
jpeg-encoder 0.6.1, https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Licensed under (MIT OR Apache-2.0) AND IJG. The MIT option and the IJG and SIMD
|
||||
notices are reproduced below. Original license texts and provenance hashes are
|
||||
retained in licenses/jpeg-encoder-0.6.1/.
|
||||
|
||||
--- jpeg-encoder 0.6.1: LICENSE-MIT ---
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
|
||||
--- jpeg-encoder 0.6.1: IJG-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
--- jpeg-encoder 0.6.1: SIMD-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
@@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified
|
||||
The scores are self-assessed from our code against public documentation;
|
||||
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
|
||||
|
||||
All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview.
|
||||
|
||||
**What's missing:**
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
|
||||
- scripting, and the rest of Variables (image and graph kinds, dataset import);
|
||||
- generative AI features.
|
||||
|
||||
+25
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -18,11 +18,13 @@ 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 |
|
||||
|---|---|---|
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
|
||||
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
|
||||
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
|
||||
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
|
||||
@@ -96,17 +98,18 @@ 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% |
|
||||
| Indonesian | `id` | none | 0% |
|
||||
| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips |
|
||||
| Japanese | `ja` | full | 100% |
|
||||
| German | `de` | full | 98% |
|
||||
| Korean | `ko` | full | 100% |
|
||||
| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% |
|
||||
| Vietnamese | `vi` | full | 100% |
|
||||
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
|
||||
The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md).
|
||||
|
||||
## Upcoming
|
||||
@@ -121,11 +124,20 @@ 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-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), 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-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. 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-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers 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.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
@@ -133,14 +145,18 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
|
||||
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
|
||||
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
|
||||
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 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 +232,9 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
| 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 +243,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. |
|
||||
|
||||
@@ -238,10 +238,11 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
prefs_dir::attach_color_settings(&mut h.session);
|
||||
@@ -418,10 +419,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);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+1749
-173
File diff suppressed because it is too large.
Load diff
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(windows)]
|
||||
use super::windows_screen_color;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
@@ -354,7 +356,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
@@ -393,8 +395,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.
|
||||
@@ -412,6 +415,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
#[cfg(windows)]
|
||||
screen_color: Some(windows_screen_color::sampler(sampled_ui)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode <mode>] [--frame-latency <frames>] [--] [files…]`,
|
||||
//! `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
@@ -19,6 +20,9 @@
|
||||
//! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the
|
||||
//! files its requests read and write (`vectorcraft_engine::file_access`); the person at the
|
||||
//! keyboard isn't confined.
|
||||
//!
|
||||
//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change
|
||||
//! how the window's frames reach the display (`presentation`).
|
||||
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
|
||||
|
||||
mod automation_args;
|
||||
@@ -28,6 +32,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 +58,15 @@ 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 presentation;
|
||||
mod printing;
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
mod quit_windows;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
mod single_instance;
|
||||
#[cfg(windows)]
|
||||
@@ -67,6 +77,7 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_screen_color;
|
||||
mod windows_stylus;
|
||||
mod xwayland;
|
||||
|
||||
@@ -102,7 +113,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 +127,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 +138,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>,
|
||||
}
|
||||
@@ -150,6 +164,14 @@ Options:
|
||||
--safe-mode Start without plug-ins: none loads or runs until
|
||||
VectorCraft starts normally (Help › Safe Mode); the
|
||||
files open in a new window, as with --new-instance
|
||||
--present-mode <mode> How frames reach the display: fifo (vsync),
|
||||
autovsync (the default; relaxed vsync where the
|
||||
driver offers it) or novsync
|
||||
(or VECTORCRAFT_PRESENT_MODE)
|
||||
--frame-latency <frames> Frames the display may queue, 1 to 3 (the default
|
||||
is 1) (or VECTORCRAFT_FRAME_LATENCY); with either
|
||||
one set, the files open in a new window, as with
|
||||
--new-instance
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
@@ -169,13 +191,16 @@ struct CommandLine {
|
||||
safe_mode: bool,
|
||||
}
|
||||
|
||||
/// Reads the arguments after the program name. The automation roots and the control port go into
|
||||
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
|
||||
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
|
||||
/// Reads the arguments after the program name. The automation roots, the control port and the
|
||||
/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling
|
||||
/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code
|
||||
/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or
|
||||
/// presentation option or an unknown option prints an error and fails.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
presentation: &mut presentation::Overrides,
|
||||
) -> Result<CommandLine, std::process::ExitCode> {
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
@@ -188,7 +213,11 @@ fn read_command_line(
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
match roots_args
|
||||
.consume(&a, &mut args)
|
||||
.and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) })
|
||||
.and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) })
|
||||
{
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
@@ -227,6 +256,14 @@ fn read_command_line(
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
// After the arguments: the flags, `--version` and `--help` win over a bad environment value.
|
||||
match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) {
|
||||
Ok(overrides) => *presentation = overrides,
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
@@ -245,8 +282,9 @@ fn main() -> std::process::ExitCode {
|
||||
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
let mut roots_args =
|
||||
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
|
||||
let mut presentation = presentation::Overrides::default();
|
||||
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
@@ -267,7 +305,8 @@ fn main() -> std::process::ExitCode {
|
||||
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
|
||||
// the log file is attached: a launch that hands its files over leaves the running app's log be.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
// A launch that sets the presentation runs as its own app: a running app keeps its own surface.
|
||||
match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
@@ -359,17 +398,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 +427,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,12 +449,19 @@ 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;
|
||||
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
|
||||
// composites it, so the window answers the pointer a frame sooner (#444).
|
||||
options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
|
||||
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
|
||||
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
|
||||
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
|
||||
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
|
||||
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
|
||||
@@ -438,6 +492,10 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
options
|
||||
};
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
if presentation != presentation::Overrides::default() {
|
||||
log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it");
|
||||
}
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu::watch_panics();
|
||||
#[cfg(feature = "wgpu")]
|
||||
@@ -478,6 +536,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
@@ -531,14 +591,15 @@ fn main() -> std::process::ExitCode {
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
let hint = if chosen_gpu {
|
||||
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
));
|
||||
} else {
|
||||
""
|
||||
};
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
|
||||
));
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
|
||||
));
|
||||
}
|
||||
} else if let Some(crash) = &crash {
|
||||
app.status(match crash {
|
||||
gpu::Crash::Adapter { name, .. } => format!(
|
||||
@@ -585,7 +646,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 +692,7 @@ fn main() -> std::process::ExitCode {
|
||||
maximize_tries: 8,
|
||||
held_files,
|
||||
monitors_listed: None,
|
||||
display_profile: Default::default(),
|
||||
frame_start: None,
|
||||
}))
|
||||
}),
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
|
||||
/// makes.
|
||||
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Metadata Templates") {
|
||||
session.attach_metadata_templates_dir(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Have File › New start each category's documents from its profile in the `New Document
|
||||
/// Profiles` folder, which `file.newProfiles.edit` makes.
|
||||
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! `--present-mode <mode>` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency <frames>` (or
|
||||
//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The
|
||||
//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late
|
||||
//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox,
|
||||
//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of
|
||||
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
|
||||
//! overrides its variable; a value that isn't one of these stops the app with a message, as
|
||||
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
|
||||
//! The surface the app asks for is logged at start-up.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// A present mode the command line or the environment can ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Fifo,
|
||||
AutoVsync,
|
||||
NoVsync,
|
||||
}
|
||||
|
||||
/// The present mode and frame latency this launch asked for (`None`: the app's own setting).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Overrides {
|
||||
pub mode: Option<Mode>,
|
||||
pub latency: Option<u32>,
|
||||
}
|
||||
|
||||
/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case.
|
||||
fn mode(name: &str, value: Option<&str>) -> Result<Mode, String> {
|
||||
let need = format!("{name} needs fifo, autovsync or novsync");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
"fifo" => Ok(Mode::Fifo),
|
||||
"autovsync" => Ok(Mode::AutoVsync),
|
||||
"novsync" => Ok(Mode::NoVsync),
|
||||
_ => Err(format!("{need}, not `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame latency named by `name`: 1, 2 or 3.
|
||||
fn latency(name: &str, value: Option<&str>) -> Result<u32, String> {
|
||||
let need = format!("{name} needs 1, 2 or 3 frames");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`"))
|
||||
}
|
||||
|
||||
/// The value of `--flag <value>` or `--flag=<value>` when `arg` is that flag; `None` when it isn't.
|
||||
fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) -> Option<Option<String>> {
|
||||
match arg.strip_prefix(flag)? {
|
||||
"" => Some(args.next()),
|
||||
rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
/// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is
|
||||
/// its value whatever it is, as with `--control`.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
if let Some(value) = flag_value("--present-mode", arg, args) {
|
||||
if self.mode.is_some() {
|
||||
return Err("--present-mode given twice".into());
|
||||
}
|
||||
self.mode = Some(mode("--present-mode", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(value) = flag_value("--frame-latency", arg, args) {
|
||||
if self.latency.is_some() {
|
||||
return Err("--frame-latency given twice".into());
|
||||
}
|
||||
self.latency = Some(latency("--frame-latency", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`.
|
||||
/// Unset or empty is no override; a variable is not read when its flag was given.
|
||||
pub fn with_env(self, mode_var: Option<OsString>, latency_var: Option<OsString>) -> Result<Self, String> {
|
||||
let set = |v: Option<OsString>| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned());
|
||||
let mode = match (self.mode, set(mode_var)) {
|
||||
(Some(m), _) => Some(m),
|
||||
(None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
let latency = match (self.latency, set(latency_var)) {
|
||||
(Some(n), _) => Some(n),
|
||||
(None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
Ok(Self { mode, latency })
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let present_mode = match self.mode {
|
||||
Some(Mode::Fifo) => PresentMode::Fifo,
|
||||
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
|
||||
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
|
||||
None => surface.present_mode,
|
||||
};
|
||||
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The present mode and frame latency `surface` asks for, for the start-up log:
|
||||
/// "autovsync, frame latency 1", with "(override)"
|
||||
/// after a value a flag or variable set.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
|
||||
use eframe::wgpu::PresentMode;
|
||||
let mode = match surface.present_mode {
|
||||
PresentMode::AutoVsync => "autovsync",
|
||||
PresentMode::AutoNoVsync => "novsync",
|
||||
PresentMode::Fifo => "fifo",
|
||||
PresentMode::FifoRelaxed => "fiforelaxed",
|
||||
PresentMode::Immediate => "immediate",
|
||||
PresentMode::Mailbox => "mailbox",
|
||||
};
|
||||
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
let tag = |set: bool| if set { " (override)" } else { "" };
|
||||
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Overrides, String> {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = args.iter().map(|a| a.to_string());
|
||||
while let Some(a) = args.next() {
|
||||
assert!(overrides.consume(&a, &mut args)?, "{a}");
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_take_the_three_modes_and_latencies_from_1_to_3() {
|
||||
assert_eq!(parse(&[]), Ok(Overrides::default()));
|
||||
assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo)));
|
||||
assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync)));
|
||||
assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync)));
|
||||
for n in 1..=3 {
|
||||
assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n)));
|
||||
}
|
||||
assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_flag_values_are_errors() {
|
||||
let modes = "--present-mode needs fifo, autovsync or novsync";
|
||||
assert_eq!(parse(&["--present-mode"]), Err(modes.into()));
|
||||
for bad in ["mailbox", "immediate", "vsync", "fast", ""] {
|
||||
assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`")));
|
||||
assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`")));
|
||||
let frames = "--frame-latency needs 1, 2 or 3 frames";
|
||||
assert_eq!(parse(&["--frame-latency"]), Err(frames.into()));
|
||||
for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] {
|
||||
assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`")));
|
||||
}
|
||||
assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into()));
|
||||
assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_arguments_are_not_presentation_flags() {
|
||||
let mut overrides = Overrides::default();
|
||||
let mut args = ["fifo".to_owned()].into_iter();
|
||||
for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] {
|
||||
assert!(!overrides.consume(other, &mut args).unwrap(), "{other}");
|
||||
}
|
||||
assert_eq!(args.next().as_deref(), Some("fifo"));
|
||||
assert_eq!(overrides, Overrides::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() {
|
||||
let none = Overrides::default();
|
||||
assert_eq!(none.with_env(None, None), Ok(none));
|
||||
assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none));
|
||||
assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
|
||||
assert_eq!(
|
||||
none.with_env(Some("mailbox".into()), None),
|
||||
Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into())
|
||||
);
|
||||
assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into()));
|
||||
// A flag wins, and its variable is not read, so a bad value there doesn't stop the app.
|
||||
let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags));
|
||||
let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None };
|
||||
assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) }));
|
||||
// Either value set makes the launch run as its own app.
|
||||
assert!(!none.is_set());
|
||||
assert!(mode_only.is_set());
|
||||
assert!(Overrides { mode: None, latency: Some(1) }.is_set());
|
||||
}
|
||||
|
||||
/// `--help` states the app's own surface as the default, so it changes with it.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_usage_names_the_app_surface_as_the_default() {
|
||||
let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
|
||||
let usage = crate::USAGE.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default");
|
||||
assert!(usage.contains("autovsync (the default"), "{usage}");
|
||||
let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") };
|
||||
assert!(usage.contains(&format!("(the default is {frames})")), "{usage}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn overrides_change_only_what_they_set_on_the_app_surface() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
// No override: the surface the app asks for is unchanged.
|
||||
assert_eq!(Overrides::default().apply(app), app);
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
|
||||
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
|
||||
let s = fifo.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
|
||||
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
|
||||
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
|
||||
let s = novsync.apply(app);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
|
||||
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
|
||||
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
|
||||
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,8 @@ impl PrintService for SystemPrint {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,6 +28,15 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
@@ -38,7 +46,7 @@ mod system {
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +135,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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>"]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
for flag in [
|
||||
"--control",
|
||||
"--automation-read-root",
|
||||
"--automation-write-root",
|
||||
"--in-window-menus",
|
||||
"--safe-mode",
|
||||
"--present-mode",
|
||||
"--frame-latency",
|
||||
"--version",
|
||||
"--help",
|
||||
] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// A bad presentation variable stops the app with a message before it starts; `--help` and the
|
||||
/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail.
|
||||
#[test]
|
||||
fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() {
|
||||
for (var, value, need) in [
|
||||
("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"),
|
||||
("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"),
|
||||
] {
|
||||
let out = run(&[], &[(var, value)]);
|
||||
assert!(!out.status.success(), "{var}");
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n"));
|
||||
prints_usage(&["--help"], &[(var, value)]);
|
||||
}
|
||||
for (args, env) in [
|
||||
(&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")),
|
||||
(&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")),
|
||||
(&[], ("VECTORCRAFT_FRAME_LATENCY", "3")),
|
||||
] {
|
||||
let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}");
|
||||
}
|
||||
let out = run(&["--frame-latency", "4"], &[]);
|
||||
assert!(!out.status.success());
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n");
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
|
||||
@@ -20,4 +20,4 @@ craft-affinity = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# The tests build containers and decode previews.
|
||||
crc32fast = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
@@ -50,8 +50,8 @@ fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||||
assert_eq!((image.width, image.height), (400, 300));
|
||||
assert_eq!(image.transform, Affine::IDENTITY);
|
||||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
|
||||
let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8();
|
||||
assert_eq!(pixels.as_slice(), expected.as_raw());
|
||||
let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8();
|
||||
assert_eq!(pixels.as_slice(), expected.as_slice());
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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> {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! 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();
|
||||
}
|
||||
|
||||
/// Sets the art on `doc` as [`Document::mounted_art`] with the ids it is stored with, the id
|
||||
/// counter left as it is: what a save looks through, writing back only the brushes whose art it
|
||||
/// changed ([`Self::write_back`]).
|
||||
pub fn mount_as_stored(&self, doc: &mut Document) {
|
||||
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,14 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-dxf = { workspace = true }
|
||||
craft-plotter = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
@@ -18,6 +20,7 @@ vectorcraft-pathops = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+4
-67
@@ -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);
|
||||
|
||||
+2
-428
@@ -1,428 +1,2 @@
|
||||
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
|
||||
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
|
||||
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
|
||||
//! with the data their escapes carry.
|
||||
|
||||
/// The end-of-text character, the default label terminator.
|
||||
pub(super) const ETX: u8 = 3;
|
||||
const ESC: u8 = 0x1b;
|
||||
|
||||
/// The most digits of a number that count: longer ones are read as their first digits.
|
||||
const MAX_DIGITS: usize = 18;
|
||||
|
||||
/// What the bytes being read hold.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
/// HP-GL instructions.
|
||||
Hpgl,
|
||||
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
|
||||
Pcl,
|
||||
/// After a Universal Exit Language: PJL lines until a language starts.
|
||||
Pjl,
|
||||
}
|
||||
|
||||
/// One item of a PE (Polyline Encoded) instruction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum PeItem {
|
||||
/// Select pen.
|
||||
Pen(i64),
|
||||
/// Rectangle mode: the following coordinates come in fours.
|
||||
Rect,
|
||||
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
|
||||
Point { x: f64, y: f64, up: bool, absolute: bool },
|
||||
}
|
||||
|
||||
/// The state of one PE instruction being read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct Pe {
|
||||
seven_bit: bool,
|
||||
fraction_bits: u32,
|
||||
up: bool,
|
||||
absolute: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Lexer<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
mode: Mode,
|
||||
/// The file holds HP RTL or PCL raster image data.
|
||||
pub raster: bool,
|
||||
}
|
||||
|
||||
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
|
||||
fn separator(c: u8) -> bool {
|
||||
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.at).copied()
|
||||
}
|
||||
|
||||
/// Whether everything has been read.
|
||||
pub fn done(&self) -> bool {
|
||||
self.at >= self.b.len()
|
||||
}
|
||||
|
||||
/// How many bytes have been read.
|
||||
pub fn pos(&self) -> usize {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
|
||||
/// escape sequences may come before it (anything else gives `None`, as the end does).
|
||||
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if c == ESC {
|
||||
self.escape();
|
||||
continue;
|
||||
}
|
||||
match self.mode {
|
||||
Mode::Pcl => {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
Mode::Pjl => {
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c == b'@' {
|
||||
self.pjl_line();
|
||||
} else {
|
||||
self.mode = Mode::Hpgl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Mode::Hpgl => {}
|
||||
}
|
||||
let next = self.b.get(self.at + 1).copied();
|
||||
if c.is_ascii_alphabetic()
|
||||
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
|
||||
{
|
||||
self.at += 2;
|
||||
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
|
||||
}
|
||||
if strict && !(separator(c) || c == b';' || c < 0x20) {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
|
||||
fn pjl_line(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
|
||||
// A command names its language within its first 256 bytes; longer lines aren't copied.
|
||||
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
|
||||
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
|
||||
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
|
||||
}
|
||||
self.at += end;
|
||||
}
|
||||
|
||||
/// An escape sequence at the current byte, with the data it carries.
|
||||
fn escape(&mut self) {
|
||||
self.at += 1;
|
||||
let Some(c) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
match c {
|
||||
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
|
||||
// `ESC%#A` to PCL or HP RTL).
|
||||
b'%' => {
|
||||
let (_, end) = self.value();
|
||||
match end {
|
||||
Some(b'X') => self.mode = Mode::Pjl,
|
||||
Some(b'B') => self.mode = Mode::Hpgl,
|
||||
Some(b'A') => self.mode = Mode::Pcl,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Reset: PCL follows, until a language switch.
|
||||
b'E' => self.mode = Mode::Pcl,
|
||||
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
|
||||
b'.' => {
|
||||
let Some(kind) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
if !b"()YZBEJKLORUX".contains(&kind) {
|
||||
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
|
||||
if let Some(n) = rest.iter().position(|&c| c == b':')
|
||||
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
|
||||
{
|
||||
self.at += n + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parameterized PCL: a group character, then values each ending in a letter (upper case
|
||||
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
|
||||
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
|
||||
// `ESC)0N`), one value and the letter ending it.
|
||||
0x21..=0x2f => {
|
||||
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
|
||||
self.value();
|
||||
return;
|
||||
};
|
||||
self.at += 1;
|
||||
loop {
|
||||
let (v, end) = self.value();
|
||||
let Some(end) = end else { return };
|
||||
let upper = end.to_ascii_uppercase();
|
||||
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
|
||||
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
|
||||
if (c, group) == (b'*', b'b') && n > 0 {
|
||||
self.raster = true;
|
||||
}
|
||||
self.at += n;
|
||||
}
|
||||
if (c, group, end) == (b'*', b'r', b'A') {
|
||||
self.raster = true;
|
||||
}
|
||||
if !end.is_ascii_lowercase() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A two-character escape.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
|
||||
/// when that is not a letter or `@` (which is then left unread).
|
||||
fn value(&mut self) -> (f64, Option<u8>) {
|
||||
let v = self.number_here().unwrap_or(0.0);
|
||||
match self.peek() {
|
||||
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
|
||||
self.at += 1;
|
||||
(v, Some(c))
|
||||
}
|
||||
_ => (v, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
|
||||
/// (its sign and point are read all the same).
|
||||
fn number_here(&mut self) -> Option<f64> {
|
||||
let mut neg = false;
|
||||
if let Some(c @ (b'+' | b'-')) = self.peek() {
|
||||
neg = c == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
|
||||
let mut point = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
if digits < MAX_DIGITS {
|
||||
if point {
|
||||
scale /= 10.0;
|
||||
v += f64::from(c - b'0') * scale;
|
||||
} else {
|
||||
v = v * 10.0 + f64::from(c - b'0');
|
||||
}
|
||||
} else if !point {
|
||||
// Past the digits that count, an integer part keeps its size.
|
||||
v *= 10.0;
|
||||
}
|
||||
digits += 1;
|
||||
} else if c == b'.' && !point {
|
||||
point = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
let v = v.min(f64::MAX);
|
||||
(digits > 0).then_some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
|
||||
/// ending it is read).
|
||||
pub fn number(&mut self) -> Option<f64> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
|
||||
if let Some(v) = self.number_here() {
|
||||
return Some(v);
|
||||
}
|
||||
} else {
|
||||
if c == b';' {
|
||||
self.at += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
|
||||
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
|
||||
let mut n = 0;
|
||||
while let Some(v) = self.number() {
|
||||
if let Some(slot) = out.get_mut(n) {
|
||||
*slot = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
n.min(out.len())
|
||||
}
|
||||
|
||||
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
|
||||
pub fn params(&mut self) {
|
||||
loop {
|
||||
while self.number().is_some() {}
|
||||
if self.peek() != Some(b'"') {
|
||||
return;
|
||||
}
|
||||
self.quoted();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
|
||||
/// doesn't know, written out in full).
|
||||
pub fn closed_params(&mut self) -> bool {
|
||||
while self.number().is_some() {}
|
||||
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
|
||||
}
|
||||
|
||||
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
|
||||
/// is one.
|
||||
pub fn comment(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => self.quoted(),
|
||||
Some(b';') => {
|
||||
self.at += 1;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a label, up to and including `terminator` (or the end).
|
||||
pub fn label(&mut self, terminator: u8) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
|
||||
/// there was one.
|
||||
pub fn quoted(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
let found = self.peek() == Some(b'"');
|
||||
if found {
|
||||
self.at += 1;
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
if self.peek() == Some(b';') {
|
||||
self.at += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
|
||||
/// (the semicolon is read).
|
||||
pub fn char(&mut self) -> Option<u8> {
|
||||
let c = self.peek()?;
|
||||
self.at += 1;
|
||||
(c != b';').then_some(c)
|
||||
}
|
||||
|
||||
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
|
||||
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = raw & 0x7f;
|
||||
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b';' => {
|
||||
self.at += 1;
|
||||
return None;
|
||||
}
|
||||
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
|
||||
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
|
||||
self.at += 1;
|
||||
match c {
|
||||
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
|
||||
b'<' => st.up = true,
|
||||
b'>' => match self.pe_value(st) {
|
||||
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
|
||||
None => return self.end_pe(),
|
||||
},
|
||||
b'=' => st.absolute = true,
|
||||
b'7' => st.seven_bit = true,
|
||||
_ => return Some(PeItem::Rect),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let scale = 0.5f64.powi(st.fraction_bits as i32);
|
||||
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
|
||||
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
|
||||
(st.up, st.absolute) = (false, false);
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
|
||||
fn end_pe(&mut self) -> Option<PeItem> {
|
||||
self.skip_pe();
|
||||
None
|
||||
}
|
||||
|
||||
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
|
||||
/// read as instructions.
|
||||
pub fn skip_pe(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
|
||||
/// digit comes first, which is read).
|
||||
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
|
||||
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
|
||||
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
|
||||
let (mut v, mut place) = (0u64, 1u64);
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = if st.seven_bit { raw & 0x7f } else { raw };
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b';' {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
let (digit, last) = if low.contains(&c) {
|
||||
(u64::from(c - 63), false)
|
||||
} else if high.contains(&c) {
|
||||
(u64::from(c - high.start()), true)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
v = v.saturating_add(digit.saturating_mul(place));
|
||||
place = place.saturating_mul(base);
|
||||
if last {
|
||||
// The low bit is the sign.
|
||||
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
|
||||
return Some(if v & 1 == 1 { -n } else { n });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//! Shared HP-GL byte lexer; drawing interpretation remains local.
|
||||
pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem};
|
||||
@@ -596,6 +596,9 @@ struct Walk<'a> {
|
||||
clips: Vec<Region>,
|
||||
/// The points those masks hold ([`MAX_MASK_POINTS`]).
|
||||
mask_points: usize,
|
||||
/// Set while the stroke pieces of a clipping path whose fill paints are drawn: they close, as
|
||||
/// its fill closes its outline.
|
||||
closing: bool,
|
||||
runs: Vec<Run>,
|
||||
points: usize,
|
||||
clip_tests: u64,
|
||||
@@ -624,6 +627,7 @@ impl<'a> Walk<'a> {
|
||||
tolerance,
|
||||
clips: vec![],
|
||||
mask_points: 0,
|
||||
closing: false,
|
||||
runs: vec![],
|
||||
points: 0,
|
||||
clip_tests: 0,
|
||||
@@ -827,7 +831,9 @@ impl<'a> Walk<'a> {
|
||||
let mut paint = first.clip_paint();
|
||||
// A stroke at 0% opacity isn't drawn, so the clipping path is drawn in its fill.
|
||||
let type_stroke = |s: &Node| matches!(&s.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.has_stroke()));
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s));
|
||||
// The strokes of a clipping path whose stroke effects were applied are a group of pieces,
|
||||
// which effects around it may have put in groups of their own.
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s) || strokes_in_pieces(s));
|
||||
if paint.stroke.is_none()
|
||||
&& let Some(fill) = &paint.fill
|
||||
{
|
||||
@@ -852,9 +858,16 @@ impl<'a> Walk<'a> {
|
||||
None => {}
|
||||
}
|
||||
// Drawn whole where its stroke paints: a fill closes its outline, and type's characters
|
||||
// without a stroke are drawn too.
|
||||
if paint.stroke.is_some() {
|
||||
self.node(first, false);
|
||||
// without a stroke are drawn too. Pieces of a clipping path whose fill and stroke effects
|
||||
// were applied are drawn in its stroke pieces alone, closed where its fill paints.
|
||||
if let Some(stroke) = &paint.stroke {
|
||||
if first.extras().clip_pieces {
|
||||
let closing = std::mem::replace(&mut self.closing, paint.fill.as_ref().is_some_and(fills_in_pieces));
|
||||
self.node(stroke, false);
|
||||
self.closing = closing;
|
||||
} else {
|
||||
self.node(first, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,7 +887,8 @@ impl<'a> Walk<'a> {
|
||||
|
||||
/// A path drawn in its color: the topmost stroke's that paints, else the topmost fill's that
|
||||
/// paints (visible, with a paint and some opacity). A filled path's every subpath is closed,
|
||||
/// as its fill closes it, also when its stroke gives the color.
|
||||
/// as its fill closes it, also when its stroke gives the color, and so is each stroke piece
|
||||
/// of a clipping path whose fill paints ([`Walk::closing`]).
|
||||
fn shape(&mut self, n: &Node, bp: &BezPath) {
|
||||
if bp.elements().is_empty() {
|
||||
return;
|
||||
@@ -896,7 +910,7 @@ impl<'a> Walk<'a> {
|
||||
(None, None) => return,
|
||||
};
|
||||
let rgb = self.flat(paint);
|
||||
self.draw(rgb, bp, fill.is_some());
|
||||
self.draw(rgb, bp, fill.is_some() || self.closing);
|
||||
}
|
||||
|
||||
/// `bp` drawn in `rgb`: flattened (with `close` every subpath closed), then cut and added.
|
||||
@@ -1024,6 +1038,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
|
||||
@@ -1126,6 +1160,18 @@ fn top_stroke(n: &Node) -> Option<&StrokeLayer> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a stroke that paints ([`top_stroke`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn strokes_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_stroke(c).is_some() || strokes_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a fill that paints ([`top_fill`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn fills_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_fill(c).is_some() || fills_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// The paint of the topmost fill of `n` that paints: visible, with a paint and some opacity.
|
||||
fn top_fill(n: &Node) -> Option<&Paint> {
|
||||
n.appearance.items.iter().rev().find_map(|i| match i {
|
||||
|
||||
@@ -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]
|
||||
@@ -663,6 +747,86 @@ fn a_clipping_path_is_drawn_where_it_paints() {
|
||||
});
|
||||
let t = text(&plot(&open_doc, &opts(&open_doc)));
|
||||
assert!(t.ends_with("SP2;PU282,1129;PD564,1129,564,847,282,1129;PU;SP0;"), "{t}");
|
||||
// A stroke with a geometry effect of its own is drawn once, over the art it clips, in its color.
|
||||
let moved = doc_with(|d| {
|
||||
let (blue, red) = (Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)));
|
||||
let mut clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::basic(blue, red, 1.0));
|
||||
for item in &mut clip.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
});
|
||||
assert_eq!(plot(&moved, &opts(&moved)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// So are the stroke's pieces when an effect around them put them in a group of their own.
|
||||
let grouped = |opacity: f32| {
|
||||
doc_with(|d| {
|
||||
// One path for each, carrying only that fill or stroke.
|
||||
let piece = |d: &mut Document, fill: bool| {
|
||||
let mut a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
a.items.retain(|i| matches!(i, AppearanceItem::Fill(_)) == fill);
|
||||
Arc::new(Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), a))
|
||||
};
|
||||
let (fill, stroke) = (piece(d, true), piece(d, false));
|
||||
let mut copies = Node::group(d.alloc_id(), vec![stroke]);
|
||||
copies.opacity = opacity;
|
||||
let mut clip = Node::group(d.alloc_id(), vec![fill, Arc::new(copies)]);
|
||||
clip.extras_mut().clip_pieces = true;
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let shown = grouped(1.0);
|
||||
assert_eq!(plot(&shown, &opts(&shown)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// In a group at 0% opacity they are not drawn, and the clipping path is drawn in its fill.
|
||||
let faded = grouped(0.0);
|
||||
assert_eq!(plot(&faded, &opts(&faded)).pens, [[0, 0, 255], [0, 0, 0]]);
|
||||
// An open clipping path with a fill is drawn closed also where its stroke's effect moved it.
|
||||
let open_moved = |fill_opacity: f32| {
|
||||
doc_with(|d| {
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((20.0, 20.0));
|
||||
open.line_to((40.0, 20.0));
|
||||
open.line_to((40.0, 40.0));
|
||||
let a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
let mut clip = Node::path(d.alloc_id(), PathData::from_bezpath(&open), a);
|
||||
for item in &mut clip.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.opacity = fill_opacity,
|
||||
AppearanceItem::Stroke(s) => {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let filled = open_moved(1.0);
|
||||
let t = text(&plot(&filled, &opts(&filled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847,353,1129;PU;SP0;"), "{t}");
|
||||
// A fill at 0% opacity does not close it.
|
||||
let unfilled = open_moved(0.0);
|
||||
let t = text(&plot(&unfilled, &opts(&unfilled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847;PU;SP0;"), "{t}");
|
||||
}
|
||||
|
||||
/// A symbol `art` and an instance of it at its place.
|
||||
|
||||
+20
-19
@@ -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
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
+24
-7
@@ -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 DXF writer (versions R12 to 2018) on `craft_dxf::drawing` 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,11 +11,11 @@
|
||||
//! 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.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
@@ -24,7 +24,6 @@ mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -136,11 +135,27 @@ impl DxfVersion {
|
||||
self >= Self::R2004
|
||||
}
|
||||
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
|
||||
fn utf8(self) -> bool {
|
||||
pub fn utf8(self) -> bool {
|
||||
self >= Self::R2007
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DxfVersion> for craft_dxf::drawing::Format {
|
||||
fn from(v: DxfVersion) -> Self {
|
||||
match v {
|
||||
DxfVersion::R12 => Self::R12,
|
||||
DxfVersion::R13 => Self::R13,
|
||||
DxfVersion::R14 => Self::R14,
|
||||
DxfVersion::R2000 => Self::R2000,
|
||||
DxfVersion::R2004 => Self::R2004,
|
||||
DxfVersion::R2007 => Self::R2007,
|
||||
DxfVersion::R2010 => Self::R2010,
|
||||
DxfVersion::R2013 => Self::R2013,
|
||||
DxfVersion::R2018 => Self::R2018,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
|
||||
/// (with the nearest index for apps that read only the index).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -428,7 +443,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 layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
Ok(scene::Scene::new(doc, opts).run())
|
||||
}
|
||||
|
||||
+25
-24
@@ -5,7 +5,6 @@
|
||||
//! filled outlines where the look needs them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Cursor;
|
||||
|
||||
use kurbo::PathEl;
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -14,8 +13,8 @@ use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
|
||||
use crate::aci::nearest_aci;
|
||||
use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed};
|
||||
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
|
||||
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
|
||||
/// Curves are flattened to within this distance (points) where DXF needs straight segments
|
||||
/// (hatch boundaries, R12 polylines).
|
||||
@@ -543,7 +542,7 @@ impl<'a> Scene<'a> {
|
||||
o,
|
||||
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
|
||||
k,
|
||||
e: Codes::new(o.version),
|
||||
e: Codes::new(o.version.into()),
|
||||
next: fixed::FIRST_FREE,
|
||||
layers: vec![],
|
||||
layer_names: Names::with(&["0", "Defpoints"]),
|
||||
@@ -551,7 +550,7 @@ impl<'a> Scene<'a> {
|
||||
flags: LayerFlags { off: false, locked: false, plot: true },
|
||||
linetypes: vec![],
|
||||
styles: vec![],
|
||||
style_names: Names::with(&[crate::writer::STANDARD_STYLE]),
|
||||
style_names: Names::with(&[STANDARD_STYLE]),
|
||||
images: vec![],
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
@@ -579,7 +578,7 @@ impl<'a> Scene<'a> {
|
||||
let one = (self.o.scale - 1.0).abs() < 1e-12;
|
||||
let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 };
|
||||
let drawing = Drawing {
|
||||
version: self.o.version,
|
||||
version: self.o.version.into(),
|
||||
layers: self.layers,
|
||||
linetypes: self.linetypes,
|
||||
styles: self.styles,
|
||||
@@ -683,7 +682,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));
|
||||
@@ -1403,35 +1402,37 @@ impl<'a> Scene<'a> {
|
||||
|
||||
/// Image `im` as a file in the chosen format, and its size in pixels.
|
||||
fn encode_image(&self, im: &ImageObject) -> Result<(DxfImage, (u32, u32)), String> {
|
||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType};
|
||||
let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()).ok_or_else(|| "an image has no pixels and was left out".to_string())?;
|
||||
// The pixels it converts to (RGBA, 4 bytes each) are read from its header before decoding.
|
||||
let (w, h) = image::ImageReader::new(Cursor::new(blob.bytes.as_slice()))
|
||||
.with_guessed_format()
|
||||
.ok()
|
||||
.and_then(|r| r.into_dimensions().ok())
|
||||
.ok_or_else(|| UNDECODED.to_string())?;
|
||||
let (w, h) = vectorcraft_doc::header_size(&blob.bytes).ok_or_else(|| UNDECODED.to_string())?;
|
||||
if u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS {
|
||||
return Err("an image is too large for DXF and was left out".to_string());
|
||||
}
|
||||
let img = image::load_from_memory(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
|
||||
let size = (img.width(), img.height());
|
||||
let mut bytes = vec![];
|
||||
let written = match self.o.raster {
|
||||
RasterFormat::Png => img.to_rgba8().write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png),
|
||||
let decoded = craft_image_codecs::decode(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
|
||||
let size = decoded.dimensions();
|
||||
let mut rgba = decoded.to_rgba8();
|
||||
let bytes = match self.o.raster {
|
||||
RasterFormat::Png => {
|
||||
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgba, SampleType::U8, rgba)
|
||||
.map_err(|e| format!("an image could not be written: {e}"))?;
|
||||
craft_image_codecs::encode(&img, Format::Png, &EncodeOptions::default())
|
||||
}
|
||||
RasterFormat::Jpeg => {
|
||||
// No alpha in JPEG: transparent pixels over white.
|
||||
let mut rgba = img.to_rgba8();
|
||||
for p in rgba.pixels_mut() {
|
||||
let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
|
||||
for p in rgba.as_chunks_mut::<4>().0 {
|
||||
let a = u32::from(p[3]);
|
||||
for c in 0..3 {
|
||||
p[c] = ((u32::from(p[c]) * a + 255 * (255 - a)) / 255) as u8;
|
||||
for c in &p[..3] {
|
||||
rgb.push(((u32::from(*c) * a + 255 * (255 - a)) / 255) as u8);
|
||||
}
|
||||
}
|
||||
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
|
||||
rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90))
|
||||
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgb, SampleType::U8, rgb)
|
||||
.map_err(|e| format!("an image could not be written: {e}"))?;
|
||||
craft_image_codecs::encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 90, ..EncodeOptions::default() })
|
||||
}
|
||||
};
|
||||
written.map_err(|e| format!("an image could not be written: {e}"))?;
|
||||
}
|
||||
.map_err(|e| format!("an image could not be written: {e}"))?;
|
||||
Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size))
|
||||
}
|
||||
}
|
||||
|
||||
+84
-4
@@ -852,8 +852,19 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
|
||||
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
|
||||
/// `fill`'s rectangle.
|
||||
fn image_and_fill_doc(fill: Paint) -> Document {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 0, 255, 255].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
@@ -1312,8 +1323,19 @@ fn a_font_height_reference_is_written_as_the_size_drawn() {
|
||||
|
||||
#[test]
|
||||
fn images_link_png_or_jpeg_files() {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[255u8, 0, 0, 128].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
@@ -1395,6 +1417,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
|
||||
@@ -1413,3 +1473,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
|
||||
let cases: [(&str, DxfVersion, Document); 2] =
|
||||
[("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())];
|
||||
for (name, version, doc) in cases {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,674 +0,0 @@
|
||||
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
|
||||
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
|
||||
//! add layouts and plot styles, which CAD apps expect to find.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::DxfVersion;
|
||||
|
||||
/// An object handle (written in hex).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Handle(pub u32);
|
||||
|
||||
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
|
||||
/// [`FIRST_FREE`].
|
||||
pub(crate) mod fixed {
|
||||
use super::Handle;
|
||||
pub const LAYER_TABLE: Handle = Handle(0x1);
|
||||
pub const LTYPE_TABLE: Handle = Handle(0x2);
|
||||
pub const APPID_TABLE: Handle = Handle(0x3);
|
||||
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
|
||||
pub const STYLE_TABLE: Handle = Handle(0x5);
|
||||
pub const UCS_TABLE: Handle = Handle(0x6);
|
||||
pub const VIEW_TABLE: Handle = Handle(0x7);
|
||||
pub const VPORT_TABLE: Handle = Handle(0x8);
|
||||
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
|
||||
pub const ROOT: Handle = Handle(0xA);
|
||||
pub const GROUPS: Handle = Handle(0xB);
|
||||
pub const LAYOUTS: Handle = Handle(0xC);
|
||||
pub const MODEL_RECORD: Handle = Handle(0xD);
|
||||
pub const PAPER_RECORD: Handle = Handle(0xE);
|
||||
pub const MODEL_BLOCK: Handle = Handle(0xF);
|
||||
pub const MODEL_END: Handle = Handle(0x10);
|
||||
pub const PAPER_BLOCK: Handle = Handle(0x11);
|
||||
pub const PAPER_END: Handle = Handle(0x12);
|
||||
pub const MODEL_LAYOUT: Handle = Handle(0x13);
|
||||
pub const PAPER_LAYOUT: Handle = Handle(0x14);
|
||||
pub const ACTIVE_VPORT: Handle = Handle(0x15);
|
||||
pub const ACAD_APPID: Handle = Handle(0x16);
|
||||
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
|
||||
pub const IMAGE_DICT: Handle = Handle(0x18);
|
||||
pub const IMAGE_VARS: Handle = Handle(0x19);
|
||||
pub const PLOT_STYLES: Handle = Handle(0x1A);
|
||||
pub const PLOT_NORMAL: Handle = Handle(0x1B);
|
||||
pub const FIRST_FREE: u32 = 0x30;
|
||||
}
|
||||
|
||||
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
|
||||
pub(crate) fn num(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{v:.6}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
|
||||
}
|
||||
|
||||
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
|
||||
/// every character outside ASCII as `\U+XXXX`.
|
||||
pub(crate) fn text(s: &str, utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\r' | '\n' | '\t' => out.push(' '),
|
||||
c if c.is_control() => {}
|
||||
'^' => out.push_str("^ "),
|
||||
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
|
||||
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
|
||||
Err(_) => out.push('?'),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Group-code/value pairs in the order they are written.
|
||||
pub(crate) struct Codes {
|
||||
pub v: DxfVersion,
|
||||
out: String,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
pub fn new(v: DxfVersion) -> Self {
|
||||
Self { v, out: String::new() }
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.out
|
||||
}
|
||||
|
||||
pub fn append(&mut self, other: &str) {
|
||||
self.out.push_str(other);
|
||||
}
|
||||
|
||||
/// A value written as it is (names and keywords the writer itself chose).
|
||||
pub fn raw(&mut self, code: u16, value: &str) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
/// Text from the document, encoded for the version (see [`text`]).
|
||||
pub fn str(&mut self, code: u16, value: &str) {
|
||||
let t = text(value, self.v.utf8());
|
||||
self.raw(code, &t);
|
||||
}
|
||||
|
||||
pub fn int(&mut self, code: u16, value: i64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
pub fn num(&mut self, code: u16, value: f64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, code: u16, h: Handle) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
|
||||
}
|
||||
|
||||
/// A 2D point at `code` (x), `code + 10` (y).
|
||||
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.num(code, x);
|
||||
self.num(code + 10, y);
|
||||
}
|
||||
|
||||
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
|
||||
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.xy(code, x, y);
|
||||
self.num(code + 20, 0.0);
|
||||
}
|
||||
|
||||
/// The extrusion direction of planar entities: the z axis.
|
||||
pub fn normal(&mut self) {
|
||||
self.num(210, 0.0);
|
||||
self.num(220, 0.0);
|
||||
self.num(230, 1.0);
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
self.raw(0, kind);
|
||||
if self.v.handles() {
|
||||
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
|
||||
self.handle(330, owner);
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table entry: the shared record subclass, then the table's own (from R13).
|
||||
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
|
||||
self.object(kind, h, table, "AcDbSymbolTableRecord");
|
||||
if self.v.handles() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, name: &str) {
|
||||
self.raw(0, "SECTION");
|
||||
self.raw(2, name);
|
||||
}
|
||||
|
||||
fn end_section(&mut self) {
|
||||
self.raw(0, "ENDSEC");
|
||||
}
|
||||
|
||||
fn table(&mut self, name: &str, h: Handle, count: usize) {
|
||||
self.raw(0, "TABLE");
|
||||
self.raw(2, name);
|
||||
if self.v.handles() {
|
||||
self.handle(5, h);
|
||||
self.raw(330, "0");
|
||||
self.raw(100, "AcDbSymbolTable");
|
||||
}
|
||||
self.int(70, count as i64);
|
||||
if name == "DIMSTYLE" && self.v.r2000() {
|
||||
self.raw(100, "AcDbDimStyleTable");
|
||||
}
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
self.raw(0, "ENDTAB");
|
||||
}
|
||||
}
|
||||
|
||||
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct EntityStyle {
|
||||
pub aci: u8,
|
||||
/// `0xRRGGBB` (DXF 2004 and later).
|
||||
pub rgb: Option<u32>,
|
||||
/// Hundredths of a millimetre (DXF 2000 and later).
|
||||
pub lineweight: Option<i32>,
|
||||
pub linetype: Option<String>,
|
||||
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
|
||||
pub alpha: Option<u8>,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
|
||||
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
|
||||
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
|
||||
self.object(kind, h, owner, "AcDbEntity");
|
||||
self.str(8, layer);
|
||||
if let Some(lt) = &style.linetype {
|
||||
self.str(6, lt);
|
||||
}
|
||||
self.int(62, i64::from(style.aci.max(1)));
|
||||
if self.v.r2000()
|
||||
&& let Some(lw) = style.lineweight
|
||||
{
|
||||
self.int(370, i64::from(lw));
|
||||
}
|
||||
if self.v.true_color() {
|
||||
if let Some(rgb) = style.rgb {
|
||||
self.int(420, i64::from(rgb));
|
||||
}
|
||||
if let Some(a) = style.alpha {
|
||||
self.int(440, 0x0200_0000 | i64::from(a));
|
||||
}
|
||||
}
|
||||
if self.v.handles() && !subclass.is_empty() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DXF layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Layer {
|
||||
pub name: String,
|
||||
pub aci: u8,
|
||||
/// Switched off (a hidden layer).
|
||||
pub off: bool,
|
||||
pub locked: bool,
|
||||
/// Plotted (printable).
|
||||
pub plot: bool,
|
||||
}
|
||||
|
||||
/// A dash pattern: dash, gap, dash… lengths in drawing units.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LineType {
|
||||
pub name: String,
|
||||
pub pattern: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A placed image file and the image entities that show it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageDef {
|
||||
pub name: String,
|
||||
pub size: (u32, u32),
|
||||
pub handle: Handle,
|
||||
/// `(reactor, image entity)` per image entity.
|
||||
pub reactors: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
/// Everything around the entities, collected while they were written.
|
||||
pub(crate) struct Drawing {
|
||||
pub version: DxfVersion,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<LineType>,
|
||||
/// Text styles: (style name, font family).
|
||||
pub styles: Vec<(String, String)>,
|
||||
pub images: Vec<ImageDef>,
|
||||
/// The entities' group codes.
|
||||
pub entities: String,
|
||||
/// `[x0, y0, x1, y1]` of everything written (drawing units).
|
||||
pub extents: [f64; 4],
|
||||
/// The export region (drawing units).
|
||||
pub limits: [f64; 4],
|
||||
/// `$INSUNITS`.
|
||||
pub insunits: u8,
|
||||
pub metric: bool,
|
||||
/// The next free handle.
|
||||
pub next: u32,
|
||||
}
|
||||
|
||||
/// The text style every drawing has.
|
||||
pub(crate) const STANDARD_STYLE: &str = "Standard";
|
||||
|
||||
impl Drawing {
|
||||
/// The whole file.
|
||||
pub fn write(self) -> String {
|
||||
let v = self.version;
|
||||
let mut c = Codes::new(v);
|
||||
// Table entries get the handles after the entities'.
|
||||
let mut next = self.next;
|
||||
let mut take = |n: usize| {
|
||||
let start = next;
|
||||
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
|
||||
start
|
||||
};
|
||||
let ltype_base = take(3 + self.linetypes.len());
|
||||
let layer_base = take(1 + self.layers.len());
|
||||
let style_base = take(1 + self.styles.len());
|
||||
self.header(&mut c, next);
|
||||
if v.handles() {
|
||||
self.classes(&mut c);
|
||||
}
|
||||
c.section("TABLES");
|
||||
self.vport(&mut c);
|
||||
self.ltypes(&mut c, ltype_base);
|
||||
self.layer_table(&mut c, layer_base);
|
||||
self.style_table(&mut c, style_base);
|
||||
if v.handles() {
|
||||
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
|
||||
c.table(name, h, 0);
|
||||
c.end_table();
|
||||
}
|
||||
c.table("APPID", fixed::APPID_TABLE, 1);
|
||||
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
|
||||
c.raw(2, "ACAD");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
|
||||
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
|
||||
c.raw(2, "Standard");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
|
||||
for (name, h, layout) in
|
||||
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
|
||||
{
|
||||
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
|
||||
c.raw(2, name);
|
||||
if v.r2000() {
|
||||
c.handle(340, layout);
|
||||
c.int(70, 0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
c.section("BLOCKS");
|
||||
for (name, record, begin, end) in [
|
||||
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
|
||||
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
|
||||
] {
|
||||
c.object("BLOCK", begin, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockBegin");
|
||||
c.raw(2, name);
|
||||
c.int(70, 0);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
c.raw(3, name);
|
||||
c.raw(1, "");
|
||||
c.object("ENDBLK", end, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
c.section("ENTITIES");
|
||||
c.append(&self.entities);
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
self.objects(&mut c);
|
||||
}
|
||||
c.raw(0, "EOF");
|
||||
c.into_string()
|
||||
}
|
||||
|
||||
fn header(&self, c: &mut Codes, handseed: u32) {
|
||||
let v = self.version;
|
||||
let var = |c: &mut Codes, name: &str| c.raw(9, name);
|
||||
c.section("HEADER");
|
||||
var(c, "$ACADVER");
|
||||
c.raw(1, v.acadver());
|
||||
var(c, "$DWGCODEPAGE");
|
||||
c.raw(3, "ANSI_1252");
|
||||
var(c, "$INSBASE");
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
var(c, "$EXTMIN");
|
||||
c.xyz(10, x0, y0);
|
||||
var(c, "$EXTMAX");
|
||||
c.xyz(10, x1, y1);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
var(c, "$LIMMIN");
|
||||
c.xy(10, lx0, ly0);
|
||||
var(c, "$LIMMAX");
|
||||
c.xy(10, lx1, ly1);
|
||||
if v.r2000() {
|
||||
var(c, "$LWDISPLAY");
|
||||
c.int(290, 1);
|
||||
var(c, "$INSUNITS");
|
||||
c.int(70, i64::from(self.insunits));
|
||||
var(c, "$MEASUREMENT");
|
||||
c.int(70, i64::from(self.metric));
|
||||
}
|
||||
if v.handles() {
|
||||
var(c, "$HANDSEED");
|
||||
c.handle(5, Handle(handseed));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
fn classes(&self, c: &mut Codes) {
|
||||
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
|
||||
if self.version.r2000() {
|
||||
classes.extend([
|
||||
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
|
||||
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
|
||||
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
|
||||
]);
|
||||
}
|
||||
if !self.images.is_empty() {
|
||||
classes.extend([
|
||||
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
|
||||
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
|
||||
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
|
||||
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
|
||||
]);
|
||||
}
|
||||
c.section("CLASSES");
|
||||
for (name, cpp, app, flags, entity) in classes {
|
||||
c.raw(0, "CLASS");
|
||||
c.raw(1, name);
|
||||
c.raw(2, cpp);
|
||||
c.raw(3, app);
|
||||
c.int(90, flags);
|
||||
if self.version.true_color() {
|
||||
c.int(91, 0);
|
||||
}
|
||||
c.int(280, 0);
|
||||
c.int(281, i64::from(entity));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// The active viewport, zoomed to the drawing's extents.
|
||||
fn vport(&self, c: &mut Codes) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.table("VPORT", fixed::VPORT_TABLE, 1);
|
||||
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
|
||||
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
|
||||
c.int(70, 0);
|
||||
c.xy(10, 0.0, 0.0);
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
c.xy(13, 0.0, 0.0);
|
||||
c.xy(14, 1.0, 1.0);
|
||||
c.xy(15, 10.0, 10.0);
|
||||
// The view direction looks down the z axis: (0, 0, 1), each code once.
|
||||
c.xy(16, 0.0, 0.0);
|
||||
c.num(36, 1.0);
|
||||
c.xyz(17, 0.0, 0.0);
|
||||
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
// The view's height, with a margin; its width follows from the aspect ratio.
|
||||
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
|
||||
c.num(41, 1.5);
|
||||
c.num(42, 50.0);
|
||||
c.num(43, 0.0);
|
||||
c.num(44, 0.0);
|
||||
c.num(50, 0.0);
|
||||
c.num(51, 0.0);
|
||||
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
|
||||
c.int(code, value);
|
||||
}
|
||||
if self.version.r2000() {
|
||||
c.int(281, 0);
|
||||
c.int(65, 0);
|
||||
c.num(146, 0.0);
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn ltypes(&self, c: &mut Codes, base: u32) {
|
||||
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
|
||||
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
|
||||
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
|
||||
for (i, (name, desc, pattern)) in rows.enumerate() {
|
||||
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
|
||||
c.int(72, 65);
|
||||
c.int(73, pattern.len() as i64);
|
||||
c.num(40, pattern.iter().map(|v| v.abs()).sum());
|
||||
for v in pattern {
|
||||
c.num(49, *v);
|
||||
if self.version.handles() {
|
||||
c.int(74, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn layer_table(&self, c: &mut Codes, base: u32) {
|
||||
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
|
||||
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
|
||||
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
|
||||
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
|
||||
c.str(2, &l.name);
|
||||
c.int(70, if l.locked { 4 } else { 0 });
|
||||
// A negative colour switches the layer off.
|
||||
let aci = i64::from(l.aci.max(1));
|
||||
c.int(62, if l.off { -aci } else { aci });
|
||||
c.raw(6, "Continuous");
|
||||
if self.version.r2000() {
|
||||
c.int(290, i64::from(l.plot));
|
||||
c.int(370, -3);
|
||||
c.handle(390, fixed::PLOT_NORMAL);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn style_table(&self, c: &mut Codes, base: u32) {
|
||||
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
|
||||
let standard = (STANDARD_STYLE.to_string(), String::new());
|
||||
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
|
||||
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.num(40, 0.0);
|
||||
c.num(41, 1.0);
|
||||
c.num(50, 0.0);
|
||||
c.int(71, 0);
|
||||
c.num(42, 2.5);
|
||||
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
|
||||
if family.is_empty() {
|
||||
c.raw(3, "txt");
|
||||
} else {
|
||||
c.str(3, &format!("{family}.ttf"));
|
||||
}
|
||||
c.raw(4, "");
|
||||
if self.version.r2000() && !family.is_empty() {
|
||||
c.raw(1001, "ACAD");
|
||||
c.str(1000, family);
|
||||
c.int(1071, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn objects(&self, c: &mut Codes) {
|
||||
let v = self.version;
|
||||
let images = !self.images.is_empty();
|
||||
c.section("OBJECTS");
|
||||
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
|
||||
c.object("DICTIONARY", h, owner, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
for (name, e) in entries {
|
||||
c.str(3, name);
|
||||
c.handle(350, *e);
|
||||
}
|
||||
};
|
||||
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
|
||||
if images {
|
||||
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
|
||||
}
|
||||
if v.r2000() {
|
||||
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
|
||||
}
|
||||
dict(c, fixed::ROOT, Handle(0), &root);
|
||||
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
|
||||
if v.r2000() {
|
||||
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
|
||||
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
c.raw(3, "Normal");
|
||||
c.handle(350, fixed::PLOT_NORMAL);
|
||||
c.raw(100, "AcDbDictionaryWithDefault");
|
||||
c.handle(340, fixed::PLOT_NORMAL);
|
||||
// A placeholder has no data and no subclass marker of its own.
|
||||
c.raw(0, "ACDBPLACEHOLDER");
|
||||
c.handle(5, fixed::PLOT_NORMAL);
|
||||
c.handle(330, fixed::PLOT_STYLES);
|
||||
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
|
||||
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
|
||||
}
|
||||
if images {
|
||||
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
|
||||
c.int(90, 0);
|
||||
c.int(70, 0);
|
||||
c.int(71, 1);
|
||||
c.int(72, 0);
|
||||
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
|
||||
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
|
||||
for img in &self.images {
|
||||
c.raw(0, "IMAGEDEF");
|
||||
c.handle(5, img.handle);
|
||||
c.raw(102, "{ACAD_REACTORS");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
for (reactor, _) in &img.reactors {
|
||||
c.handle(330, *reactor);
|
||||
}
|
||||
c.raw(102, "}");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
c.raw(100, "AcDbRasterImageDef");
|
||||
c.int(90, 0);
|
||||
c.str(1, &img.name);
|
||||
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
for (reactor, image) in &img.reactors {
|
||||
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
|
||||
c.int(90, 2);
|
||||
c.handle(330, *image);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
|
||||
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
|
||||
c.raw(1, "");
|
||||
c.raw(2, "none_device");
|
||||
c.raw(4, "");
|
||||
c.raw(6, "");
|
||||
for code in 40..=49 {
|
||||
c.num(code, 0.0);
|
||||
}
|
||||
c.num(140, 0.0);
|
||||
c.num(141, 0.0);
|
||||
c.num(142, 1.0);
|
||||
c.num(143, 1.0);
|
||||
// Plot flags; 1024 marks the model space layout.
|
||||
c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 });
|
||||
c.int(72, 1);
|
||||
c.int(73, 0);
|
||||
c.int(74, 5);
|
||||
c.raw(7, "");
|
||||
c.int(75, 16);
|
||||
if self.version.true_color() {
|
||||
// Shade plot mode (as displayed), resolution level (normal) and custom DPI.
|
||||
c.int(76, 0);
|
||||
c.int(77, 2);
|
||||
c.int(78, 300);
|
||||
}
|
||||
c.num(147, 1.0);
|
||||
// The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158.
|
||||
c.num(148, 0.0);
|
||||
c.num(149, 0.0);
|
||||
c.raw(100, "AcDbLayout");
|
||||
c.raw(1, name);
|
||||
c.int(70, 1);
|
||||
c.int(71, tab);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
c.xy(10, lx0, ly0);
|
||||
c.xy(11, lx1, ly1);
|
||||
c.xyz(12, 0.0, 0.0);
|
||||
c.xyz(14, x0, y0);
|
||||
c.xyz(15, x1, y1);
|
||||
c.num(146, 0.0);
|
||||
c.xyz(13, 0.0, 0.0);
|
||||
c.xyz(16, 1.0, 0.0);
|
||||
c.xyz(17, 0.0, 1.0);
|
||||
c.int(76, 1);
|
||||
c.handle(330, record);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_and_text_are_written_plainly() {
|
||||
assert_eq!(num(1.5), "1.5");
|
||||
assert_eq!(num(-0.0000001), "0");
|
||||
assert_eq!(num(2.0), "2");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(text("a^b\nc", true), "a^ b c");
|
||||
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
|
||||
assert_eq!(text("Größe", true), "Größe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
9
|
||||
$DWGCODEPAGE
|
||||
3
|
||||
ANSI_1252
|
||||
9
|
||||
$INSBASE
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMIN
|
||||
10
|
||||
10
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMAX
|
||||
10
|
||||
180
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
9
|
||||
$LIMMIN
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
9
|
||||
$LIMMAX
|
||||
10
|
||||
200
|
||||
20
|
||||
100
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
VPORT
|
||||
70
|
||||
1
|
||||
0
|
||||
VPORT
|
||||
2
|
||||
*ACTIVE
|
||||
70
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
12
|
||||
95
|
||||
22
|
||||
55
|
||||
13
|
||||
0
|
||||
23
|
||||
0
|
||||
14
|
||||
1
|
||||
24
|
||||
1
|
||||
15
|
||||
10
|
||||
25
|
||||
10
|
||||
16
|
||||
0
|
||||
26
|
||||
0
|
||||
36
|
||||
1
|
||||
17
|
||||
0
|
||||
27
|
||||
0
|
||||
37
|
||||
0
|
||||
40
|
||||
124.666667
|
||||
41
|
||||
1.5
|
||||
42
|
||||
50
|
||||
43
|
||||
0
|
||||
44
|
||||
0
|
||||
50
|
||||
0
|
||||
51
|
||||
0
|
||||
71
|
||||
0
|
||||
72
|
||||
1000
|
||||
73
|
||||
1
|
||||
74
|
||||
3
|
||||
75
|
||||
0
|
||||
76
|
||||
0
|
||||
77
|
||||
0
|
||||
78
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
3
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByBlock
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByLayer
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
Continuous
|
||||
70
|
||||
0
|
||||
3
|
||||
Solid line
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LAYER
|
||||
70
|
||||
2
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
0
|
||||
70
|
||||
0
|
||||
62
|
||||
7
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
LAYER_1
|
||||
70
|
||||
0
|
||||
62
|
||||
171
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
STYLE
|
||||
70
|
||||
1
|
||||
0
|
||||
STYLE
|
||||
2
|
||||
Standard
|
||||
70
|
||||
0
|
||||
40
|
||||
0
|
||||
41
|
||||
1
|
||||
50
|
||||
0
|
||||
71
|
||||
0
|
||||
42
|
||||
2.5
|
||||
3
|
||||
txt
|
||||
4
|
||||
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
1
|
||||
41
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
2
|
||||
41
|
||||
2
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
120
|
||||
20
|
||||
50
|
||||
30
|
||||
0
|
||||
42
|
||||
-2.414214
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
150
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
42
|
||||
-0.414214
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
File diff suppressed because it is too large.
Load diff
+206
-16
@@ -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};
|
||||
|
||||
@@ -89,6 +94,50 @@ impl Intent {
|
||||
}
|
||||
}
|
||||
|
||||
/// A color management policy (Edit → Color Settings): what opening a document does with a profile
|
||||
/// it is tagged with that is not the working space of its model.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Policy {
|
||||
/// The document loses the profile; its color numbers stay as they are.
|
||||
Off,
|
||||
/// The document keeps the profile.
|
||||
#[default]
|
||||
PreserveEmbedded,
|
||||
/// The colors are converted from the profile into the working space, which keeps their
|
||||
/// appearance, and the document loses the profile.
|
||||
Convert,
|
||||
/// CMYK only: the document loses the profile; its color numbers stay as they are.
|
||||
PreserveNumbers,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// The RGB policies, in menu order.
|
||||
pub const RGB: [Policy; 3] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert];
|
||||
/// The CMYK policies, in menu order.
|
||||
pub const CMYK: [Policy; 4] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers];
|
||||
/// Parse an id of [`Policy::id`].
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers].into_iter().find(|p| p.id() == s)
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "off",
|
||||
Policy::PreserveEmbedded => "preserveEmbedded",
|
||||
Policy::Convert => "convert",
|
||||
Policy::PreserveNumbers => "preserveNumbers",
|
||||
}
|
||||
}
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "Off",
|
||||
Policy::PreserveEmbedded => "Preserve Embedded Profiles",
|
||||
Policy::Convert => "Convert to Working Space",
|
||||
Policy::PreserveNumbers => "Preserve Numbers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProfileKind {
|
||||
@@ -129,11 +178,25 @@ pub struct ColorSettings {
|
||||
pub intent: Intent,
|
||||
/// Black-point compensation.
|
||||
pub bpc: bool,
|
||||
/// The color management policy for RGB profiles (one of [`Policy::RGB`]). Settings saved
|
||||
/// without one take the default.
|
||||
#[serde(default)]
|
||||
pub rgb_policy: Policy,
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
fn default() -> Self {
|
||||
Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
|
||||
Self {
|
||||
rgb: SRGB.into(),
|
||||
cmyk: GENERIC_CMYK.into(),
|
||||
intent: Intent::RelativeColorimetric,
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,6 +576,41 @@ impl Cms {
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let icc = |s: &RgbSpace| match s {
|
||||
RgbSpace::Icc(p) => Some(p.clone()),
|
||||
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
|
||||
};
|
||||
let [r, g, b] = icc(&self.rgb)
|
||||
.zip(icc(&dest.rgb))
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &[r, g, b], intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| dest.srgb_to_rgb(self.rgb_to_srgb([r, g, b])));
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
let inks = [c, m, y, k].map(|v| v.clamp(0.0, 1.0));
|
||||
let direct = match (&self.cmyk, &dest.cmyk) {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
Color::Gray { .. } | Color::Lab { .. } => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
|
||||
pub fn gamut_error(&self, c: &Color) -> f32 {
|
||||
match c {
|
||||
@@ -531,7 +629,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 +1006,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();
|
||||
}
|
||||
@@ -938,8 +1059,11 @@ pub fn working_settings() -> ColorSettings {
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
/// leaving both unchanged, if a profile is unknown or the RGB policy is Preserve Numbers).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
if !Policy::RGB.contains(&settings.rgb_policy) {
|
||||
return Err(CmsError::Unsupported(format!("the RGB policy can't be {}", settings.rgb_policy.id())));
|
||||
}
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
@@ -952,14 +1076,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 +1092,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 +1166,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)]
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,17 @@ type Xf = Option<Arc<TransformF32Executor>>;
|
||||
/// generation only lets the cache drop what reloads left behind.
|
||||
type DirectKey = (u64, u64, usize, bool);
|
||||
|
||||
/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear
|
||||
/// tone curves, where black-point compensation is a linear remap, and from there into the
|
||||
/// destination.
|
||||
struct SameModel {
|
||||
into: Arc<TransformF32Executor>,
|
||||
out_of: Arc<TransformF32Executor>,
|
||||
/// The source's and the destination's black as luminance in the linear space (both 0 without
|
||||
/// compensation).
|
||||
black: [f32; 2],
|
||||
}
|
||||
|
||||
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
|
||||
pub struct IccProfile {
|
||||
pub name: String,
|
||||
@@ -49,6 +60,9 @@ pub struct IccProfile {
|
||||
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
|
||||
/// and black-point compensation.
|
||||
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
|
||||
/// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as
|
||||
/// [`Self::direct`] is.
|
||||
same_model: Mutex<Vec<(DirectKey, Option<Arc<SameModel>>)>>,
|
||||
}
|
||||
|
||||
/// A transform from one profile into an RGB profile without passing through sRGB: into the
|
||||
@@ -99,6 +113,7 @@ impl IccProfile {
|
||||
to_srgb: Default::default(),
|
||||
from_srgb: Default::default(),
|
||||
direct: Mutex::new(Vec::new()),
|
||||
same_model: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -172,6 +187,21 @@ impl IccProfile {
|
||||
Some(dst.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// Device pixels `v` (RGB / CMYK / Gray, 0..1, the profile's channels a pixel, any number of
|
||||
/// pixels) → sRGB in `dst` (three values a pixel), converted with `intent` in one pass of the
|
||||
/// cached transform. `None` when `v` doesn't hold whole pixels, `dst` doesn't hold three values
|
||||
/// for each, or no transform can be built.
|
||||
pub fn to_srgb_pixels(&self, v: &[f32], dst: &mut [f32], intent: Intent) -> Option<()> {
|
||||
let n = self.channels();
|
||||
if !v.len().is_multiple_of(n) || dst.len() != v.len() / n * 3 {
|
||||
return None;
|
||||
}
|
||||
let xf = self.to_xf(intent)?;
|
||||
xf.transform(v, dst).ok()?;
|
||||
dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// sRGB → device values.
|
||||
pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
|
||||
let xf = self.inverse_xf(intent)?;
|
||||
@@ -249,6 +279,69 @@ impl IccProfile {
|
||||
Some(Direct { to_linear, to_dest: Some(to_dest), black })
|
||||
}
|
||||
|
||||
/// Device values of this profile → device values of `dest`, a profile of the same model,
|
||||
/// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB
|
||||
/// keep their place. With `bpc` (and an intent other than absolute), this profile's black
|
||||
/// maps onto the destination's black (black-point compensation). `None` when `dest` is of
|
||||
/// another model or no transform can be built.
|
||||
pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
|
||||
if dest.kind != self.kind || v.len() != self.channels() {
|
||||
return None;
|
||||
}
|
||||
let bpc = bpc && intent != Intent::AbsoluteColorimetric;
|
||||
let generation = profiles_generation();
|
||||
let key = (dest.id, generation, intent_index(intent), bpc);
|
||||
let t = {
|
||||
let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.retain(|(k, _)| k.1 == generation);
|
||||
match cache.iter().find(|(k, _)| *k == key) {
|
||||
Some((_, t)) => t.clone(),
|
||||
None => {
|
||||
let t = self.build_same_model(dest, intent, bpc).map(Arc::new);
|
||||
cache.push((key, t.clone()));
|
||||
t
|
||||
}
|
||||
}
|
||||
}?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
t.into.transform(v, &mut lin).ok()?;
|
||||
let [from, to] = t.black;
|
||||
if from > 0.0 || to > 0.0 {
|
||||
lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from));
|
||||
}
|
||||
let lin = lin.map(|x| x.clamp(0.0, 1.0));
|
||||
let mut out = vec![0.0f32; dest.channels()];
|
||||
t.out_of.transform(&lin, &mut out).ok()?;
|
||||
Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
|
||||
}
|
||||
|
||||
fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<SameModel> {
|
||||
let mut linear = rgb_space(super::PROPHOTO_RGB)?;
|
||||
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
|
||||
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
|
||||
}
|
||||
linear.cicp = None;
|
||||
let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?;
|
||||
let black = if bpc {
|
||||
// Each profile's black: the darkest colour it reproduces, found as `build_direct`
|
||||
// finds it, as luminance in the linear space.
|
||||
let luminance = |p: &IccProfile, xf: &Arc<TransformF32Executor>| -> Option<f32> {
|
||||
let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
xf.transform(&inks, &mut lin).ok()?;
|
||||
let y = |c: &moxcms::Xyzd| c.y as f32;
|
||||
let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant);
|
||||
Some(lum.clamp(0.0, 0.5))
|
||||
};
|
||||
let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
[luminance(self, &into)?, luminance(dest, &back)?]
|
||||
} else {
|
||||
[0.0; 2]
|
||||
};
|
||||
Some(SameModel { into, out_of, black })
|
||||
}
|
||||
|
||||
/// Whether transforms can be built for this profile (checked at registration).
|
||||
pub fn usable(&self) -> bool {
|
||||
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
|
||||
|
||||
@@ -403,3 +403,78 @@ 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");
|
||||
}
|
||||
|
||||
/// The color management policies parse from their ids, Preserve Numbers is a CMYK policy only, and
|
||||
/// settings saved before the policies existed read with the default policy.
|
||||
#[test]
|
||||
fn policies_parse_and_default_in_saved_settings() {
|
||||
for p in Policy::CMYK {
|
||||
assert_eq!(Policy::parse(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(Policy::parse("bogus"), None);
|
||||
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert_eq!((old.rgb_policy, old.cmyk_policy), (Policy::PreserveEmbedded, Policy::PreserveEmbedded));
|
||||
let saved = serde_json::to_value(ColorSettings { cmyk_policy: Policy::PreserveNumbers, ..Default::default() }).unwrap();
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
#[test]
|
||||
fn convert_into_keeps_the_appearance() {
|
||||
let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let working = cms();
|
||||
let rgb = Color::Rgb { r: 0.25, g: 0.4, b: 0.6 };
|
||||
let moved = wide.convert_into(&working, &rgb, Intent::RelativeColorimetric);
|
||||
assert_ne!(moved, rgb, "the numbers change");
|
||||
assert!(de(wide.display_rgb(&rgb), working.display_rgb(&moved)) < 1.0, "{rgb:?} → {moved:?}");
|
||||
let ink = Color::Cmyk { c: 0.2, m: 0.4, y: 0.6, k: 0.1 };
|
||||
let moved = wide.convert_into(&working, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }) && moved != ink, "{ink:?} → {moved:?}");
|
||||
assert!(delta_e2000(wide.lab(&ink), working.lab(&moved)) < 3.0, "{ink:?} → {moved:?}");
|
||||
for c in [Color::Gray { k: 0.3 }, Color::Lab { l: 50.0, a: 10.0, b: -20.0 }] {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,28 @@ fn gray_is_srgb_toned() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_pixels_convert_as_each_one_does() {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(DISPLAY_P3).unwrap()).unwrap();
|
||||
let px = [[1.0f32, 0.0, 0.0], [0.2, 0.6, 0.9], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]];
|
||||
for intent in Intent::ALL {
|
||||
let v: Vec<f32> = px.iter().flatten().copied().collect();
|
||||
let mut dst = vec![0.0; v.len()];
|
||||
p.to_srgb_pixels(&v, &mut dst, intent).unwrap();
|
||||
for (i, rgb) in px.iter().enumerate() {
|
||||
let one = p.to_srgb(rgb, intent).unwrap();
|
||||
assert!(dst[i * 3..i * 3 + 3].iter().zip(one).all(|(a, b)| (a - b).abs() < 1e-5), "{intent:?} {rgb:?}: {dst:?} vs {one:?}");
|
||||
}
|
||||
}
|
||||
// Lengths that aren't whole pixels, or a destination of another size, are refused.
|
||||
assert!(p.to_srgb_pixels(&[0.5; 4], &mut [0.0; 3], Intent::Perceptual).is_none());
|
||||
assert!(p.to_srgb_pixels(&[0.5; 3], &mut [0.0; 6], Intent::Perceptual).is_none());
|
||||
let gray = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
|
||||
let mut dst = [0.0; 6];
|
||||
gray.to_srgb_pixels(&[0.25, 0.75], &mut dst, Intent::RelativeColorimetric).unwrap();
|
||||
assert!(dst.iter().zip([0.25, 0.25, 0.25, 0.75, 0.75, 0.75]).all(|(a, b)| (a - b).abs() < 0.01), "{dst:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_profiles_are_reproducible() {
|
||||
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
|
||||
@@ -252,3 +274,55 @@ fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones()
|
||||
assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}");
|
||||
assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}");
|
||||
}
|
||||
|
||||
/// A CMYK profile converts into another CMYK profile, ink for ink, and refuses a profile
|
||||
/// of another model or inks of the wrong count.
|
||||
#[test]
|
||||
fn cmyk_profiles_convert_into_each_other_directly() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let srgb = IccProfile::from_bytes(None, &icc_bytes(SRGB).unwrap()).unwrap();
|
||||
let inks = [0.2, 0.4, 0.6, 0.1];
|
||||
let out = generic.to_same_model_of(&device, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
assert_eq!(out.len(), 4);
|
||||
assert!(out.iter().zip(inks).any(|(a, b)| (a - b).abs() > 0.01), "{out:?}");
|
||||
assert!(generic.to_same_model_of(&srgb, &inks, Intent::RelativeColorimetric, false).is_none());
|
||||
assert!(generic.to_same_model_of(&device, &inks[..3], Intent::RelativeColorimetric, false).is_none());
|
||||
}
|
||||
|
||||
/// With black-point compensation, a CMYK profile's darkest ink converts into an ink as dark as a
|
||||
/// darker profile's darkest ink, and a dark grey of a darker profile converts lighter into a
|
||||
/// profile whose black is lighter; absolute colorimetric never compensates.
|
||||
#[test]
|
||||
fn cmyk_to_cmyk_compensates_the_black_point() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let rel = Intent::RelativeColorimetric;
|
||||
let lightness = |p: &IccProfile, inks: &[f32]| lab::srgb_to_lab(p.to_srgb(inks, rel).unwrap()).l;
|
||||
let black = |p: &IccProfile| p.from_srgb([0.0; 3], rel).unwrap();
|
||||
// Generic CMYK's black is a dark grey, the uncalibrated profile's is black.
|
||||
let (light, dark) = (lightness(&generic, &black(&generic)), lightness(&device, &black(&device)));
|
||||
assert!(light > dark + 5.0, "{light} vs {dark}");
|
||||
let into_device = |bpc| lightness(&device, &generic.to_same_model_of(&device, &black(&generic), rel, bpc).unwrap());
|
||||
let (on, off) = (into_device(true), into_device(false));
|
||||
assert!((on - dark).abs() < 1.5 && off > dark + 5.0, "with {on}, without {off}, the black {dark}");
|
||||
let grey = device.from_srgb([0.2; 3], rel).unwrap();
|
||||
let into_generic = |bpc| lightness(&generic, &device.to_same_model_of(&generic, &grey, rel, bpc).unwrap());
|
||||
let (on, off) = (into_generic(true), into_generic(false));
|
||||
assert!(on > off + 1.0, "with {on}, without {off}");
|
||||
for (from, to, inks) in [(&generic, &device, black(&generic)), (&device, &generic, grey)] {
|
||||
let abs = |bpc| from.to_same_model_of(to, &inks, Intent::AbsoluteColorimetric, bpc).unwrap();
|
||||
assert_eq!(abs(true), abs(false));
|
||||
}
|
||||
// Convert to Working Space (Cms::convert_into) compensates as Color Settings say.
|
||||
let device_name = register_icc(&icc_bytes(DEVICE_CMYK).unwrap(), Some("Test ICC Device CMYK".into())).unwrap().name;
|
||||
let rich = Color::Cmyk { c: 0.9, m: 0.8, y: 0.8, k: 1.0 };
|
||||
let convert = |bpc| {
|
||||
let dest = Cms::new(&ColorSettings { cmyk: device_name.clone(), bpc, ..ColorSettings::default() }).unwrap();
|
||||
icc_cmyk(bpc).convert_into(&dest, &rich, rel)
|
||||
};
|
||||
assert_ne!(convert(true), convert(false));
|
||||
// White is untouched.
|
||||
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
|
||||
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
}
|
||||
+178
-25
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -294,13 +294,19 @@ impl GuideOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
|
||||
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
|
||||
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
|
||||
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
|
||||
}
|
||||
|
||||
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
|
||||
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
|
||||
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
|
||||
if step == 0 {
|
||||
return c;
|
||||
}
|
||||
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
|
||||
let f = step_fraction(opts, step);
|
||||
let v = match opts.variation {
|
||||
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
|
||||
Variation::WarmCool => {
|
||||
|
||||
+41
-7
@@ -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);
|
||||
|
||||
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
let stop = |&(t, c, o): &(f32, Color, f32)| {
|
||||
let at = if mirrored { 1.0 - t } else { t };
|
||||
format!("{} {}%", css_color(&c, o), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
// Stops that repeat or reflect run that many times across the box. CSS mixes
|
||||
// hex colors evenly in sRGB between two stops
|
||||
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
|
||||
// midpoint and the curve of a Perceptual or hue gradient are written as stops
|
||||
// of their own, each with its color and opacity. A gradient that would need
|
||||
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
|
||||
unrolled.expanded_stops()
|
||||
} else {
|
||||
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
|
||||
};
|
||||
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
|
||||
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
|
||||
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
|
||||
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
|
||||
/// last the end colors hold.
|
||||
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
|
||||
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
|
||||
let stops: Vec<([f64; 3], f64, f64)> = list
|
||||
.split(", ")
|
||||
.map(|stop| {
|
||||
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
|
||||
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
|
||||
let at: f64 = at.trim_end_matches('%').parse().unwrap();
|
||||
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
|
||||
})
|
||||
.collect();
|
||||
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
|
||||
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
|
||||
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
|
||||
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
|
||||
let a = a0 + (a1 - a0) * w;
|
||||
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
|
||||
(c, a)
|
||||
}
|
||||
|
||||
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
|
||||
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
|
||||
/// own, also on a reflected and a mirrored conic swatch.
|
||||
#[test]
|
||||
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
|
||||
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
|
||||
for i in 0..64 {
|
||||
let p = (f64::from(i) + 0.5) / 64.0;
|
||||
let (css, css_alpha) = css_gradient_at(value, p);
|
||||
let (color, opacity) = gp.gradient.sample(at(p) as f32);
|
||||
let want = color.to_rgb();
|
||||
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
|
||||
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
|
||||
}
|
||||
};
|
||||
let ramp = |method| Gradient {
|
||||
method,
|
||||
..Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
|
||||
)
|
||||
};
|
||||
for method in crate::GradientMethod::ALL {
|
||||
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
|
||||
}
|
||||
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
|
||||
let fade = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
|
||||
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
|
||||
],
|
||||
);
|
||||
check("fade", GradientPaint::new(fade), &|p| p);
|
||||
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
|
||||
let spread = reflected.spreader();
|
||||
check("reflect", GradientPaint::new(reflected), &spread);
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
check("mirrored conic", conic, &|p| 1.0 - p);
|
||||
}
|
||||
|
||||
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
|
||||
/// own stops.
|
||||
#[test]
|
||||
fn css_gradient_swatches_keep_their_stop_count_bounded() {
|
||||
let n = 4000;
|
||||
let stops = (0..n)
|
||||
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
|
||||
.collect();
|
||||
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -8,20 +8,28 @@ 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 }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
# Image headers (PNG and JPEG sizes, `pixels::header_size`) and CMYK JPEG inks (`cmyk`).
|
||||
craft-image-codecs = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
# 1-bit TIFFs compressed with CCITT Group 3 (Compression 2 and 3).
|
||||
hayro-ccitt = { workspace = true }
|
||||
zune-jpeg = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
flate2 = { workspace = true }
|
||||
# The CMYK JPEG reader `cmyk` had before craft-image-codecs, kept as the reference its inks match.
|
||||
zune-jpeg = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
|
||||
+1206
-79
File diff suppressed because it is too large.
Load diff
+237
-44
@@ -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));
|
||||
}
|
||||
}
|
||||
+1735
-235
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,96 @@
|
||||
//! Images decoded through craft-image-codecs as the image crate gave them (#778): the renderer,
|
||||
//! File › Open and Place, SVG import, and embedded and linked images read their pixels with
|
||||
//! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`].
|
||||
|
||||
/// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds.
|
||||
pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
|
||||
|
||||
/// `bytes` decoded as `format` within `allowance` bytes, the pixels as stored (not turned
|
||||
/// upright) and as the image crate gave them ([`dynamic`]), with the ICC profile the file embeds.
|
||||
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
|
||||
/// with it.
|
||||
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
|
||||
keep_orientation: true,
|
||||
};
|
||||
let mut img = craft_image_codecs::decode_as_with(format, bytes, &opts)?;
|
||||
let icc = img.icc.take();
|
||||
let img = dynamic(img).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the decoded samples don't fit the image".into()))?;
|
||||
Ok((img, icc))
|
||||
}
|
||||
|
||||
/// `bytes` decoded within `max` bytes, counted as the file's samples and as RGBA (#1717), the
|
||||
/// pixels as stored and as the image crate gave them, with the ICC profile the file embeds.
|
||||
/// Image blobs read their pixels with it. `Ok(None)` when they would take more than `max` as
|
||||
/// samples or as RGBA (the header alone decides; the pixels are not read). `Err` when the bytes
|
||||
/// aren't an image the decoder reads, including a file whose header fits the allowance but whose
|
||||
/// pixels can't be decoded (a cut-short file, or one the decoder refuses as a decompression bomb).
|
||||
pub fn decode_within(bytes: &[u8], max: u64) -> Result<Option<DecodedImage>, craft_image_codecs::CodecError> {
|
||||
let format = craft_image_codecs::detect(bytes).ok_or(craft_image_codecs::CodecError::UnknownFormat)?;
|
||||
let (w, h, per_pixel) =
|
||||
decoded_layout(bytes, format).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the image's size can't be read".into()))?;
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
if pixels.saturating_mul(per_pixel) > max || pixels.saturating_mul(4) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
decode_image(format, bytes, max).map(Some)
|
||||
}
|
||||
|
||||
/// A decoded image as the image crate's: 8- and 16-bit gray, gray and alpha, RGB and RGBA as they
|
||||
/// are, 32-bit float RGB and RGBA as they are, anything else as 8-bit RGBA.
|
||||
fn dynamic(img: craft_image_codecs::Image) -> Option<image::DynamicImage> {
|
||||
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
|
||||
use image::{DynamicImage as D, ImageBuffer as B};
|
||||
let (w, h) = img.dimensions();
|
||||
Some(match (img.layout(), img.sample_type()) {
|
||||
(L::Gray, S::U8) => D::ImageLuma8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::GrayA, S::U8) => D::ImageLumaA8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::Rgb, S::U8) => D::ImageRgb8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::Rgba, S::U8) => D::ImageRgba8(B::from_raw(w, h, img.into_data())?),
|
||||
(layout @ (L::Gray | L::GrayA | L::Rgb | L::Rgba), S::U16) => {
|
||||
let v = img.to_u16_samples()?;
|
||||
match layout {
|
||||
L::Gray => D::ImageLuma16(B::from_raw(w, h, v)?),
|
||||
L::GrayA => D::ImageLumaA16(B::from_raw(w, h, v)?),
|
||||
L::Rgb => D::ImageRgb16(B::from_raw(w, h, v)?),
|
||||
_ => D::ImageRgba16(B::from_raw(w, h, v)?),
|
||||
}
|
||||
}
|
||||
_ => D::ImageRgba8(B::from_raw(w, h, img.to_rgba8())?),
|
||||
})
|
||||
}
|
||||
|
||||
/// The image's size and the bytes a pixel of it takes decoded ([`decode_as`]), read from its
|
||||
/// header: palettes as RGB (RGBA with a transparent entry; GIF frames always RGBA), bitmaps as 8-bit
|
||||
/// gray, 16-bit samples as two bytes. A PNG whose header alone is there is read from its `IHDR`;
|
||||
/// a format whose header says only its size (TGA, ICO and the like) counts RGBA.
|
||||
pub fn decoded_layout(bytes: &[u8], format: craft_image_codecs::Format) -> Option<(u32, u32, u64)> {
|
||||
use craft_image_codecs::{Format as F, RasterColorType as T};
|
||||
if let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() {
|
||||
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
|
||||
let channels = match i.color_type {
|
||||
_ if format == F::Gif => 4,
|
||||
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
|
||||
T::Bitmap => 1,
|
||||
_ => u64::from(i.channels.max(1)),
|
||||
};
|
||||
return Some((i.width, i.height, channels * if deep { 2 } else { 1 }));
|
||||
}
|
||||
if format != F::Png {
|
||||
return crate::header_size(bytes).map(|(w, h)| (w, h, 4));
|
||||
}
|
||||
if bytes.get(12..16)? != b"IHDR" {
|
||||
return None;
|
||||
}
|
||||
let be = |at: usize| Some(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?));
|
||||
let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?);
|
||||
let channels: u64 = match color {
|
||||
0 => 1,
|
||||
2 | 3 => 3,
|
||||
4 => 2,
|
||||
6 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
Some((be(16)?, be(20)?, channels * if depth == 16 { 2 } else { 1 }))
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
@@ -747,6 +752,18 @@ impl Document {
|
||||
|
||||
/// [`Document::locked_artboards`] leaving out artboard `index`.
|
||||
pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> {
|
||||
self.locks_except(index, false)
|
||||
}
|
||||
|
||||
/// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept
|
||||
/// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too
|
||||
/// ([`crate::symbols::KeptBoxes::keeping`]).
|
||||
pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> {
|
||||
self.locks_except(usize::MAX, true)
|
||||
}
|
||||
|
||||
/// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes.
|
||||
fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> {
|
||||
// Art flush with an edge from outside can overlap it by a rounding error, as in
|
||||
// `art_bounds_on` (#1295).
|
||||
let rects: Vec<Rect> =
|
||||
@@ -765,7 +782,9 @@ impl Document {
|
||||
if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) {
|
||||
objects(layer, &mut pattern_art);
|
||||
}
|
||||
LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() }
|
||||
// Nothing is measured without a locked artboard.
|
||||
let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() };
|
||||
LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() }
|
||||
}
|
||||
|
||||
/// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]));
|
||||
}
|
||||
}
|
||||
+148
-1
@@ -140,7 +140,7 @@ impl crate::Document {
|
||||
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
|
||||
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
|
||||
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
|
||||
/// label's alignment.
|
||||
/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LabelStyles {
|
||||
@@ -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,42 @@ 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>,
|
||||
/// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls
|
||||
/// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the
|
||||
/// default stroke.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub axis_rows: Option<LabelRows>,
|
||||
/// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ring_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 +387,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
|
||||
@@ -417,6 +491,10 @@ pub struct GraphSpec {
|
||||
pub first_column_in_front: bool,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub filled_lines: bool,
|
||||
/// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws
|
||||
/// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_width: Option<f64>,
|
||||
/// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the
|
||||
/// legend in rows above the plot instead of a column on its right).
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -477,6 +555,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 {
|
||||
@@ -487,17 +569,80 @@ fn is_zero(n: &usize) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and
|
||||
/// greatest widths a graph takes, in points.
|
||||
pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
|
||||
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
|
||||
|
||||
/// The weight of the black outline Draw Filled Lines draws around each band, in points.
|
||||
pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25;
|
||||
|
||||
impl GraphSpec {
|
||||
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
|
||||
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
|
||||
/// default.
|
||||
pub fn filled_line_width(&self) -> f64 {
|
||||
self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH)
|
||||
}
|
||||
}
|
||||
|
||||
/// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then.
|
||||
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>>> {
|
||||
@@ -581,6 +726,7 @@ impl Default for GraphSpec {
|
||||
first_row_in_front: false,
|
||||
first_column_in_front: false,
|
||||
filled_lines: false,
|
||||
line_width: None,
|
||||
drop_shadow: false,
|
||||
legend_across_top: false,
|
||||
pie_legend_in_wedges: false,
|
||||
@@ -601,6 +747,7 @@ impl Default for GraphSpec {
|
||||
connect_points: true,
|
||||
edge_to_edge: false,
|
||||
placed: None,
|
||||
placed_art: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
+1204
-205
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+233
-25
@@ -15,7 +15,8 @@ use crate::{AppearanceItem, Document, Node, NodeKind};
|
||||
pub struct Inks {
|
||||
/// Process inks C, M, Y, K (0..1).
|
||||
pub cmyk: [f32; 4],
|
||||
/// Spot ink (swatch name, tint 0..1).
|
||||
/// Spot ink (swatch name, tint 0..1). A spot ink named like a process plate ("Cyan",
|
||||
/// "Magenta", "Yellow", "Black") prints on that plate: its tint is in `cmyk` too.
|
||||
pub spot: Option<(String, f32)>,
|
||||
/// Registration: the tint (every process ink's) prints on every spot plate too.
|
||||
pub registration: bool,
|
||||
@@ -49,7 +50,20 @@ pub struct Plate {
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch.
|
||||
/// Spot swatch `name` as art links to it: [`Document::swatch`] `name` when that is a spot swatch of
|
||||
/// a solid colour.
|
||||
fn spot_swatch<'a>(doc: &'a Document, name: &str) -> Option<&'a vectorcraft_color::Swatch> {
|
||||
doc.swatch(name).filter(|s| s.spot && s.paint.color().is_some())
|
||||
}
|
||||
|
||||
/// The index in [`PROCESS_PLATES`] of the process plate named `name`.
|
||||
fn process_plate(name: &str) -> Option<usize> {
|
||||
PROCESS_PLATES.iter().position(|p| *p == name)
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch that art can link to. A
|
||||
/// link names a swatch, which is the first swatch of that name ([`Document::swatch`]), so a spot
|
||||
/// swatch after another of its name, or named like a process plate, gets no plate.
|
||||
pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let mut v: Vec<Plate> = PROCESS_PLATES
|
||||
@@ -61,58 +75,106 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
|
||||
})
|
||||
.collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for sw in doc.swatches_iter() {
|
||||
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
|
||||
&& !v.iter().any(|p| p.name == sw.name)
|
||||
// Only the first swatch of a name is the one [`spot_swatch`] finds.
|
||||
if !seen.insert(sw.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let (true, Some(color)) = (sw.spot, sw.paint.color())
|
||||
&& !PROCESS_PLATES.contains(&sw.name.as_str())
|
||||
{
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
|
||||
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
|
||||
/// prints on that plate.
|
||||
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
let s = doc.swatch(name).filter(|s| s.spot)?;
|
||||
s.paint.color().map(|c| doc.linked_color(c, true))
|
||||
if process_plate(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
|
||||
}
|
||||
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
pub type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
/// An ink amount clamped to 0..1; an amount that is not a finite number prints no ink.
|
||||
fn ink_amount(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate.
|
||||
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
|
||||
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
|
||||
/// tint on every plate. A tint that is not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [tint.clamp(0.0, 1.0); 4], spot: None, registration: true };
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
&& spot_swatch(doc, name).is_some()
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), tint.clamp(0.0, 1.0))), registration: false };
|
||||
let tint = ink_amount(tint);
|
||||
let mut cmyk = [0.0; 4];
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = tint;
|
||||
}
|
||||
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
|
||||
}
|
||||
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 spot ink named like a process plate prints its tint layered
|
||||
/// over that plate's amount; EPS export can't write that ink beside process plates in one DeviceN
|
||||
/// space, so it writes such a gradient in process colors with a warning. 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((name, tint))) = (plates, &ink.spot) {
|
||||
let mut cmyk = p.map(ink_amount);
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = 1.0 - (1.0 - cmyk[i]) * (1.0 - tint);
|
||||
}
|
||||
ink.cmyk = cmyk;
|
||||
}
|
||||
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 +199,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 +211,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 +237,149 @@ 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, SwatchGroup};
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of `doc`'s spot plates, in order.
|
||||
fn spot_plates(doc: &Document) -> Vec<String> {
|
||||
plates(doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_an_earlier_process_swatch_gets_no_plate() {
|
||||
// Art links to a swatch by name, which finds the earlier process `Teal`: the later spot
|
||||
// `Teal` in a colour group prints nothing, so it gets no plate.
|
||||
let mut d = gold_doc();
|
||||
let spot_teal = Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.9, 0.0, 0.4, 0.0)), global: true, spot: true };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![spot_teal.clone()] });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.8, 0.0, 0.3, 0.0);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 1.0)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: c.to_cmyk(&look, Intent::RelativeColorimetric), spot: None, registration: false });
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Teal", 1.0)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!(stop, teal, "a gradient stop linked to it separates as process too");
|
||||
assert_eq!(spot_color(&d, "Teal"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"], "no plate for the spot swatch that no art reaches");
|
||||
// The first swatch of a name decides either way: a spot swatch first gets its plate, and a
|
||||
// later process swatch of the same name does not take it away.
|
||||
let mut d = gold_doc();
|
||||
d.swatches.retain(|s| s.name != "Teal");
|
||||
d.swatches.insert(0, spot_teal);
|
||||
let process_teal = Swatch { name: "Teal".into(), paint: Paint::solid(look), global: true, spot: false };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![process_teal] });
|
||||
assert_eq!(spot_plates(&d), ["Teal", "Gold"]);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: [0.0; 4], spot: Some(("Teal".into(), 0.5)), registration: false });
|
||||
assert_eq!(spot_color(&d, "Teal"), Some(Color::cmyk(0.9, 0.0, 0.4, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_a_process_plate_prints_on_that_plate() {
|
||||
// A spot `Cyan` has the process Cyan plate's name, so art linked to it prints its tint on
|
||||
// that plate, as a Separation ink named `Cyan` in PDF and EPS export does, instead of a
|
||||
// spot amount that no plate prints.
|
||||
let mut d = gold_doc();
|
||||
let blue = Color::cmyk(1.0, 0.3, 0.0, 0.1);
|
||||
d.swatches.insert(0, Swatch { name: "Cyan".into(), paint: Paint::solid(blue), global: true, spot: true });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let ink = inks(&d, &c, &blue, Some(("Cyan", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(ink, Inks { cmyk: [0.5, 0.0, 0.0, 0.0], spot: Some(("Cyan".into(), 0.5)), registration: false });
|
||||
assert_eq!((ink.on_plate("Cyan"), ink.on_plate("Magenta"), ink.on_plate("Gold")), (0.5, 0.0, 0.0));
|
||||
let nan = inks(&d, &c, &blue, Some(("Cyan", f32::NAN)), Intent::RelativeColorimetric);
|
||||
assert_eq!(nan.cmyk, [0.0; 4], "a tint that is not a number prints no ink");
|
||||
// A gradient stop's own process plates still print, with the tint layered over its Cyan.
|
||||
let stop = stop_inks(&d, &c, &blue, Some(("Cyan", 0.5)), Some([0.2, 0.4, 0.0, 0.0]), Intent::RelativeColorimetric);
|
||||
assert!((stop.on_plate("Cyan") - 0.6).abs() < 1e-6, "{stop:?}");
|
||||
assert_eq!((stop.on_plate("Magenta"), stop.on_plate("Yellow"), stop.on_plate("Black")), (0.4, 0.0, 0.0));
|
||||
assert_eq!(spot_color(&d, "Cyan"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
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| inks(&d, &c, &look, link, Intent::RelativeColorimetric);
|
||||
for t in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let spot = ink(Some(("Gold", t)));
|
||||
assert_eq!(spot, Inks { cmyk: [0.0; 4], spot: Some(("Gold".into(), 0.0)), registration: false }, "{t}");
|
||||
assert_eq!((spot.on_plate("Gold"), spot.on_plate("Cyan")), (0.0, 0.0), "{t}");
|
||||
let reg = ink(Some((REGISTRATION, t)));
|
||||
assert_eq!(reg, Inks { cmyk: [0.0; 4], spot: None, registration: true }, "{t}");
|
||||
assert_eq!((reg.on_plate("Gold"), reg.on_plate("Black")), (0.0, 0.0), "{t}");
|
||||
// A stop's process plates still print beside a spot tint that prints nothing.
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Gold", t)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!((stop.cmyk, stop.on_plate("Gold")), ([0.25, 0.0, 0.4, 0.0], 0.0), "{t}");
|
||||
}
|
||||
// Finite tints outside 0..1 are clamped.
|
||||
assert_eq!(ink(Some(("Gold", 2.0))).on_plate("Gold"), 1.0);
|
||||
assert_eq!(ink(Some(("Gold", -1.0))).on_plate("Gold"), 0.0);
|
||||
assert_eq!(ink(Some((REGISTRATION, 2.0))).cmyk, [1.0; 4]);
|
||||
assert_eq!(ink(Some((REGISTRATION, -1.0))).cmyk, [0.0; 4]);
|
||||
}
|
||||
|
||||
#[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
@@ -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));
|
||||
}
|
||||
}
|
||||
+29
-8
@@ -14,6 +14,7 @@ pub mod cmyk;
|
||||
pub mod color_mask;
|
||||
pub mod compound_shape;
|
||||
pub mod corners;
|
||||
pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod graph;
|
||||
@@ -28,15 +29,17 @@ pub mod shared;
|
||||
mod symbol_export_type;
|
||||
mod symbol_nine_slice;
|
||||
pub mod symbol_overrides;
|
||||
mod symbol_pixel_aligned;
|
||||
mod symbol_registration;
|
||||
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_pixel_aligned::SYMBOL_PIXEL_ALIGNED;
|
||||
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
|
||||
pub mod links;
|
||||
pub mod live;
|
||||
@@ -52,15 +55,17 @@ pub mod overprint;
|
||||
pub mod pattern;
|
||||
pub mod perspective;
|
||||
mod pixels;
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
|
||||
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick, header_size};
|
||||
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 +97,9 @@ 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, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
|
||||
LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength,
|
||||
ValueAxisSide,
|
||||
};
|
||||
pub use hit::{Hit, HitKind};
|
||||
pub use links::{LinkInfo, PlacementOptions};
|
||||
@@ -117,13 +123,16 @@ 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::PATH_LEAD_MAX;
|
||||
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,
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -142,6 +151,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 +164,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)]
|
||||
@@ -265,8 +276,8 @@ pub struct Document {
|
||||
/// File → Document Setup (bleed, transparency grid, paper, type options).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub setup: DocSetup,
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name)
|
||||
/// they were copied from instead of the current layer.
|
||||
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers and
|
||||
/// sublayers they were copied from instead of the current layer.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub paste_remembers_layers: bool,
|
||||
/// File → File Info (its title is [`Document::info_title`]).
|
||||
@@ -360,6 +371,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 {
|
||||
|
||||
+73
-35
@@ -145,9 +145,9 @@ impl ImageBlob {
|
||||
/// This blob after its pixels are decoded once, within [`crate::MAX_RASTER_ALLOC`], to check
|
||||
/// that they can be read; with `proxy`, it also gets the preview [`Self::with_proxy`] makes,
|
||||
/// made from that decode. `None` when the pixels can't be read, as with a file cut short that
|
||||
/// has a header but not all its pixels. An image whose pixels would take more than the
|
||||
/// allowance as RGBA is not decoded, and one whose decode needs more than the allowance stops
|
||||
/// decoding; either is returned as it is.
|
||||
/// has a header but not all its pixels, or one the decoder refuses as a decompression bomb.
|
||||
/// An image whose pixels would take more than the allowance as RGBA is not decoded and is
|
||||
/// returned as it is.
|
||||
pub fn checked_with_proxy(self, proxy: bool) -> Option<Self> {
|
||||
self.checked_with_pixels(proxy).map(|(blob, _)| blob)
|
||||
}
|
||||
@@ -155,22 +155,12 @@ impl ImageBlob {
|
||||
/// [`Self::checked_with_proxy`], with the pixels it decoded: `None` beside the blob when it
|
||||
/// decoded none (an image past the allowance).
|
||||
pub fn checked_with_pixels(mut self, proxy: bool) -> Option<(Self, Option<image::DynamicImage>)> {
|
||||
let max = crate::MAX_RASTER_ALLOC;
|
||||
let reader = || image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok();
|
||||
let (w, h) = reader()?.into_dimensions().ok()?;
|
||||
if u64::from(w) * u64::from(h) > max / 4 {
|
||||
return Some((self, None));
|
||||
}
|
||||
let mut r = reader()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(max);
|
||||
r.limits(limits);
|
||||
let img = match r.decode() {
|
||||
Ok(img) => img,
|
||||
Err(image::ImageError::Limits(_)) => return Some((self, None)),
|
||||
let img = match crate::decode::decode_within(&self.bytes, crate::MAX_RASTER_ALLOC) {
|
||||
Ok(Some((img, _))) => img,
|
||||
Ok(None) => return Some((self, None)),
|
||||
Err(_) => return None,
|
||||
};
|
||||
if proxy && self.proxy.is_none() && w.max(h) > PROXY_SIZE {
|
||||
if proxy && self.proxy.is_none() && img.width().max(img.height()) > PROXY_SIZE {
|
||||
self.proxy = proxy_of(&img).map(Arc::new);
|
||||
}
|
||||
Some((self, Some(img)))
|
||||
@@ -210,26 +200,22 @@ pub fn missing_placeholder() -> Option<Vec<u8>> {
|
||||
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
|
||||
/// undecodable.
|
||||
fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
|
||||
let format = craft_image_codecs::detect(bytes)?;
|
||||
let (w, h, _) = crate::decode::decoded_layout(bytes, format)?;
|
||||
if w.max(h) <= PROXY_SIZE {
|
||||
return None;
|
||||
}
|
||||
// The proxy decodes within the project's raster cap, counted as RGBA like every other
|
||||
// decode path (#3597): the header alone decides whether the pixels could ever fit, and the
|
||||
// decoder gets the same budget instead of image's own default.
|
||||
if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 {
|
||||
return None;
|
||||
}
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(crate::MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
proxy_of(&reader.decode().ok()?)
|
||||
// The proxy decodes within the project's raster cap, counted as the file's samples and as
|
||||
// RGBA like every other decode path (#3597, #1717): the header alone decides whether the
|
||||
// pixels could ever fit, and the decoder gets the same budget.
|
||||
let (img, _) = crate::decode::decode_within(bytes, crate::MAX_RASTER_ALLOC).ok()??;
|
||||
proxy_of(&img)
|
||||
}
|
||||
|
||||
/// 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 +234,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 +371,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 +397,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 +460,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 +718,52 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG that says it is `w` × `h` 1-bit grey pixels (header and a stub IDAT, no rows).
|
||||
fn png_header_1bit(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
let push = |out: &mut Vec<u8>, chunk: &[u8]| {
|
||||
out.extend((chunk.len() as u32 - 4).to_be_bytes());
|
||||
out.extend(chunk);
|
||||
out.extend(crc32(chunk).to_be_bytes());
|
||||
};
|
||||
let mut ihdr = b"IHDR".to_vec();
|
||||
ihdr.extend(w.to_be_bytes());
|
||||
ihdr.extend(h.to_be_bytes());
|
||||
ihdr.extend([1, 0, 0, 0, 0]);
|
||||
push(&mut out, &ihdr);
|
||||
push(&mut out, b"IDAT\x78\x9c");
|
||||
push(&mut out, b"IEND");
|
||||
out
|
||||
}
|
||||
|
||||
/// A header-only 23,170 × 23,170 1-bit gray PNG is within the 2 GiB RGBA allowance, so Place
|
||||
/// decodes it and must refuse it (no pixel rows). 23,171 × 23,170 is past the allowance and is
|
||||
/// kept unread, not refused. craft-image-codecs reports the cut-short file as LimitExceeded
|
||||
/// (its decompression-bomb guard); that is still "pixels can't be read", not "past the allowance".
|
||||
#[test]
|
||||
fn a_gray_header_within_the_allowance_is_unreadable() {
|
||||
let within = png_header_1bit(23_170, 23_170);
|
||||
let over = png_header_1bit(23_171, 23_170);
|
||||
assert!(crate::decode::decode_within(&within, crate::MAX_RASTER_ALLOC).is_err(), "header-only within the allowance");
|
||||
assert!(matches!(crate::decode::decode_within(&over, crate::MAX_RASTER_ALLOC), Ok(None)), "past the allowance is not decoded");
|
||||
assert!(ImageBlob::new("image/png", within).checked_with_pixels(false).is_none(), "Place refuses the file");
|
||||
let (_, pixels) = ImageBlob::new("image/png", over).checked_with_pixels(false).expect("past the allowance is kept unread");
|
||||
assert!(pixels.is_none());
|
||||
}
|
||||
}
|
||||
+272
-18
@@ -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::{
|
||||
@@ -65,7 +65,9 @@ pub use expand::{
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -88,6 +90,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smooth map takes each handle along the map's derivative, also far from the origin,
|
||||
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
|
||||
/// handles there.
|
||||
#[test]
|
||||
fn map_smooth_within_keeps_handles_far_from_the_origin() {
|
||||
for at in [0.0, 1e13] {
|
||||
let o = Point::new(at, at);
|
||||
let curve = PathData::single(vectorcraft_geom::SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
|
||||
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
|
||||
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
@@ -358,6 +384,34 @@ mod tests {
|
||||
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coons_places_are_where_the_patch_bends() {
|
||||
// A rectangle's sides have 65 evenly spaced points.
|
||||
let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places();
|
||||
assert_eq!((u.len(), v.len()), (65, 65));
|
||||
assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}");
|
||||
// A top object with a curved top: between two places next to each other the patch is
|
||||
// straight, in `u` and in `v`.
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0));
|
||||
path.line_to((100.0, 50.0));
|
||||
path.line_to((40.0, 50.0));
|
||||
path.line_to((0.0, 50.0));
|
||||
path.close_path();
|
||||
let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap();
|
||||
let [u, v] = c.places();
|
||||
assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}");
|
||||
assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}");
|
||||
for w in u.windows(2) {
|
||||
for y in [0.0, 0.3, 1.0] {
|
||||
let mid = c.eval((w[0] + w[1]) / 2.0, y);
|
||||
let half = c.eval(w[0], y).midpoint(c.eval(w[1], y));
|
||||
assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_go_on_past_the_content_box() {
|
||||
// A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there.
|
||||
@@ -568,23 +622,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 +1301,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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+294
-28
@@ -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
|
||||
@@ -305,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
|
||||
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
|
||||
for h in &mut feed.0 {
|
||||
h.write_u8(u8::from(text.first_para_continues));
|
||||
h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from));
|
||||
for b in inline_bounds.clone() {
|
||||
match b {
|
||||
None => h.write_u8(0),
|
||||
@@ -367,15 +379,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 +408,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 +429,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 +446,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 +549,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 +673,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 +859,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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
+118
-15
@@ -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);
|
||||
@@ -330,12 +338,107 @@ impl Coons {
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
|
||||
/// The places in `u` where the top or bottom side has a point, and the places in `v` where the
|
||||
/// left or right side has one, rising from 0 to 1. Between two places next to each other, each
|
||||
/// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of
|
||||
/// the grid they make.
|
||||
pub fn places(&self) -> [Vec<f64>; 2] {
|
||||
let sides = [&self.top, &self.right, &self.bottom, &self.left];
|
||||
let at = |which: usize| -> Vec<f64> {
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => knots.clone(),
|
||||
None => {
|
||||
let last = sides[which].len().saturating_sub(1).max(1);
|
||||
(0..=last).map(|i| i as f64 / last as f64).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let merge = |a: usize, b: usize| {
|
||||
let mut v = at(a);
|
||||
v.extend(at(b));
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
[merge(0, 2), merge(1, 3)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
/// 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;
|
||||
|
||||
@@ -497,6 +497,37 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
|
||||
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
|
||||
/// mapped as points point different ways on the two sides of a join and the curve kinks there
|
||||
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
|
||||
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
let v = h - p;
|
||||
let len = v.hypot();
|
||||
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
|
||||
if len.is_nan() || len <= 0.0 || len.is_infinite() {
|
||||
return f(p);
|
||||
}
|
||||
// A thousandth of the handle, or more where the coordinates are so large that so short a
|
||||
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
|
||||
// at most at the handle's own end.
|
||||
let size = p.x.abs().max(p.y.abs()).max(1.0);
|
||||
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
|
||||
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
|
||||
f(p) + d
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
|
||||
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
@@ -516,20 +547,20 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
pending_in = Some(handle(sub.p3, sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+37
-4
@@ -105,8 +105,13 @@ impl Document {
|
||||
n += shared(&self.para_styles, &newer.para_styles, styles);
|
||||
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
|
||||
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
|
||||
let custom = |f: &crate::CompositeFont| {
|
||||
vec_bytes(&f.custom) + f.custom.iter().map(|s| s.name.capacity() + s.characters.capacity() + part(&s.part)).sum::<usize>()
|
||||
};
|
||||
vec_bytes(c)
|
||||
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
|
||||
+ c.iter()
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
@@ -276,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
});
|
||||
}
|
||||
b += match &n.kind {
|
||||
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let was = other.and_then(|o| match &o.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
});
|
||||
path_bytes_besides(path, was) + boxed(live)
|
||||
}
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
@@ -293,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
}
|
||||
|
||||
fn path_bytes(p: &PathData) -> usize {
|
||||
let anchors: usize =
|
||||
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
|
||||
path_bytes_besides(p, None)
|
||||
}
|
||||
|
||||
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
|
||||
/// a version made by changing one anchor shares every chunk but the one it changed.
|
||||
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
|
||||
let mut shared: Vec<usize> =
|
||||
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
|
||||
shared.sort_unstable();
|
||||
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
|
||||
let anchors: usize = p
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let table = s.anchors.table_bytes();
|
||||
let own: usize = s
|
||||
.anchors
|
||||
.chunk_allocations()
|
||||
.filter(|(id, _)| shared.binary_search(id).is_err())
|
||||
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
|
||||
.sum();
|
||||
if table == 0 { own } else { ALLOC + table + own }
|
||||
})
|
||||
.sum();
|
||||
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
|
||||
}
|
||||
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -74,19 +74,32 @@ impl Node {
|
||||
/// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted
|
||||
/// over it (unclipped). Each part is this object keeping only those appearance items (type:
|
||||
/// also only its characters' fills or strokes); `None` where it paints nothing, as right after
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths.
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths, and so does
|
||||
/// a group of the pieces a clipping path's fills and strokes draw ([`crate::NodeExtras::clip_pieces`]),
|
||||
/// even after effects around it split or copy those pieces into groups: each part is then that
|
||||
/// group keeping only the pieces of those fills or strokes.
|
||||
pub fn clip_paint(&self) -> ClipPaint {
|
||||
use crate::appearance::AppearanceItem;
|
||||
let item = |fill: bool, i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
if matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().clip_pieces {
|
||||
let part = |fill: bool| {
|
||||
let mut paints = false;
|
||||
let mut n = pieces_of(self, fill, &|i| item(fill, i), &mut paints)?;
|
||||
n.extras_mut().clip_pieces = false;
|
||||
paints.then_some(n)
|
||||
};
|
||||
return ClipPaint { fill: part(true), stroke: part(false) };
|
||||
}
|
||||
let runs = match &self.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None,
|
||||
NodeKind::Text(t) => Some(&t.runs),
|
||||
_ => return ClipPaint::default(),
|
||||
};
|
||||
let paints = |fill: bool| {
|
||||
let item = |i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
let item = |i: &AppearanceItem| item(fill, i);
|
||||
let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 };
|
||||
self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run))
|
||||
};
|
||||
@@ -110,6 +123,30 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`, a group of a clipping path's pieces or one of them, keeping only the pieces of its fills
|
||||
/// (`fill`) or of its strokes, at every depth of the groups an effect put them in; `None` when it
|
||||
/// holds none. `paints` is set when one of the kept fills or strokes paints.
|
||||
fn pieces_of(n: &Node, fill: bool, paints_item: &dyn Fn(&crate::appearance::AppearanceItem) -> bool, paints: &mut bool) -> Option<Node> {
|
||||
use crate::appearance::AppearanceItem;
|
||||
if let NodeKind::Group { children, clip: false } = &n.kind {
|
||||
let kept: Vec<_> = children.iter().filter_map(|c| pieces_of(c, fill, paints_item, paints).map(std::sync::Arc::new)).collect();
|
||||
if kept.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = kept;
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let items = &n.appearance.items;
|
||||
if !items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) == fill) {
|
||||
return None;
|
||||
}
|
||||
*paints |= items.iter().any(paints_item);
|
||||
Some(n.clone())
|
||||
}
|
||||
|
||||
/// What a clipping path paints ([`Node::clip_paint`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ClipPaint {
|
||||
|
||||
@@ -75,6 +75,14 @@ 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,
|
||||
/// A group of the pieces a clipping path's fills and strokes draw once their geometry effects
|
||||
/// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints
|
||||
/// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]).
|
||||
pub clip_pieces: bool,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -103,6 +111,8 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
envelope_edit_margin: None,
|
||||
pixel_aligned: false,
|
||||
color_mask: None,
|
||||
warp_piece: false,
|
||||
clip_pieces: false,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
+142
-23
@@ -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
|
||||
@@ -226,7 +228,11 @@ impl Node {
|
||||
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
|
||||
/// guides, that box also holds the art box placed by each cell's map
|
||||
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform. An
|
||||
/// instance whose art holds a clipping path with live geometry effects also takes in the region
|
||||
/// they give it ([`crate::hit::set_clip_region`]): moved with the instance when it only moves its
|
||||
/// art, otherwise placed by it and grown by as far as the region reaches past the art, times √2
|
||||
/// and the larger of 1 and the Frobenius norm of the transform's linear part.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
@@ -261,6 +267,35 @@ 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)))
|
||||
}
|
||||
// The live geometry effects of the clipping paths in the art can draw it past its box.
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let Some((s, art, region)) = symbols.and_then(|s| {
|
||||
let a = s.art(symbol)?;
|
||||
Some((s, a, a.reshaped?))
|
||||
}) else {
|
||||
return self.visual(symbols);
|
||||
};
|
||||
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
|
||||
let placed = if moves_only(*xf) && map.is_none() {
|
||||
xf.transform_rect_bbox(region)
|
||||
} else {
|
||||
// An effect can reach a fixed distance past the art or a distance in proportion
|
||||
// to its size, as `SymbolBoxes::effects_reach` estimates it.
|
||||
let g = art.geometric;
|
||||
let all = region.union(g);
|
||||
let past = [g.x0 - region.x0, region.x1 - g.x1, g.y0 - region.y0, region.y1 - g.y1].into_iter().fold(0.0_f64, f64::max);
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let grow = past * std::f64::consts::SQRT_2 * (a * a + b * b + c * c + d * d).sqrt().max(1.0);
|
||||
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
|
||||
};
|
||||
let o = self.appearance.outset();
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
@@ -362,7 +397,7 @@ impl Node {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints (see `clip_paint`) strokes over the clip edge.
|
||||
let clip = children.first()?;
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) {
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) || clip.extras().clip_pieces {
|
||||
clip.visual(symbols)
|
||||
} else {
|
||||
clip.geometric(symbols)
|
||||
@@ -573,6 +608,18 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no
|
||||
/// node after it is visited, and the break is returned.
|
||||
pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow<B>) -> std::ops::ControlFlow<B> {
|
||||
f(self)?;
|
||||
if let Some(ch) = self.children() {
|
||||
for c in ch {
|
||||
c.try_walk(f)?;
|
||||
}
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
/// Count of nodes in this subtree, ruler guides left out.
|
||||
pub fn count(&self) -> usize {
|
||||
let mut n = 0;
|
||||
@@ -716,6 +763,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 +810,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 +867,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"
|
||||
|
||||
@@ -23,6 +23,8 @@ 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;
|
||||
e.clip_pieces = true;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -69,10 +71,14 @@ fn extras_are_written_flat_in_order() {
|
||||
"shape_mode",
|
||||
"envelope_edit_margin",
|
||||
"pixel_aligned",
|
||||
"warp_piece",
|
||||
"clip_pieces",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(v["pixel_aligned"], true);
|
||||
assert_eq!(v["warp_piece"], true);
|
||||
assert_eq!(v["clip_pieces"], 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 +601,235 @@ 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);
|
||||
}
|
||||
|
||||
/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its
|
||||
/// children, its later siblings or its ancestors' later siblings.
|
||||
#[test]
|
||||
fn try_walk_ends_at_the_break() {
|
||||
use std::ops::ControlFlow;
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]);
|
||||
let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]);
|
||||
let mut all = vec![];
|
||||
root.walk(&mut |n| all.push(n.id));
|
||||
let mut seen = vec![];
|
||||
assert_eq!(
|
||||
root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
ControlFlow::<()>::Continue(())
|
||||
}),
|
||||
ControlFlow::Continue(())
|
||||
);
|
||||
assert_eq!(seen, all, "without a break it visits what walk visits, in the same order");
|
||||
seen.clear();
|
||||
let flow = root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
Loaded 100 of 1487 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user