Merge main into fix/ai-scatter-brush-art-upright

This commit is contained in:
dotCooCoo committed 2026-11-17 09:41:16 -08:00
commit 2733c8c85c
1266 files changed
+209157 -17392

No files matched your search

+5
View File
@@ -31,3 +31,8 @@ jobs:
require-craft-fonts: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
run-package-check: true
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
# four jobs and again with two. One rustc at a time; it still uses every core.
cargo-build-extra-args: "-j 1"
cargo-test-extra-args: "-j 1"
Generated
+412 -105
View File
File diff suppressed because it is too large. Load diff
+47 -34
View File
@@ -11,27 +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-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 = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
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 = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
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" }
@@ -89,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.
@@ -104,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
@@ -128,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"
@@ -171,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" }
+122
View File
@@ -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.
*/
+2 -1
View File
@@ -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.
+17 -4
View File
@@ -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
@@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | 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 |
@@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| 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
@@ -124,12 +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.
@@ -137,9 +145,12 @@ 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.
@@ -221,6 +232,8 @@ 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. |
+2 -1
View File
@@ -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);
+49 -4
View File
@@ -8,23 +8,40 @@
//! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none:
//! heartbeats alone decide there.
#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::collections::{BTreeMap, BTreeSet};
#[cfg(target_arch = "wasm32")]
use std::sync::{Arc, Mutex};
#[cfg(target_arch = "wasm32")]
use js_sys::{Function, Promise, Reflect};
#[cfg(target_arch = "wasm32")]
use vectorcraft_engine::cmd::recovery::Hold;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast as _;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::closure::Closure;
/// How often the snapshot of the locks held is refreshed (ms).
#[cfg(target_arch = "wasm32")]
const REFRESH_MS: i32 = 10_000;
/// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was
/// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under
/// that is safe; an older snapshot counts every area as held.
const FRESH_MS: f64 = 60_000.0;
/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on
/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later
/// than `now`.
fn trusted(asked: f64, now: f64) -> bool {
(0.0..=FRESH_MS).contains(&(now - asked))
}
#[cfg(target_arch = "wasm32")]
thread_local! {
/// What releases each lock this tab holds, by name: it resolves the promise the lock is held
/// by (wasm runs on one thread).
@@ -32,26 +49,31 @@ thread_local! {
}
/// The locks of the page, named `<prefix><area>`.
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct WebLocks {
prefix: &'static str,
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms since
/// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms on
/// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does
/// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// [`REFRESH_MS`] and read from here.
seen: Arc<Mutex<(f64, BTreeSet<String>)>>,
}
/// `navigator.locks`, if the browser has it here.
#[cfg(target_arch = "wasm32")]
fn manager() -> Option<JsValue> {
let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?;
locks.is_object().then_some(locks)
}
/// Method `name` of `obj`.
#[cfg(target_arch = "wasm32")]
fn method(obj: &JsValue, name: &str) -> Option<Function> {
Reflect::get(obj, &name.into()).ok()?.dyn_into().ok()
}
#[cfg(target_arch = "wasm32")]
impl WebLocks {
/// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when
/// the browser has none or won't say which are held (heartbeats alone decide then).
@@ -75,7 +97,7 @@ impl WebLocks {
/// Take a new snapshot of the locks held.
async fn refresh(&self) -> Option<()> {
let m = manager()?;
let asked = js_sys::Date::now();
let asked = vectorcraft_ui_egui::now_ms();
let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?;
let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?;
let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?);
@@ -91,7 +113,7 @@ impl WebLocks {
/// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell.
pub fn held(&self, area: &str) -> bool {
let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area)
!trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area)
}
/// Hold `area`'s lock until the returned hold is dropped (or the page goes).
@@ -110,8 +132,10 @@ impl WebLocks {
}
/// A lock this tab holds (by name), released when dropped.
#[cfg(target_arch = "wasm32")]
struct LockHold(String);
#[cfg(target_arch = "wasm32")]
impl Drop for LockHold {
fn drop(&mut self) {
if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) {
@@ -120,3 +144,24 @@ impl Drop for LockHold {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_is_trusted_for_a_minute() {
assert!(trusted(1_000.0, 1_000.0));
assert!(trusted(1_000.0, 1_000.0 + FRESH_MS));
assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS));
// Before the first snapshot every area counts as held.
assert!(!trusted(f64::NEG_INFINITY, 0.0));
}
#[test]
fn a_snapshot_stamped_later_than_now_is_not_trusted() {
// A clock that went back reads an old snapshot as taken in the future.
assert!(!trusted(5_000_000.0, 1_000.0));
assert!(!trusted(1_001.0, 1_000.0));
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ mod api;
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
mod keys;
#[cfg(target_arch = "wasm32")]
#[cfg(any(target_arch = "wasm32", test))]
mod locks;
#[cfg(any(target_arch = "wasm32", test))]
mod pencil;
+3 -26
View File
@@ -108,37 +108,14 @@ 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)))]
hide_before_teardown(self.winit_window.as_deref());
super::quit_windows::before_teardown(self.winit_window.as_deref());
end_before_teardown(self.frames);
}
}
/// The main window as [`hide_before_teardown`] sees it.
#[cfg(not(any(target_os = "macos", windows)))]
pub(crate) trait QuittingWindow {
fn hide(&self);
}
#[cfg(not(any(target_os = "macos", windows)))]
impl QuittingWindow for winit::window::Window {
fn hide(&self) {
self.set_visible(false);
}
}
/// On Linux and the BSDs, hide the main window 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
/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
/// cannot hide a Wayland window.
#[cfg(not(any(target_os = "macos", windows)))]
pub(crate) fn hide_before_teardown<W: QuittingWindow + ?Sized>(window: Option<&W>) {
if let Some(window) = window {
window.hide();
}
}
impl App {
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
/// focused, shown window whose windows had input waits for the renderer and the next frame,
+683 -76
View File
@@ -11,13 +11,14 @@
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG,
//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a
//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app
//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads copied
//! files (`text/uri-list`), SVG, text and PNG. A clipboard that can't be opened is tried again
//! after a wait that grows to a minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A
//! file of more than 64 MiB is skipped before it is read.
use std::io::{Cursor, Read};
use std::path::PathBuf;
@@ -144,9 +145,28 @@ fn dib_image(dib: &[u8]) -> Option<image::RgbaImage> {
Some(img)
}
/// The most bytes a paste takes from another app (untrusted data), VectorCraft's own limit: a copied
/// file of more is skipped, and on Wayland a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read
/// whole. Only its first bytes are read to tell, so other files cost little.
/// whole, at most [`MAX_BYTES`]. Only its first bytes are read to tell, so other files cost little.
fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
copied_file_within(paths, mimes, MAX_BYTES)
}
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
#[cfg_attr(windows, allow(dead_code))]
fn takes_files(mimes: &[&'static str]) -> bool {
mimes.iter().any(|&m| m != TEXT)
}
/// [`copied_file`] with a file of more than `limit` bytes skipped.
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
// A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at.
if paths.len() > MAX_URIS {
return None;
}
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -164,22 +184,164 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
if !std::fs::metadata(&path).ok()?.is_file() {
return None;
}
let mut file = std::fs::File::open(&path).ok()?;
// The file opened may not be the one looked at: its size is checked before any read.
let meta = file.metadata().ok()?;
if !meta.is_file() || meta.len() > limit as u64 {
return None;
}
let mut head = Vec::with_capacity(FILE_HEAD);
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
(&mut file).take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
let data = std::fs::read(&path).ok()?;
let data = read_rest(file, head, limit)?;
(!data.is_empty()).then_some(Flavour { mime, data })
})
}
/// `data` (the first bytes read of `file`) followed by the rest of `file`, or `None` when they come
/// to more than `limit` bytes, as when the file grew after its size was checked. At most one byte
/// past `limit` is read.
fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>> {
let more = (limit + 1).saturating_sub(data.len());
file.take(more as u64).read_to_end(&mut data).ok()?;
(data.len() <= limit).then_some(data)
}
/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports
/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and
/// when the copy comes to more than `limit` bytes.
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<Vec<u8>>) -> Option<Vec<u8>> {
size.filter(|&n| n > 0 && n <= limit)?;
copy().filter(|data| data.len() <= limit)
}
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
#[cfg_attr(not(windows), allow(dead_code))]
fn utf8_most(utf16: usize) -> usize {
utf16.div_ceil(2).saturating_mul(3)
}
/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a
/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit`
/// files. Counting stops at the first name past `limit`. A block too short for its header, or
/// whose names would start past its end, is not within.
#[cfg_attr(not(windows), allow(dead_code))]
fn drop_files_within(block: &[u8], limit: usize) -> bool {
let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?));
let (Some(start), Some(wide)) = (field(0), field(16)) else {
return false;
};
let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else {
return false;
};
let (mut count, mut in_name) = (0usize, false);
for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) {
if unit.iter().all(|&b| b == 0) {
if !in_name {
break;
}
in_name = false;
} else if !in_name {
in_name = true;
count += 1;
if count > limit {
return false;
}
}
}
true
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
/// The local files a `text/uri-list` names, in order ([`file_uri_path`]). Each line holds one URI
/// and a line that starts with `#` is a comment (RFC 2483, section 5); lines end in CRLF or LF.
/// Lines that are not UTF-8 and URIs that don't name a local file are skipped. A list of more than
/// [`MAX_URIS`] URIs names none.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn uri_list_paths(list: &[u8]) -> Vec<PathBuf> {
let uris: Vec<&[u8]> = list
.split(|&b| b == b'\n')
.map(|line| line.strip_suffix(b"\r").unwrap_or(line))
.filter(|line| !line.is_empty() && !line.starts_with(b"#"))
.take(MAX_URIS + 1)
.collect();
if uris.len() > MAX_URIS {
return vec![];
}
uris.into_iter().filter_map(|uri| file_uri_path(std::str::from_utf8(uri).ok()?)).collect()
}
/// The local files GNOME Files' `x-special/gnome-copied-files` names: a first line of `copy` or
/// `cut`, then one URI a line, read as [`uri_list_paths`] reads them. A paste places the files'
/// art either way and leaves the files where they are. No files when the first line is neither.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn gnome_copied_paths(list: &[u8]) -> Vec<PathBuf> {
let (action, uris) = match list.iter().position(|&b| b == b'\n') {
Some(end) => (list.get(..end).unwrap_or_default(), list.get(end + 1..).unwrap_or_default()),
None => (list, &[][..]),
};
match action.strip_suffix(b"\r").unwrap_or(action) {
b"copy" | b"cut" => uri_list_paths(uris),
_ => vec![],
}
}
/// The absolute path a `file:` URI names on this machine: `file:/path`, `file:///path` or
/// `file://localhost/path` (RFC 8089, section 2; scheme and host in any letter case), its percent
/// escapes decoded once (RFC 3986, section 2.1) and a fragment (`#…`) left out. None for another
/// scheme, another host, a relative path, a query (`?…`), a bad escape, an escaped NUL or a path
/// that is not UTF-8 once decoded.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn file_uri_path(uri: &str) -> Option<PathBuf> {
let uri = uri.trim_matches(|c: char| c.is_ascii_whitespace());
let uri = uri.split_once('#').map_or(uri, |(before, _)| before);
if uri.contains('?') {
return None;
}
let scheme = uri.get(..5).filter(|s| s.eq_ignore_ascii_case("file:"))?;
let rest = uri.get(scheme.len()..)?;
let path = match rest.strip_prefix("//") {
Some(authority_and_path) => {
let slash = authority_and_path.find('/')?;
let host = authority_and_path.get(..slash)?;
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return None;
}
authority_and_path.get(slash..)?
}
None => rest.starts_with('/').then_some(rest)?,
};
let mut bytes = Vec::with_capacity(path.len());
let mut it = path.bytes();
while let Some(b) = it.next() {
if b == b'%' {
let hex = |d: Option<u8>| char::from(d?).to_digit(16);
let (hi, lo) = (hex(it.next())?, hex(it.next())?);
bytes.push(u8::try_from(hi * 16 + lo).ok()?);
} else {
bytes.push(b);
}
}
if bytes.contains(&0) {
return None;
}
String::from_utf8(bytes).ok().map(PathBuf::from)
}
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
use std::num::{NonZeroU32, NonZeroUsize};
use clipboard_win::{formats, options::NoClear, raw};
use super::{
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png,
dib_image, drop_files_within, png_flavour, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -266,8 +428,11 @@ mod win {
let mut files = vec![];
{
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
// None copied when the clipboard holds no file list.
let _ = raw::get_file_list_path(&mut files);
// None copied when the clipboard holds no file list, or one of more than MAX_BYTES
// or MAX_URIS files: the list is counted before its names are copied.
if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) {
let _ = raw::get_file_list_path(&mut files);
}
}
// The files are read with the clipboard closed again, not keeping other apps waiting.
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
@@ -286,44 +451,64 @@ mod win {
}
}
/// Read the first registered format of `mime` the clipboard holds into `data`.
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
data.clear();
raw::get_vec(id, data).is_ok() && !data.is_empty()
/// The size the clipboard reports for format `id`, while it is open.
fn size_of(id: u32) -> Option<usize> {
raw::size(id).map(NonZeroUsize::get)
}
/// The data of format `id`, while the clipboard is open, copied only when its size is at most
/// `limit` bytes ([`copy_within`]).
fn copy_registered(id: u32, limit: usize) -> Option<Vec<u8>> {
copy_within(size_of(id), limit, || {
let mut data = vec![];
raw::get_vec(id, &mut data).ok()?;
Some(data)
})
}
/// The first registered format of `mime` the clipboard holds that is not empty and at most
/// [`MAX_BYTES`]; a larger one is skipped and the next tried.
fn read_registered(mime: &str) -> Option<Vec<u8>> {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
}
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
/// `size` gives each format's size before `get` copies it, and a format of more than
/// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried.
pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option<usize>, mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect();
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
}
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
/// the work that comes back decodes each captured format in preference order.
/// the work that comes back decodes each captured format in preference order. Text whose
/// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read.
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
let mut data = vec![];
let mime = match mime {
BITMAP if read_registered(PNG, &mut data) => PNG,
BITMAP => {
return read_dibs(|id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
let (mime, mut data) = match mime {
BITMAP => match read_registered(PNG) {
Some(png) => (PNG, png),
None => {
return read_dibs(size_of, |id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
},
TEXT => {
raw::get_string(&mut data).ok()?;
TEXT
let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || {
let mut text = vec![];
raw::get_string(&mut text).ok()?;
Some(text)
})?;
(TEXT, text)
}
m if read_registered(m, &mut data) => m,
_ => return None,
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
if mime == SVG
@@ -623,7 +808,7 @@ mod portable {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of};
/// What our last write put on the clipboard.
#[derive(Clone)]
@@ -637,7 +822,7 @@ mod portable {
}
/// A read of arboard's clipboard.
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Request {
Text,
Image,
@@ -709,6 +894,19 @@ mod portable {
}
}
/// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one
/// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes`
/// is not text (`files` reads the list). The list is read only when the text doesn't do, and no
/// copied file is opened: Paste checks the files themselves.
fn arboard_has<B>(
mimes: &[&'static str],
cb: &mut B,
text: impl FnOnce(&mut B) -> Result<String, String>,
files: impl FnOnce(&mut B) -> Vec<PathBuf>,
) -> bool {
(mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty())
}
/// `request` read on `reads`' worker, waiting `wait` at most.
#[cfg(test)]
fn read_within(reads: &mut super::loads::Loads<Request, Answer>, request: Request, wait: Duration) -> Answer {
@@ -1094,7 +1292,9 @@ mod portable {
}
}
/// Files copied in a file manager (none where the backend can't read a file list).
/// Files copied in a file manager, read through arboard. The Wayland core protocol reads
/// its file list with the rest of a paste
/// ([`DataClipboard::read`](super::wayland::DataClipboard::read)).
fn file_list(&mut self) -> Vec<PathBuf> {
match self {
Self::Arboard(cb) => cb.read(Request::Files).files(),
@@ -1233,8 +1433,9 @@ mod portable {
}
/// Text and copied files are read here, and work that reads arboard's image comes back. On
/// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here,
/// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most.
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
/// waits [`IMAGE_WAIT`] at most.
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let cb = self.cb(Asker::User).ok()?;
#[cfg(target_os = "linux")]
@@ -1334,10 +1535,11 @@ mod portable {
read
}
/// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
/// core protocol SVG, text or PNG (by the types offered, nothing read). arboard has no
/// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys
/// take it, the menu item waits for text.
/// Text or files copied in a file manager (their list read, no file opened:
/// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the
/// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
/// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it):
/// the paste keys take it, the menu item waits for text or copied files.
fn has(&mut self, mimes: &[&'static str]) -> bool {
#[cfg(target_os = "macos")]
if super::mac::has(mimes) {
@@ -1348,7 +1550,7 @@ mod portable {
if let Backend::Wayland(wl) = cb {
return wl.has(mimes);
}
mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty())
arboard_has(mimes, cb, Backend::get_text, Backend::file_list)
}
}
@@ -1512,6 +1714,40 @@ mod portable {
assert!(Answer::Text(Ok("art.svg".into())).files().is_empty());
}
#[test]
fn paste_is_available_for_files_copied_in_a_file_manager() {
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
/// What the clipboard holds, and which reads [`arboard_has`] made.
struct Held {
text: Option<String>,
files: Vec<PathBuf>,
reads: Vec<Request>,
}
fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec<Request>) {
let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] };
let text = |h: &mut Held| {
h.reads.push(Request::Text);
h.text.clone().ok_or_else(|| "no text".to_string())
};
let files = |h: &mut Held| {
h.reads.push(Request::Files);
h.files.clone()
};
let has = arboard_has(mimes, &mut held, text, files);
(has, held.reads)
}
// Files a file manager copied, with no text: the Paste menu item is available.
assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files]));
// Text does, and the list is not read.
assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text]));
// An empty list and no text: nothing to paste.
assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files]));
// A paste of text alone can't take copied files, and their list is not read.
assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text]));
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
@@ -1784,12 +2020,13 @@ mod portable {
/// window's own Wayland connection: what Copy and Paste use where the compositor lacks the
/// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on
/// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its
/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste
/// check looks at the types offered without reading any data. The protocol gives the clipboard to
/// the window with the keyboard focus only. A worker thread handles the protocol's events and
/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads
/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and
/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
/// text under each of [`TEXT_TYPES`]; Paste reads the files a file manager copied
/// ([`FILE_LISTS`]), then the clipboard's SVG, text and PNG, and the paste check looks at the types
/// offered without reading any data. The protocol gives the clipboard to the window with the
/// keyboard focus only. A worker thread handles the protocol's events and starts a thread for each
/// paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads run on another worker and
/// take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, file lists, SVG and PNG as long as
/// a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
/// a paste to wait for off the UI thread, as arboard's are. A read or send whose pipe moves no data
/// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread.
#[cfg(target_os = "linux")]
@@ -1817,14 +2054,17 @@ mod wayland {
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::{BITMAP, Flavour, PNG, SVG, TEXT};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
/// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own
/// limit: a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// What reads the files a file list names.
type PathsOf = fn(&[u8]) -> Vec<PathBuf>;
/// The types files copied in a file manager are offered under, each with what reads its files,
/// best first: `text/uri-list` (RFC 2483), and GNOME Files' own list, read only when the first
/// names no file.
const FILE_LISTS: [(&str, PathsOf); 2] = [("text/uri-list", uri_list_paths), ("x-special/gnome-copied-files", gnome_copied_paths)];
/// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing.
const MAX_SENDS: usize = 8;
/// The most types of an offer that are kept (untrusted data).
@@ -1905,6 +2145,30 @@ mod wayland {
Some(first)
}
/// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case.
fn file_list_type(offered: &[String]) -> Option<&str> {
FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str)
}
/// The first file a file manager copied that pastes as one of `mimes` ([`copied_file`]), from
/// the first of [`FILE_LISTS`] among `offered` that names a file, `read` reading each list.
fn copied(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option<Vec<u8>>) -> Option<Flavour> {
if !takes_files(mimes) {
return None;
}
let paths = FILE_LISTS.iter().find_map(|(list, paths_of)| {
let wire = offered.iter().find(|o| o.eq_ignore_ascii_case(list))?;
Some(paths_of(&read(wire)?)).filter(|paths| !paths.is_empty())
})?;
copied_file(paths, mimes)
}
/// What a paste of one of `mimes` takes: the first copied file that is art ([`copied`]), else
/// what [`pick`] takes.
fn pick_pasted(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option<Vec<u8>>) -> Option<Flavour> {
copied(offered, mimes, &mut read).or_else(|| pick(offered, mimes, read))
}
/// The time `idle` from now; None when that is past the clock's range (no limit).
fn idle_until(idle: Duration) -> Option<Instant> {
Instant::now().checked_add(idle)
@@ -2089,9 +2353,9 @@ mod wayland {
impl Unanswered {
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
/// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read
/// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the
/// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
@@ -2103,7 +2367,9 @@ mod wayland {
}
seen.offered.clone()
};
pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok())
pick_pasted(&offered, mimes, |wire| {
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
})
}
}
@@ -2136,12 +2402,36 @@ mod wayland {
}
}
/// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here,
/// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and
/// waited for, `wait` at most, by the work that comes back. When that read fails or is
/// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until
/// `wait` after the first was sent, [`LOAD_WAIT`] at least.
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
/// by the work that comes back. When that read fails or is empty, the work reads the rest
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
/// after the first was sent, [`LOAD_WAIT`] at least.
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
if takes_files(mimes) {
let offered = lock(&self.seen).offered.clone();
if let Some(list) = file_list_type(&offered).map(str::to_string) {
let sent = Instant::now();
let answer = self.loads.ask(list.clone()).ok()?;
self.unanswered = None;
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
return Some(ClipboardRead::Later(Box::new(move || {
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
// The list asked for here is read from its answer, every other type anew.
let mut first = Some((list, answer));
pick_pasted(&offered, &mimes, |wire| {
let answer = match first.take_if(|(list, _)| list.as_str() == wire) {
Some((_, answer)) => answer,
None => reads.ask(wire.to_string()).ok()?,
};
wait_for_answer(&answer, left()).ok()?.ok()
})
})));
}
}
mimes.iter().enumerate().find_map(|(i, &mime)| {
let wire = self.wire(mime)?;
if mime == TEXT {
@@ -2163,10 +2453,11 @@ mod wayland {
})
}
/// Whether the clipboard offers one of `mimes`; nothing is read.
/// Whether the clipboard offers one of `mimes`, or files a file manager copied when a paste
/// of `mimes` can take a file; nothing is read.
pub(super) fn has(&self, mimes: &[&'static str]) -> bool {
let seen = lock(&self.seen);
mimes.iter().any(|m| wire_type(m, &seen.offered).is_some())
(takes_files(mimes) && file_list_type(&seen.offered).is_some()) || mimes.iter().any(|m| wire_type(m, &seen.offered).is_some())
}
/// Whether the clipboard holds this connection's last Copy.
@@ -2835,6 +3126,85 @@ mod wayland {
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
/// Reads of a clipboard holding `data` by type, answered at once.
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
let types: Vec<&str> = types.iter().map(String::as_str).collect();
Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types))))
}
/// The `file:` URI of `path`, its spaces escaped.
fn file_uri(path: &std::path::Path) -> String {
format!("file://{}", path.display().to_string().replace(' ', "%20"))
}
/// What a paste of `mimes` takes from `reads`.
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
match reads.read(mimes, Duration::from_secs(600))? {
ClipboardRead::Now(f) => Some((f.mime, f.data)),
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
}
}
#[test]
fn files_copied_in_a_file_manager_paste_as_their_art() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let d = tempfile::Builder::new().prefix("vectorcraft-wayland-files-").tempdir().unwrap();
let (notes, red) = (d.path().join("notes.txt"), d.path().join("red image.png"));
let mut png = vec![];
image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
std::fs::write(&notes, "not art").unwrap();
std::fs::write(&red, &png).unwrap();
let list = |paths: &[&std::path::Path]| paths.iter().map(|p| file_uri(p) + "\r\n").collect::<String>().into_bytes();
let held = |types: &[(&str, Vec<u8>)]| reads_holding(types.iter().map(|(t, d)| (t.to_string(), d.clone())).collect());
let text = ("text/plain;charset=utf-8", b"the files' paths".to_vec());
// A file list alone enables Paste and pastes the first file that is art.
let mut reads = held(&[("text/uri-list", list(&[&notes, &red]))]);
assert!(reads.has(&PASTE_ORDER) && reads.has(&[BITMAP]));
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
// A paste of text alone takes no file.
assert!(!reads.has(&[TEXT]));
assert_eq!(paste(&mut reads, &[TEXT]), None);
// The files come before the other types offered, as on the other platforms; the type in
// any letter case.
let mut reads = held(&[(SVG, b"<svg/>".to_vec()), text.clone(), ("Text/URI-List", list(&[&red]))]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
assert_eq!(paste(&mut reads, &[TEXT]), Some((TEXT, text.1.clone())));
// With no file that is art, the paste takes the other types.
let mut reads = held(&[("text/uri-list", list(&[&notes, &d.path().join("gone.png")])), text.clone()]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((TEXT, text.1.clone())));
let mut reads = held(&[("text/uri-list", b"https://example.com/art.png\r\n".to_vec())]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), None);
// GNOME Files' own list, alone or when the URI list names no local file.
let gnome = [b"copy\n".to_vec(), file_uri(&red).into_bytes()].concat();
let mut reads = held(&[("x-special/gnome-copied-files", gnome.clone())]);
assert!(reads.has(&PASTE_ORDER));
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
let mut reads = held(&[("text/uri-list", b"file://server/art.png\r\n".to_vec()), ("x-special/gnome-copied-files", gnome)]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
// KDE's cut marker is not a file list.
let mut reads = held(&[("application/x-kde-cutselection", b"1".to_vec())]);
assert!(!reads.has(&PASTE_ORDER));
assert_eq!(paste(&mut reads, &PASTE_ORDER), None);
}
#[test]
fn a_file_list_that_cant_be_read_gives_way_to_the_other_types() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let offered = offered(&["text/uri-list", "text/plain"]);
let mut asked = vec![];
let f = pick_pasted(&offered, &PASTE_ORDER, |wire| {
asked.push(wire.to_string());
(wire == "text/plain").then(|| b"words".to_vec())
});
assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"words".to_vec())));
assert_eq!(asked, ["text/uri-list", "text/plain"]);
}
}
}
@@ -2846,7 +3216,7 @@ mod mac {
use objc2_app_kit::NSPasteboard;
use objc2_foundation::{NSArray, NSString};
use super::{Flavour, pasteboard_types};
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
@@ -2857,13 +3227,16 @@ mod mac {
})
}
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is
/// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger
/// type is skipped and the next tried.
pub fn read(mime: &str) -> Option<Flavour> {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
(!data.is_empty()).then_some(Flavour { mime, data })
let held = pasteboard.dataForType(&NSString::from_str(t))?;
let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?;
Some(Flavour { mime, data })
})
})
}
@@ -2952,6 +3325,211 @@ mod tests {
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
}
/// A copied file of more than 64 MiB is skipped before it is read, and the next one pastes.
#[test]
fn an_oversized_copied_file_is_skipped_before_it_is_read() {
let d = dir("oversized");
let (big, small) = (d.path().join("big.png"), d.path().join("small.png"));
std::fs::write(&big, png(2, 2)).unwrap();
// Sparse where the file system allows: no 64 MiB is written.
std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_BYTES as u64 + 1).unwrap();
std::fs::write(&small, png(3, 2)).unwrap();
assert!(copied_file(vec![big.clone()], &PASTE_ORDER).is_none());
let f = copied_file(vec![big, small], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
}
/// A copied file of exactly the limit pastes; one byte more and it is skipped.
#[test]
fn a_copied_file_pastes_up_to_the_limit() {
let d = dir("limit");
let art = d.path().join("art.svg");
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
std::fs::write(&art, svg).unwrap();
let read = |limit| copied_file_within(vec![art.clone()], &PASTE_ORDER, limit).map(|f| f.data);
assert_eq!(read(svg.len()), Some(svg.as_bytes().to_vec()));
assert_eq!(read(svg.len() - 1), None);
}
/// A file that grows past the limit after its size was checked is read to one byte past the
/// limit and refused.
#[test]
fn the_rest_of_a_file_is_read_to_the_limit_at_most() {
let read = |len: usize, head: usize| {
let bytes = vec![7u8; len];
let mut file = Cursor::new(bytes);
let mut first = vec![0; head];
file.read_exact(&mut first).unwrap();
(read_rest(&mut file, first, 16).map(|d| d.len()), file.position())
};
assert_eq!(read(16, 4), (Some(16), 16));
assert_eq!(read(0, 0), (Some(0), 0));
assert_eq!(read(17, 4), (None, 17));
assert_eq!(read(1000, 4), (None, 17));
// First bytes already past the limit: nothing more is read.
assert_eq!(read(1000, 20), (None, 20));
}
fn uri_paths(list: &[u8]) -> Vec<String> {
uri_list_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect()
}
#[test]
fn a_uri_list_names_the_local_files_of_its_lines() {
// CRLF or LF, comment lines and blank lines.
assert_eq!(uri_paths(b"# copied\r\nfile:///home/a/one.svg\r\n\r\nfile:///home/a/two.png\n"), ["/home/a/one.svg", "/home/a/two.png"]);
assert_eq!(uri_paths(b"file:///a.svg"), ["/a.svg"]);
// Percent escapes are decoded once; `+` and an escaped `#` are part of the name.
assert_eq!(uri_paths(b"file:///home/a/red%20image.png"), ["/home/a/red image.png"]);
assert_eq!(uri_paths(b"file:///home/a/caf%C3%A9.svg\nfile:///home/a/caf\xC3\xA9.svg"), ["/home/a/café.svg", "/home/a/café.svg"]);
assert_eq!(uri_paths(b"file:///a/%231+2.svg"), ["/a/#1+2.svg"]);
assert_eq!(uri_paths(b"file:///a/100%2525.svg"), ["/a/100%25.svg"]);
// No host, `localhost` in any case, and the short form name this machine; a fragment is
// left out.
assert_eq!(
uri_paths(b"file://localhost/a.svg\nFILE://LocalHost/b.svg\nfile:/c.svg\nfile:///d.svg#page=2"),
["/a.svg", "/b.svg", "/c.svg", "/d.svg"]
);
// Other hosts and schemes, relative paths, queries, bad escapes, an escaped NUL, a name
// that is not UTF-8 once decoded and a line that is not UTF-8 name no file.
for uri in [
&b"file://server/a.svg"[..],
b"https://example.com/a.svg",
b"file:a.svg",
b"file://",
b"file://localhost",
b"file:///a.svg?x=1",
b"file:///a%2",
b"file:///a%zz.svg",
b"file:///a%00b.svg",
b"file:///a%FF.svg",
b"file:///a\xFF.svg",
b"/home/a/one.svg",
b"#file:///a.svg",
] {
assert!(uri_list_paths(uri).is_empty(), "{}", String::from_utf8_lossy(uri));
}
// The files beside a URI that names none are kept.
assert_eq!(uri_paths(b"https://example.com/a.svg\r\nfile:///b.svg\r\n"), ["/b.svg"]);
assert!(uri_list_paths(b"").is_empty());
}
#[test]
fn a_uri_list_longer_than_the_limit_names_no_file() {
assert_eq!(MAX_URIS, 1024);
let list = |n: usize| (0..n).map(|i| format!("# file {i}\r\nfile:///f{i}.svg\r\n")).collect::<String>();
// Comment lines don't count.
assert_eq!(uri_list_paths(list(MAX_URIS).as_bytes()).len(), MAX_URIS);
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
}
/// A copied file list of more than 1,024 files pastes none, before any file is looked at,
/// wherever the list came from; 1,024 files paste the first that is art.
#[test]
fn a_copied_file_list_longer_than_the_limit_pastes_no_file() {
let d = dir("many");
let art = d.path().join("art.svg");
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::<Vec<_>>();
let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat();
assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// The art first: no file is opened past the count.
let first = [vec![art.clone()], missing(MAX_URIS)].concat();
assert!(copied_file(first, &PASTE_ORDER).is_none());
assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none());
}
/// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit,
/// and the copy is not asked for otherwise.
#[test]
fn clipboard_data_is_copied_only_when_its_size_fits() {
let copy = |size: Option<usize>, got: usize| {
let mut asked = false;
let data = copy_within(size, 8, || {
asked = true;
Some(vec![1; got])
});
(data.map(|d| d.len()), asked)
};
assert_eq!(copy(Some(8), 8), (Some(8), true));
assert_eq!(copy(Some(1), 1), (Some(1), true));
for size in [None, Some(0), Some(9), Some(usize::MAX)] {
assert_eq!(copy(size, 1), (None, false), "{size:?}");
}
// Data that comes to more than the limit after all is refused.
assert_eq!(copy(Some(8), 9), (None, true));
assert_eq!(MAX_BYTES, 64 << 20);
}
/// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before
/// the text is converted: a block that could pass the limit as UTF-8 is not read.
#[test]
fn text_is_bounded_by_what_its_utf8_could_come_to() {
for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] {
let utf16 = text.encode_utf16().count() * 2;
assert!(utf8_most(utf16) >= text.len(), "{text:?}");
}
// Every code unit at 3 bytes of UTF-8: the bound is exact.
assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len());
let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some();
assert!(copied(MAX_BYTES / 3 * 2));
assert!(!copied(MAX_BYTES / 3 * 2 + 2));
assert!(!copied(MAX_BYTES));
assert_eq!(utf8_most(usize::MAX), usize::MAX);
}
/// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one
/// byte a character, each ended by a NUL, and one more NUL.
fn drop_files(names: &[&str], wide: bool) -> Vec<u8> {
let mut block = vec![];
block.extend(20u32.to_le_bytes());
block.extend([0u8; 12]);
block.extend(u32::from(wide).to_le_bytes());
for name in names.iter().copied().chain([""]) {
for unit in name.encode_utf16().chain([0]) {
if wide {
block.extend(unit.to_le_bytes());
} else {
block.push(unit as u8);
}
}
}
block
}
#[test]
fn a_windows_file_list_is_counted_before_its_names_are_read() {
let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::<Vec<_>>();
for wide in [true, false] {
let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::<Vec<_>>(), wide);
assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}");
assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}");
assert!(drop_files_within(&list(0), MAX_URIS), "{wide}");
// Names past the list's closing NUL are not counted.
let mut ended = list(2);
ended.extend(list(MAX_URIS + 1).get(20..).unwrap());
assert!(drop_files_within(&ended, 2), "{wide}");
// A list cut short counts the names it holds.
assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}");
}
// A header cut short, or names that would start past the block's end.
assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS));
let mut past = drop_files(&["a"], true);
past[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(!drop_files_within(&past, MAX_URIS));
}
#[test]
fn gnome_files_list_names_its_files_after_copy_or_cut() {
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
assert_eq!(paths(b"copy\nfile:///a.svg\nfile:///b%20c.png"), ["/a.svg", "/b c.png"]);
assert_eq!(paths(b"cut\r\nfile:///a.svg\r\n"), ["/a.svg"]);
// Another first line, none, or no files.
for list in [&b"move\nfile:///a.svg"[..], b"file:///a.svg\nfile:///b.svg", b"copy", b"", b"Copy\nfile:///a.svg"] {
assert!(gnome_copied_paths(list).is_empty(), "{}", String::from_utf8_lossy(list));
}
}
/// A DIB of `w`×`h` pixels (top row first when `h` is negative): a `header`-byte header (40,
/// or 124 for a BITMAPV5HEADER with BGRA masks), `extra` (the masks after a 40-byte header, a
/// colour table), then `rows`, each padded to 4 bytes.
@@ -2994,19 +3572,48 @@ mod tests {
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
let mut captured = Vec::new();
let read = win::read_dibs(|id| {
captured.push(id);
match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
}
})
let get = |id: u32| match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
};
let read = win::read_dibs(
|id| get(id).map(|d| d.len()),
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
let flavour = read.flavour().unwrap();
assert_eq!(flavour.mime, PNG);
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
// A bitmap larger than the limit is not copied, and the other one still pastes.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
// Each format has the limit to itself: a first one at the limit that doesn't decode
// leaves the second to paste.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
}
#[test]
+5 -1
View File
@@ -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();
@@ -413,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()
+63 -18
View File
@@ -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;
@@ -59,7 +63,10 @@ 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)]
@@ -70,6 +77,7 @@ mod window_frame;
mod windows_alt_codes;
#[cfg(windows)]
mod windows_cores;
mod windows_screen_color;
mod windows_stylus;
mod xwayland;
@@ -90,8 +98,6 @@ mod titlebar;
use app::bring_window_forward;
use app::native_input_hook;
use app::open_or_hold;
#[cfg(all(test, not(any(target_os = "macos", windows))))]
use app::{QuittingWindow, hide_before_teardown};
use host_services::services;
#[cfg(all(test, feature = "wgpu"))]
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
@@ -122,7 +128,7 @@ struct App {
/// 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),
/// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`).
/// 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,
@@ -158,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
@@ -177,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");
@@ -196,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) => {
@@ -235,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 })
}
@@ -253,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,
};
@@ -275,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),
}
@@ -418,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()));
@@ -454,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")]
@@ -494,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);
@@ -547,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!(
+6 -5
View File
@@ -242,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;
@@ -308,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)) =
@@ -319,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.
+8
View File
@@ -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) {
+243
View File
@@ -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");
}
}
+32 -5
View File
@@ -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, &note))
}
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"));
+280
View File
@@ -0,0 +1,280 @@
//! Takes the app's windows off screen when it quits on Linux and the BSDs, before eframe drops the
//! app. Dropping the app waits up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the
//! clipboard handles to let go, and eframe closes the windows only after that wait.
//!
//! The main window is hidden on X11 (XWayland included). winit cannot hide a Wayland window, so on
//! Linux a Wayland main window is unmapped instead: its surface gets no buffer, and the window stays
//! open with the connection the Wayland clipboard copies and reads on. On Linux the X11 windows of
//! floating panels and documents are recorded as eframe creates and drops them ([`Hooks`]), and
//! quitting unmaps them through an X11 connection of its own. On native Wayland, floating panels and
//! documents are normally drawn inside the main window.
#[cfg(target_os = "linux")]
use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};
#[cfg(target_os = "linux")]
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
/// The main window as quitting sees it.
pub(crate) trait QuittingWindow {
/// The window is a Wayland surface.
fn is_wayland(&self) -> bool;
/// Hides an X11 window.
fn hide(&self);
/// Takes a Wayland window off screen and keeps it open.
fn unmap(&self);
}
impl QuittingWindow for winit::window::Window {
#[cfg(target_os = "linux")]
fn is_wayland(&self) -> bool {
matches!(self.window_handle().map(|h| h.as_raw()), Ok(RawWindowHandle::Wayland(_)))
}
/// The BSDs have no Wayland unmap: their windows are hidden through winit.
#[cfg(not(target_os = "linux"))]
fn is_wayland(&self) -> bool {
false
}
fn hide(&self) {
self.set_visible(false);
}
#[cfg(target_os = "linux")]
fn unmap(&self) {
unmap_wayland(self);
}
#[cfg(not(target_os = "linux"))]
fn unmap(&self) {
self.set_visible(false);
}
}
/// Takes the main window and the floating windows `x11` lists off screen: a Wayland main window is
/// unmapped and any other main window hidden, and `unmap_x11` unmaps the floating windows.
pub(crate) fn off_screen<W: QuittingWindow + ?Sized>(main: Option<&W>, x11: &[u32], unmap_x11: impl FnOnce(&[u32])) {
if let Some(window) = main {
if window.is_wayland() {
window.unmap();
} else {
window.hide();
}
}
if !x11.is_empty() {
unmap_x11(x11);
}
}
/// [`off_screen`] with the running app's main window and the floating windows [`Hooks`] recorded.
/// Runs on quit, before eframe drops the app.
pub(crate) fn before_teardown(main: Option<&winit::window::Window>) {
#[cfg(target_os = "linux")]
off_screen(main, &CHILD_WINDOWS.x11(), unmap_x11);
#[cfg(not(target_os = "linux"))]
off_screen(main, &[], |_| {});
}
/// The X11 windows of floating panels and documents, by viewport, while eframe holds them.
#[cfg(target_os = "linux")]
#[derive(Default)]
pub(crate) struct ChildWindows(Mutex<HashMap<egui::ViewportId, u32>>);
#[cfg(target_os = "linux")]
impl ChildWindows {
/// eframe made `viewport`'s window, with `handle`. The main window, and windows of other window
/// systems, are not recorded; a window made again for the same viewport replaces its record.
pub(crate) fn created(&self, viewport: egui::ViewportId, handle: Option<RawWindowHandle>) {
let mut windows = self.lock();
match handle.and_then(x11_window) {
Some(id) if viewport != egui::ViewportId::ROOT => windows.insert(viewport, id),
_ => windows.remove(&viewport),
};
}
/// eframe dropped `viewport`'s window.
pub(crate) fn destroyed(&self, viewport: egui::ViewportId) {
self.lock().remove(&viewport);
}
/// The recorded windows, in id order.
pub(crate) fn x11(&self) -> Vec<u32> {
let mut ids: Vec<u32> = self.lock().values().copied().collect();
ids.sort_unstable();
ids.dedup();
ids
}
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, u32>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// The X11 window id of `handle`, None for another window system.
#[cfg(target_os = "linux")]
fn x11_window(handle: RawWindowHandle) -> Option<u32> {
match handle {
RawWindowHandle::Xlib(h) => u32::try_from(h.window).ok(),
RawWindowHandle::Xcb(h) => Some(h.window.get()),
_ => None,
}
}
/// The running app's floating windows, which [`Hooks`] records.
#[cfg(target_os = "linux")]
static CHILD_WINDOWS: LazyLock<ChildWindows> = LazyLock::new(ChildWindows::default);
/// Records the windows eframe creates and drops in [`CHILD_WINDOWS`]; set as
/// [`eframe::NativeOptions::viewport_hooks`].
#[cfg(target_os = "linux")]
pub(crate) struct Hooks;
#[cfg(target_os = "linux")]
impl eframe::ViewportHooks for Hooks {
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
CHILD_WINDOWS.created(viewport, window.window_handle().ok().map(|h| h.as_raw()));
}
fn window_destroyed(&self, viewport: egui::ViewportId) {
CHILD_WINDOWS.destroyed(viewport);
}
}
/// Unmaps the X11 `windows` through a connection of its own, and waits until the server has done so.
/// An id whose window is gone gets an error, which is ignored.
#[cfg(target_os = "linux")]
fn unmap_x11(windows: &[u32]) {
use x11rb::protocol::xproto::ConnectionExt as _;
let conn = match x11rb::connect(None) {
Ok((conn, _)) => conn,
Err(e) => {
log::warn!("couldn't reach the X server to hide the floating windows on quit: {e}");
return;
}
};
for &window in windows {
if let Ok(cookie) = conn.unmap_window(window) {
cookie.ignore_error();
}
}
// The server answers once it has handled the requests before this one.
if let Ok(cookie) = conn.get_input_focus() {
let _ = cookie.reply();
}
}
/// Attaches no buffer to `window`'s Wayland surface and commits it, which unmaps the window: the
/// compositor stops showing it, and the window and its connection stay open.
#[cfg(target_os = "linux")]
fn unmap_wayland(window: &winit::window::Window) {
let Some((conn, surface)) = super::portal_save::wayland::surface(window) else { return };
surface.attach(None, 0, 0);
surface.commit();
if let Err(e) = conn.flush() {
log::warn!("couldn't reach the compositor to hide the window on quit: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
/// A main window that records what quitting did to it.
struct Window<'a> {
wayland: bool,
done: &'a RefCell<Vec<String>>,
}
impl QuittingWindow for Window<'_> {
fn is_wayland(&self) -> bool {
self.wayland
}
fn hide(&self) {
self.done.borrow_mut().push("hide".into());
}
fn unmap(&self) {
self.done.borrow_mut().push("unmap".into());
}
}
fn quit(wayland: Option<bool>, x11: &[u32]) -> Vec<String> {
let done = RefCell::new(Vec::new());
let window = wayland.map(|wayland| Window { wayland, done: &done });
off_screen(window.as_ref(), x11, |ids| done.borrow_mut().push(format!("unmap x11 {ids:?}")));
done.into_inner()
}
/// winit cannot hide a Wayland window: quitting unmaps it, and never only asks winit to hide it.
#[test]
fn quitting_unmaps_a_wayland_main_window() {
assert_eq!(quit(Some(true), &[]), ["unmap"]);
}
/// An X11 main window (XWayland included) is hidden, and the floating panels' and documents' X11
/// windows are unmapped with it.
#[test]
fn quitting_hides_an_x11_main_window_and_its_floating_windows() {
assert_eq!(quit(Some(false), &[]), ["hide"]);
assert_eq!(quit(Some(false), &[7, 9]), ["hide", "unmap x11 [7, 9]"]);
}
/// Without a main window (none was made), the floating windows still go, and with none at all
/// nothing is done.
#[test]
fn quitting_without_a_main_window() {
assert_eq!(quit(None, &[3]), ["unmap x11 [3]"]);
assert!(quit(None, &[]).is_empty());
}
#[cfg(target_os = "linux")]
fn xlib(id: std::os::raw::c_ulong) -> Option<RawWindowHandle> {
Some(RawWindowHandle::Xlib(winit::raw_window_handle::XlibWindowHandle::new(id)))
}
#[cfg(target_os = "linux")]
fn viewport(name: &str) -> egui::ViewportId {
egui::ViewportId::from_hash_of(name)
}
/// The floating windows eframe made are recorded until it drops them; the main window, which
/// quitting reaches through winit, is not.
#[cfg(target_os = "linux")]
#[test]
fn floating_x11_windows_are_recorded_while_they_exist() {
let windows = ChildWindows::default();
windows.created(egui::ViewportId::ROOT, xlib(1));
windows.created(viewport("Layers"), xlib(9));
let xcb = winit::raw_window_handle::XcbWindowHandle::new(std::num::NonZeroU32::new(5).expect("not zero"));
windows.created(viewport("Untitled-2"), Some(RawWindowHandle::Xcb(xcb)));
windows.created(viewport("Color"), xlib(7));
assert_eq!(windows.x11(), [5, 7, 9]);
windows.destroyed(viewport("Color"));
assert_eq!(windows.x11(), [5, 9]);
// A viewport that eframe has already dropped, or never made, is no error.
windows.destroyed(viewport("Color"));
windows.destroyed(viewport("Swatches"));
assert_eq!(windows.x11(), [5, 9]);
}
/// A window made again for a viewport replaces its record, and one of another window system, or
/// one whose handle could not be read, removes it.
#[cfg(target_os = "linux")]
#[test]
fn a_window_made_again_replaces_its_record() {
let windows = ChildWindows::default();
windows.created(viewport("Layers"), xlib(9));
windows.created(viewport("Layers"), xlib(11));
assert_eq!(windows.x11(), [11]);
let surface = std::ptr::NonNull::<std::ffi::c_void>::dangling();
let wayland = winit::raw_window_handle::WaylandWindowHandle::new(surface);
windows.created(viewport("Layers"), Some(RawWindowHandle::Wayland(wayland)));
assert!(windows.x11().is_empty());
windows.created(viewport("Layers"), xlib(11));
windows.created(viewport("Layers"), None);
assert!(windows.x11().is_empty());
}
}
-18
View File
@@ -515,21 +515,3 @@ fn the_linux_desktop_entry_opens_every_readable_format() {
}
}
}
/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose
/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go.
#[cfg(not(any(target_os = "macos", windows)))]
#[test]
fn quitting_hides_the_window_before_the_clipboards_let_go() {
struct Window(std::cell::Cell<u32>);
impl QuittingWindow for Window {
fn hide(&self) {
self.0.set(self.0.get() + 1);
}
}
let window = Window(std::cell::Cell::new(0));
hide_before_teardown(Some(&window));
assert_eq!(window.0.get(), 1, "the window was not hidden");
// Without a window (none was made), there is nothing to hide.
hide_before_teardown::<Window>(None);
}
@@ -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);
}
}
+37 -1
View File
@@ -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]
+1 -1
View File
@@ -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 }
+2 -2
View File
@@ -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]));
}
+37 -2
View File
@@ -13,6 +13,7 @@
mod calli;
mod colorize;
mod defaults;
pub mod stored_art;
pub mod track;
mod warp;
@@ -351,7 +352,8 @@ pub enum Direction {
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "mode")]
pub enum ArtScale {
/// Keep the art's proportions (length follows the path; width scales with it).
/// Keep the art's proportions (length follows the path; width scales with it, times the
/// stroke weight and the brush width).
Proportional,
/// Stretch the art to the path length.
#[default]
@@ -798,9 +800,15 @@ fn number_repeated_names(lib: &mut [Brush]) {
}
}
/// Store `lib` as the document's brush library.
/// 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.
@@ -1000,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> {
+183
View File
@@ -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;
}
}
}
}
+197
View File
@@ -141,6 +141,50 @@ fn art_brush_proportional_keeps_aspect() {
assert!(near(bounds(&out).height(), 8.0, 1e-6));
}
/// Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch art
/// is, on top of the scale the path length gives it.
#[test]
fn art_brush_proportional_grows_with_weight() {
let brush = |width: f64, overlap: bool| {
let mut b = art_brush(rect_art(100.0, 4.0), ArtScale::Proportional);
if let BrushKind::Art(a) = &mut b.kind {
(a.width, a.overlap) = (width, overlap);
}
b
};
let draw = |b: &Brush, bp: &BezPath, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, bp, st);
// 3 pt stroke → 3× wider than at 1 pt (8 pt); the length still follows the path.
let b = bounds(&draw(&brush(100.0, false), &line(0.0, 0.0, 200.0, 0.0), &stroke(3.0)));
assert!(near(b.height(), 24.0, 1e-6) && near(b.x0, 0.0, 1e-6) && near(b.x1, 200.0, 1e-6), "{b:?}");
// The Width (50 %) applies on top of the stroke weight.
let b = bounds(&draw(&brush(50.0, false), &line(0.0, 0.0, 200.0, 0.0), &stroke(3.0)));
assert!(near(b.height(), 12.0, 1e-6), "{b:?}");
// A path twice as long at twice the weight (as Scale Strokes & Effects at 200 % leaves it):
// 2× from the length and 2× from the weight.
let b = bounds(&draw(&brush(100.0, false), &line(0.0, 0.0, 400.0, 0.0), &stroke(2.0)));
assert!(near(b.height(), 32.0, 1e-6), "{b:?}");
// With Overlap, each run between corners is scaled by its own length and by the weight: the
// 100 pt run 4 pt × 3 across, the 50 pt run 2 pt × 3.
let mut bent = BezPath::new();
bent.move_to((0.0, 0.0));
bent.line_to((100.0, 0.0));
bent.line_to((100.0, 50.0));
let out = draw(&brush(100.0, true), &bent, &stroke(3.0));
assert_eq!(out.len(), 2);
let (r0, r1) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
assert!(near(r0.height(), 12.0, 1e-6) && near(r1.width(), 6.0, 1e-6), "{r0:?} {r1:?}");
// A width that follows the pen: 50 % at the lightest pressure, 300 % at the heaviest, times
// the 2 pt weight (4 pt art on a 100 pt path: 4 pt across at 100 %, 1 pt either side).
let mut pen = brush(50.0, false);
if let BrushKind::Art(a) = &mut pen.kind {
(a.width_mode, a.width_max) = (Some(Variation::Pressure), Some(300.0));
}
let ramp = StrokeLayer { width: 2.0, ..pressed(vec![(0.0, 0.0), (1.0, 1.0)]) };
let out = draw(&pen, &line(0.0, 0.0, 100.0, 0.0), &ramp);
assert!(near(half_width(&out, 0.0, 1.0), 2.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
assert!(near(half_width(&out, 99.0, 100.0), 12.0, 0.2), "{}", half_width(&out, 99.0, 100.0));
}
#[test]
fn art_brush_between_guides_keeps_ends() {
// Head (last 20 % of a 100 pt art) keeps its 20 pt length on a 300 pt path.
@@ -973,6 +1017,159 @@ fn repeated_brush_names_are_numbered_when_read() {
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();
+5 -16
View File
@@ -465,17 +465,8 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
bounds.windows(2).map(|w| (w[0], w[1])).collect()
}
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1, and
/// `width` the width (%) there.
fn art_on_run(
t: &Track,
(s0, s1): (f64, f64),
a: &ArtBrush,
(art, b): (&Node, Rect),
cross: f64,
width: f64,
widen: &dyn Fn(f64) -> f64,
) -> Option<Node> {
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
let l = s1 - s0;
if l <= 1e-9 {
return None;
@@ -483,10 +474,8 @@ fn art_on_run(
let w = b.width();
let (along, cross) = match a.scale {
ArtScale::Stretch => (AlongMap::linear(w, s0, s1), cross),
ArtScale::Proportional => {
let k = l / w;
(AlongMap::linear(w, s0, s1), k * width / 100.0)
}
// Scaled across as much as along, times the stroke weight and the width, as the other modes are.
ArtScale::Proportional => (AlongMap::linear(w, s0, s1), l / w * cross),
ArtScale::BetweenGuides { start, end } => {
let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w);
let (g0, g1) = (g0.min(g1), g0.max(g1));
@@ -528,7 +517,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
};
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
for run in runs {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, width, &widen) {
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
out.push(n);
}
}
+3 -1
View File
@@ -3,13 +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 }
@@ -19,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 }
+2 -428
View File
@@ -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};
+52 -6
View File
@@ -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 {
+164
View File
@@ -177,6 +177,90 @@ fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() {
assert_eq!(t.matches("PD").count(), 3, "{t}");
}
/// `plots_nothing` picks the objects and layers that a plot draws nothing of: a path that paints
/// nothing, objects at 0% opacity, placed images, meshes with every point at 0% opacity and
/// non-printing layers, and not a painted path or a mesh.
#[test]
fn plots_nothing_picks_what_a_plot_draws_nothing_of() {
type Make = fn(&mut Document) -> Node;
let cases: [(&str, Make, bool); 7] = [
("stroked", |d| stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK), false),
("unpainted", |d| Node::path(d.alloc_id(), rect(10.0, 10.0, 40.0, 40.0), Appearance::basic(Paint::None, Paint::None, 1.0)), true),
(
"clear",
|d| {
let mut n = filled(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK);
n.opacity = 0.0;
n
},
true,
),
(
"image",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))
},
true,
),
(
"image with Crop Marks",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true });
n
},
false,
),
("mesh", |d| Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), false),
(
"clear mesh",
|d| {
let mut clear = mesh_at(10.0);
clear.points.iter_mut().for_each(|p| p.opacity = 0.0);
Node::new(d.alloc_id(), NodeKind::Mesh(clear))
},
true,
),
];
for (name, make, nothing) in cases {
let mut held = None;
let d = doc_with(|d| {
let n = make(d);
held = Some(n.clone());
vec![n]
});
let Some(n) = held else { panic!("{name}") };
assert_eq!(plots_nothing(&d, &n), nothing, "{name}");
assert_eq!(text(&plot(&d, &opts(&d))) == "IN;PU;SP0;", nothing, "{name}");
}
let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK)]);
let layer = d.layers[0].id;
assert!(!plots_nothing(&d, &d.layers[0]));
if let Some(NodeKind::Layer { printable, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
*printable = false;
}
assert!(plots_nothing(&d, &d.layers[0]));
assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;");
}
/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a
/// warning.
#[test]
@@ -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.
+22 -5
View File
@@ -1,4 +1,4 @@
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
//! 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
@@ -15,7 +15,7 @@
//! [`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())
}
+24 -23
View File
@@ -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,
@@ -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))
}
}
+69 -4
View File
@@ -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(),
@@ -1410,6 +1432,29 @@ fn a_stained_instance_is_written_in_its_stained_color() {
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
@@ -1428,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());
}
}
-674
View File
@@ -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");
}
}
+448
View File
@@ -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
+202 -14
View File
@@ -9,13 +9,16 @@
//! 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};
@@ -91,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 {
@@ -131,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(),
}
}
}
@@ -515,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 {
@@ -910,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();
}
@@ -940,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);
@@ -954,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 {
@@ -976,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);
@@ -984,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)]
+93
View File
@@ -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()
+75
View File
@@ -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);
}
}
+74
View File
@@ -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:?}");
}
+43
View File
@@ -547,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)> {
+63
View File
@@ -66,6 +66,69 @@ fn stop_reach_matches_scanning_the_stops() {
}
}
/// A gradient's stops color what draws where they color a stretch that draws, for stops in any
/// order: the sampler mixes stop `k` with stop `k + 1` above every offset of the stops before it,
/// so an out-of-order stop's pair can have no width.
#[test]
fn drawn_stops_follow_the_sampled_stretches() {
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
// In order: the clear stop next to the opaque one, not the one after it.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![true, true, false]);
// Out of order: the pair (0.8, 0.3) has no width, so the clear stop at 0.3 mixes only with
// the clear stop at 0.8 before it, and the pair (0.3, 1.0) is sampled above 0.8.
assert_eq!(g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 0.0), stop(1.0, 1.0)]).drawn_stops(), vec![false, false, true, true]);
// An opaque stop out of order: the pairs (0, 0.8) and (0.7, 1) cover every offset, so the
// pairs next to the stop at 0.3 have no width and it colors nothing.
let out_of_order = |o: f32| g(vec![stop(0.0, 0.0), stop(0.8, o), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
assert_eq!(out_of_order(0.0).drawn_stops(), vec![false; 5]);
// With the stop at 0.8 opaque, the pairs next to it with width are drawn.
assert_eq!(out_of_order(1.0).drawn_stops(), vec![true, true, false, false, false]);
// The last stop colors the offsets above every stop's, even when it is out of order.
assert_eq!(g(vec![stop(0.0, 0.0), stop(0.6, 0.0), stop(0.5, 1.0)]).drawn_stops(), vec![false, false, true]);
// The first stop colors the offsets up to its own.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.0, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![true, false, false]);
// One stop, every stop clear, and no stops at all.
assert_eq!(g(vec![stop(0.5, 1.0)]).drawn_stops(), vec![true]);
assert_eq!(g(vec![stop(0.0, 0.0), stop(1.0, 0.0)]).drawn_stops(), vec![false, false]);
assert!(g(vec![]).drawn_stops().is_empty());
// A freeform gradient draws from its points: its stops count while any is above opacity 0.
let mut free = g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]);
free.kind = GradientKind::Freeform;
assert_eq!(free.drawn_stops(), vec![true, true, true]);
free.stops.iter_mut().for_each(|s| s.opacity = 0.0);
assert_eq!(free.drawn_stops(), vec![false; 3]);
}
/// Taken as opaque, every stop that colors a stretch of positive width counts, and the first and
/// last stops, whatever their opacity; an out-of-order stop whose pairs have no width does not.
#[test]
fn reached_stops_leave_out_only_stops_without_width() {
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::BLACK) };
let g = |stops: Vec<GradientStop>| Gradient::new(GradientKind::Linear, stops);
// Clear stops in order color their stretches once opaque.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.5, 0.0), stop(1.0, 0.0)]).reached_stops(), vec![true; 3]);
assert_eq!(g(vec![stop(0.0, 0.0), stop(1.0, 0.0)]).reached_stops(), vec![true, true]);
// The stop at 0.3 sits inside the stretch the stops at 0 and 0.8 cover.
let out_of_order = g(vec![stop(0.0, 0.0), stop(0.8, 0.0), stop(0.3, 1.0), stop(0.7, 0.0), stop(1.0, 0.0)]);
assert_eq!(out_of_order.reached_stops(), vec![true, true, false, true, true]);
// A stop at the offset of the stop before it: its pair has no width, the next one does.
assert_eq!(g(vec![stop(0.0, 1.0), stop(0.0, 1.0), stop(1.0, 1.0)]).reached_stops(), vec![true, true, true]);
assert_eq!(
g(vec![stop(0.0, 1.0), stop(0.6, 1.0), stop(0.6, 1.0), stop(0.2, 1.0), stop(1.0, 1.0)]).reached_stops(),
vec![true, true, false, true, true]
);
assert!(g(vec![]).reached_stops().is_empty());
// Every pair the sampler picks between the ends has both its stops counted.
let stops: Vec<GradientStop> = [0.1, 0.4, 0.4, 0.2, 0.9, 0.5].iter().map(|&o| stop(o, 1.0)).collect();
let g = g(stops);
let (reached, reach) = (g.reached_stops(), StopReach::new(&g.stops));
for t in (5..=95).map(|k| k as f32 / 100.0).filter(|&t| t > 0.1 && t <= 0.9) {
let k = reach.0.partition_point(|r| *r < t);
assert!(reached[k] && reached[k + 1], "pair {k} at {t}: {reached:?}");
}
}
/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as
/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one
/// offset used to scan them all for each midpoint).
+7 -1
View File
@@ -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 => {
+37 -4
View File
@@ -435,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);
@@ -449,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
@@ -593,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);
+15 -6
View File
@@ -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
+93
View File
@@ -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.
+10 -2
View File
@@ -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 }
+10
View File
@@ -271,6 +271,16 @@ impl Appearance {
_ => None,
})
}
/// Does any fill draw: one that is shown, has paint and has an opacity above 0, wherever it
/// sits in the stack?
pub fn has_drawn_fill(&self) -> bool {
self.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0))
}
/// Does any stroke draw: one that is shown, has paint, a weight above 0 and an opacity above
/// 0, wherever it sits in the stack?
pub fn has_drawn_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.width > 0.0 && s.opacity > 0.0)
}
/// Largest distance the painted area can extend beyond any geometry (see
/// [`StrokeLayer::reach`]); paths measure their own with [`Self::stroked_bounds`].
pub fn outset(&self) -> f64 {
+22
View File
@@ -79,6 +79,28 @@ fn basic_means_one_plain_fill_and_stroke() {
assert!(!e.is_basic(), "an effect");
}
#[test]
fn drawn_fills_and_strokes_count_every_row() {
let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p));
let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w));
let black = || Paint::solid(Color::BLACK);
assert!(!Appearance::default().has_drawn_fill() && !Appearance::default().has_drawn_stroke());
// A painted lower row draws under an unpainted top row.
let a = Appearance { items: vec![fill(black()), stroke(black(), 2.0), fill(Paint::None), stroke(Paint::None, 1.0)], ..Appearance::default() };
assert!(a.has_drawn_fill() && a.has_drawn_stroke());
// A hidden painted row, a zero opacity or a zero weight draws nothing.
let mut b = Appearance { items: vec![fill(black()), stroke(black(), 2.0)], ..Appearance::default() };
b.fill_mut().unwrap().visible = false;
b.stroke_mut().unwrap().visible = false;
assert!(!b.has_drawn_fill() && !b.has_drawn_stroke());
let mut c = Appearance::default_art();
c.fill_mut().unwrap().opacity = 0.0;
c.stroke_mut().unwrap().opacity = 0.0;
assert!(!c.has_drawn_fill() && !c.has_drawn_stroke());
let d = Appearance::basic(Paint::None, black(), 0.0);
assert!(!d.has_drawn_fill() && !d.has_drawn_stroke());
}
#[test]
fn set_creates_missing() {
let mut a = Appearance::default();
+734 -36
View File
@@ -19,11 +19,11 @@
use std::f64::consts::PI;
use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::text::TextObject;
@@ -45,7 +45,24 @@ fn lerp_f64(x: f64, y: f64, t: f64) -> f64 {
x + (y - x) * t
}
/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`).
/// The process plates between two stops linked to one spot swatch: each of C, M, Y and K in turn,
/// a stop without plates counting as none of each. The ends keep their own plates.
fn lerp_plates(a: Option<[f32; 4]>, b: Option<[f32; 4]>, t: f32) -> Option<[f32; 4]> {
if t <= 0.0 {
return a;
}
if t >= 1.0 {
return b;
}
if a.is_none() && b.is_none() {
return None;
}
let (a, b) = (a.unwrap_or_default(), b.unwrap_or_default());
Some(std::array::from_fn(|i| lerp_f32(a[i], b[i], t)))
}
/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`), with no
/// process plates (a solid has none).
fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> Gradient {
let mut g = like.clone();
for s in &mut g.stops {
@@ -53,16 +70,22 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) ->
s.opacity = 1.0;
s.swatch = swatch.map(str::to_string);
s.tint = tint;
s.plates = None;
}
g
}
/// The swatch and tint `g` paints at `t`: a stop's own link, or the shared swatch of the two stops
/// around `t` at the tint between theirs (unlinked when they differ), as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32) {
let stops = &g.stops;
let link = |s: &GradientStop| (s.swatch.clone(), s.tint);
let Some(first) = stops.first() else { return (None, 1.0) };
/// The swatch, tint and process plates `g` paints at `t`: a stop's own link, or the shared swatch
/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ),
/// as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
link_in(&g.stops, t)
}
/// [`link_at`] of a gradient's `stops`.
fn link_in(stops: &[GradientStop], t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates);
let Some(first) = stops.first() else { return (None, 1.0, None) };
if t <= first.offset {
return link(first);
}
@@ -74,25 +97,42 @@ fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32) {
let m = a.midpoint.clamp(0.01, 0.99);
let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) };
return match (&a.swatch, &b.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v)),
_ if v <= 0.0 => link(a),
_ if v >= 1.0 => link(b),
_ => (None, 1.0),
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v), lerp_plates(a.plates, b.plates, v)),
_ => (None, 1.0, None),
};
}
}
stops.last().map_or((None, 1.0), link)
stops.last().map_or((None, 1.0, None), link)
}
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred).
/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two
/// where either gradient steps there: two of its stops at the same offset).
const STEP: f32 = 1e-4;
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An
/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its
/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step.
fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
let mut out = g.clone();
out.stops = offsets
.iter()
.map(|&o| {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint) = link_at(g, o);
GradientStop { opacity, swatch, tint, ..GradientStop::new(o, color) }
.enumerate()
.map(|(i, &o)| {
let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o);
let stepped =
if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None };
match stepped {
Some(s) => {
GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) }
}
None => {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
}
}
})
.collect();
out
@@ -111,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec<f32>) {
}
/// Two gradients of one kind with the same number of stops: as they are when the counts match,
/// else both resampled at every place either changes.
/// else both resampled at every place either changes, with two stops where either steps.
fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
if a.kind != b.kind {
return None;
@@ -127,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
gradient_breaks(b, &mut offs);
offs.retain(|o| o.is_finite());
offs.sort_by(f32::total_cmp);
offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4);
Some((resample_stops(a, &offs), resample_stops(b, &offs)))
offs.dedup_by(|x, y| (*x - *y).abs() < STEP);
let mut steps: Vec<f32> =
[a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect();
steps.sort_by(f32::total_cmp);
let mut at = Vec::with_capacity(offs.len() + steps.len());
let mut k = 0;
for o in offs {
at.push(o);
while steps.get(k).is_some_and(|&s| s <= o - STEP) {
k += 1;
}
if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) {
at.push(o);
}
}
Some((resample_stops(a, &at), resample_stops(b, &at)))
}
fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<GradientPaint> {
@@ -139,16 +193,18 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
.iter()
.zip(&gb.stops)
.map(|(sa, sb)| {
// Stops on two tints of one swatch stay linked to it, as solids do (#3234).
let (swatch, tint) = match (&sa.swatch, &sb.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t)),
_ => (None, 1.0),
// Stops on two tints of one swatch stay linked to it, as solids do (#3234), and keep
// the process plates printed with it.
let (swatch, tint, plates) = match (&sa.swatch, &sb.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t), lerp_plates(sa.plates, sb.plates, t)),
_ => (None, 1.0, None),
};
GradientStop {
opacity: lerp_f32(sa.opacity, sb.opacity, t),
midpoint: lerp_f32(sa.midpoint, sb.midpoint, t),
swatch,
tint,
plates,
..GradientStop::new(lerp_f32(sa.offset, sb.offset, t), lerp_color(&sa.color, &sb.color, t))
}
})
@@ -606,13 +662,128 @@ fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr
out
}
/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap
/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its
/// arrowheads.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the
/// part from `s` on runs first, then the part before it, stepping where the old start now falls.
/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once.
/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between
/// two of them the link [`link_at`] reads there.
fn gradient_from(g: &Gradient, s: f32) -> Gradient {
// A hue gradient that reflects unrolls through its curve, whose stops have no links: the links
// come from its own stops unrolled as a Classic gradient's, which keep them.
let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue();
let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() });
let g = g.unrolled();
let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone());
own.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let mut stops = Vec::new();
// The part from `s` to the end runs first, then the part up to `s`.
for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] {
// The first of `own` not yet matched: the parts' stops run in order, so the links are
// found in one pass.
let mut j = 0;
for (k, st) in g.span(from, to).stops.into_iter().enumerate() {
let p = from + (to - from) * st.offset;
while own.get(j).is_some_and(|o| o.offset <= p - STEP) {
j += 1;
}
let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity);
let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP));
let mut hit = near.clone().find(|&i| same(i));
// A part starting on a step starts with the color after it, so its first stop takes
// the link of the step's last stop of that color.
if k == 0
&& let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset)
{
hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit);
}
let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) {
Some((i, o)) => {
j = i + 1;
(o.swatch.clone(), o.tint, o.plates)
}
None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p),
};
stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st });
}
}
Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() }
}
/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the
/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries
/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern
/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs
/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners
/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed
/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run
/// on without restarting there.
fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
if !d.is_dashed() || !d.offset.is_finite() {
return;
}
let mut pat = d.pattern.clone();
// An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap).
if pat.len() % 2 == 1 {
pat.extend_from_within(..);
}
let period: f64 = pat.iter().sum();
// Where along the key's own subpath the turned one starts (a closed one wraps round). A
// closed one reversed from its own start runs back from its end.
let at = match (o.closed, o.seam()) {
(true, s) if s == 0.0 && o.reversed => 1.0,
(true, s) => s,
(false, _) => o.start,
};
let first = pat.first().copied().unwrap_or(0.0);
let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len };
let offsets: Vec<f64> = lens.iter().map(|&len| offset(len)).collect();
let agree = offsets.first().is_some_and(|&a| {
offsets.iter().all(|&b| {
let r = (b - a).rem_euclid(period);
r.is_finite() && r.min(period - r) <= 1e-6
})
});
if o.reversed {
if let Some(rest) = pat.get_mut(1..) {
rest.reverse();
}
d.pattern = pat;
}
if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) {
d.offset = off;
}
}
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
/// they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
if o.is_identity() {
return;
}
if let Some(d) = &mut s.dash {
reorient_dash(d, o, lens);
}
let along = s.gradient_mode == StrokeGradientMode::Along;
if s.path_gradient().is_some()
&& let Paint::Gradient(g) = &mut s.paint
{
let start = along && o.seam() > 0.0;
if start {
g.gradient = gradient_from(&g.gradient, o.seam() as f32);
}
// Stops that reflect an even number of times read the same either way.
let (spread, runs) = g.gradient.painted_spread();
let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0);
if reverse {
g.gradient.reverse();
}
if start || reverse {
// The turned gradient is no longer the swatch's.
g.swatch = None;
}
}
let same = |v: f64| v;
if let Some(p) = &mut s.profile {
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
@@ -648,20 +819,58 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same);
p.points = out;
}
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
}
}
/// `n` with every stroke read along its subpaths turned as `o` says.
/// `n` with every stroke read along its subpaths turned as `o` says, and on a reversed open path
/// its arrowheads swapped.
fn reorient_strokes(n: &mut Node, o: Orient) {
if o.is_identity() {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
reorient_stroke(s, o, &lens);
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
}
}
}
}
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
let subpaths: Vec<&SubPath> = match &n.kind {
NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
_ => return,
};
let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
let mut o = Orient::of(sp);
if reversed.get(i).copied().unwrap_or(false) {
if sp.closed {
o.start_at(sp, sp.anchors.len().saturating_sub(1));
}
o.reverse();
}
o
});
let Some(o) = turns.next() else { return };
if o.is_identity() || !turns.all(|t| t.same_turn(&o)) {
return;
}
let lens: Vec<f64> =
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o, &lens);
}
}
}
@@ -1205,13 +1414,21 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
// Spine
// =====================================================================================
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
thread_local! {
/// How many times [`Spine::new`] has run on this thread, for tests that count how often a path
/// is flattened.
pub(crate) static SPINES_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How many times [`Spine::new`] has run on this thread, for other crates' tests that count how
/// often a path is flattened (the `spine-count` feature, dev-dependencies only).
#[cfg(any(test, feature = "spine-count"))]
#[doc(hidden)]
pub fn spines_built() -> usize {
SPINES_BUILT.with(|n| n.get())
}
/// A spine (the first subpath of a path) flattened to a polyline, with cumulative lengths and the
/// arc length at each of its anchors.
pub struct Spine {
@@ -1230,7 +1447,7 @@ impl Spine {
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
/// the first one flattens to fewer than two points (so it has no length to walk).
pub fn new(path: &PathData) -> Option<Self> {
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
SPINES_BUILT.with(|n| n.set(n.get() + 1));
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
@@ -1957,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
}
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
let rail = Rail::new(keys, spec);
keys.windows(2).enumerate().all(|(i, w)| {
let [a, b] = w else { return true };
match spec.spacing {
BlendSpacing::Steps(_) => true,
// The count is `len / d` rounded, which grows with `len`.
BlendSpacing::Distance(d) => {
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
count(len - length) == count(len + length)
}
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
}
})
}
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
/// between their edges in key sizes), so the pair is settled when the least and the most of
/// these ask for the same count.
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
let bounds = a.visual_bounds().zip(b.visual_bounds());
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
match (color_distance(a, b), bounds) {
// Colors that differ, but by too little to count, or by little more: moving them may cross
// where they stop counting as the same. (The same colors stay the same.)
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
let (ca, cb) = (ba.center(), bb.center());
let reach =
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
// The centers and sizes move by up to twice `length`.
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
reach.is_finite() && least == most
}
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
(_, Some((ba, bb))) => {
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
if w <= 4.0 * length || h <= 4.0 * length {
return false;
}
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
// Each edge moves by up to `length`: the distances between them by up to twice that,
// and the mean sizes too.
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
let m = 2.0 * length;
let least = q(dx - m, dy - m, w + m, h + m);
let most = q(dx + m, dy + m, w - m, h - m);
least.is_finite() && most.is_finite() && count(least) == count(most)
}
(_, None) => true,
}
}
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
@@ -2462,6 +2743,112 @@ mod tests {
assert!(m.gradient.stops.iter().any(|s| s.swatch.is_none()), "{:?}", m.gradient.stops);
}
/// A stop linked to the spot swatch "Spot" at `tint`, printed with process `plates`.
fn spot_stop(offset: f32, tint: f32, plates: Option<[f32; 4]>) -> GradientStop {
let mut stop = GradientStop::new(offset, Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint));
stop.swatch = Some("Spot".into());
stop.tint = tint;
stop.plates = plates;
stop
}
fn gradient_paint(stops: Vec<GradientStop>) -> Paint {
Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() })))
}
fn assert_plates(got: Option<[f32; 4]>, want: [f32; 4]) {
let got = got.unwrap_or_else(|| panic!("plates {want:?}, not none"));
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-5), "{got:?} != {want:?}");
}
#[test]
fn blend_gradient_spot_process_plates_interpolate() {
let (p, q) = ([0.2, 0.4, 0.0, 0.0], [0.6, 0.0, 0.8, 1.0]);
let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]);
let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]);
let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() };
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
assert_plates(s.plates, [0.3, 0.3, 0.2, 0.25]);
}
// Without plates on either side the steps print the spot ink alone, as before.
let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]);
let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
}
#[test]
fn resampled_gradient_spot_process_plates_interpolate() {
let (p, q, r) = ([0.0, 0.4, 0.0, 0.0], [0.6, 0.4, 0.3, 0.0], [0.2, 0.2, 0.2, 0.2]);
let mut first = spot_stop(0.0, 0.2, Some(p));
first.midpoint = 0.25;
let two = Gradient { stops: vec![first, spot_stop(1.0, 0.8, Some(q))], ..Gradient::default() };
let three =
Gradient { stops: vec![spot_stop(0.0, 1.0, Some(r)), spot_stop(0.5, 1.0, Some(r)), spot_stop(1.0, 1.0, Some(r))], ..Gradient::default() };
let Some((ra, rb)) = common_stops(&two, &three) else { panic!() };
let offsets: Vec<f32> = ra.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.25, 0.5, 1.0]);
// The original stops keep their plates; between them, the midpoint at 0.25 puts 0.5 two
// thirds of the way along the inks.
assert_eq!((ra.stops[0].plates, ra.stops[3].plates), (Some(p), Some(q)));
assert_plates(ra.stops[1].plates, [0.3, 0.4, 0.15, 0.0]);
assert_plates(ra.stops[2].plates, [0.4, 0.4, 0.2, 0.0]);
assert!((ra.stops[2].tint - 0.6).abs() < 1e-5, "{}", ra.stops[2].tint);
assert!(rb.stops.iter().all(|s| s.plates == Some(r)), "{:?}", rb.stops);
let Paint::Gradient(m) = lerp_paint(&gradient_paint(two.stops), &gradient_paint(three.stops), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 4);
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
assert_plates(m.gradient.stops[2].plates, [0.3, 0.3, 0.2, 0.1]);
}
#[test]
fn blend_gradient_missing_plates_mean_zero() {
let p = [0.4, 0.8, 0.0, 0.2];
let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]);
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]));
// The ends keep their own plates.
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
// Another swatch, or an unlinked stop: process steps with no plates, as before.
let mut other = spot_stop(0.0, 1.0, Some(p));
other.swatch = Some("Other".into());
let other = gradient_paint(vec![other.clone(), GradientStop { offset: 1.0, ..other }]);
let mut plain = spot_stop(0.0, 1.0, None);
plain.swatch = None;
let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]);
for b in [&other, &plain] {
let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
}
#[test]
fn blend_solid_to_spot_gradient_does_not_copy_plates() {
let p = [0.4, 0.8, 0.0, 0.2];
let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let Paint::Gradient(g) = &gradient else { panic!() };
assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none()));
let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 };
// The solid's end has no plates: they grow from none toward the gradient's, both ways round.
for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] {
let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() };
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]);
}
}
// A process solid unlinks the steps, and they take no plates.
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
#[test]
fn gradients_with_different_stop_counts_interpolate() {
let g = |stops: &[(f32, Color)]| {
@@ -2627,6 +3014,275 @@ mod tests {
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
}
#[test]
fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() {
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
let mut ap = Appearance::default();
ap.set_stroke(Paint::solid(Color::BLACK));
if let Some(s) = ap.stroke_mut() {
edit(s);
}
Node::path(NodeId(1), path, ap)
};
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
// How light the stroke's gradient is at `u` (0 black, 3 white).
let light = |s: &StrokeLayer, u: f32| match &s.paint {
Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::<f32>(),
p => panic!("a gradient: {p:?}"),
};
// Whether dash pattern `d` draws a dash `at` this far along its subpath.
let dash_at = |d: &Dash, at: f64| {
let p = if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() };
let mut x = (at + d.offset).rem_euclid(p.iter().sum());
for (i, v) in p.iter().enumerate() {
if x < *v {
return i % 2 == 0;
}
x -= v;
}
false
};
let graded = |mode: StrokeGradientMode| {
move |s: &mut StrokeLayer| {
s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
s.gradient_mode = mode;
s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false });
}
};
// An open key clicked at its last anchor runs the other way: a gradient along it or across
// it (whose sides swap) runs the other way too, and its dashes are read from its end.
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false));
let plain = keyed(line(0.0), &|_| {});
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
let key = keyed(line(100.0), &graded(mode));
let s = stroke(&Lerp::new(&plain, &key, (None, Some(1))).at(1.0));
assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{mode:?}: {:?}", s.paint);
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..130 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, 13.0 - u), "at {u}: {d:?}");
}
}
// A closed key started half way round starts its gradient along it there too, stepping
// where its own start was, and its dashes start there.
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
let key = keyed(square(100.0), &graded(StrokeGradientMode::Along));
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0));
for (u, want) in [(0.0, 1.5), (0.25, 0.75), (0.499, 0.0), (0.501, 3.0), (0.75, 2.25), (1.0, 1.5)] {
assert!((light(&s, u) - want).abs() < 0.02, "at {u}: {} for {want}: {:?}", light(&s, u), s.paint);
}
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..200 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, u + 20.0), "at {u}: {d:?}");
}
// A closed key that winds the other way runs the other way from the same anchor: its
// dashes are read back from the end of its own subpath, which is 40 long and not a whole
// number of periods.
let wound = |x: f64| {
let mut p = square(x);
for sp in &mut p.subpaths {
sp.reverse();
}
p
};
let back = keyed(wound(100.0), &graded(StrokeGradientMode::Along));
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &back, (Some(0), Some(0))).at(1.0));
let (own, d) = (stroke(&back).dash.unwrap_or_default(), s.dash.unwrap_or_default());
for k in 1..400 {
let u = k as f64 / 10.0 + 0.03;
assert_eq!(dash_at(&d, u), dash_at(&own, 40.0 - u), "at {u}: {d:?}");
}
// Stops that reflect twice read the same either way; a link to a swatch stays.
let reflected = keyed(line(100.0), &|s| {
let mut g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::default() };
g.stops[1].swatch = Some("Ink".into());
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
assert_eq!(stroke(&Lerp::new(&plain, &reflected, (None, Some(1))).b).paint, stroke(&reflected).paint);
let linked = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
g.stops[1].swatch = Some("Ink".into());
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &linked, (Some(0), Some(2))).b);
let links = match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some("Ink")).map(|st| st.offset).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert!(links.contains(&0.5), "the stop the old start ended on keeps its link: {:?}", s.paint);
// Each stop of a step keeps its own link.
let step = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
let (mut before, mut after) = (GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.25, Color::WHITE));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
g.stops.splice(1..1, [before, after]);
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &step, (Some(0), Some(2))).b);
let links = match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.offset == 0.75).map(|st| st.swatch.clone()).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links, vec![Some("Ink".into()), Some("Paper".into())], "{:?}", s.paint);
// A step of one color between two swatches, where the turned subpath now starts: the
// start takes the link after the step and the end the link before it.
let seam_step = keyed(square(100.0), &|s| {
let mut g = Gradient::default();
let gray = Color::rgb8(128, 128, 128);
let (mut before, mut after) = (GradientStop::new(0.5, gray), GradientStop::new(0.5, gray));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
g.stops.splice(1..1, [before, after]);
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &seam_step, (Some(0), Some(2))).b);
let ends = match &s.paint {
Paint::Gradient(g) => (g.gradient.stops.first().map(|st| st.swatch.clone()), g.gradient.stops.last().map(|st| st.swatch.clone())),
p => panic!("a gradient: {p:?}"),
};
assert_eq!(ends, (Some(Some("Paper".into())), Some(Some("Ink".into()))), "{:?}", s.paint);
// A hue gradient that reflects keeps its links on the repeated stops.
let hue = keyed(square(100.0), &|s| {
let (mut red, mut blue) =
(GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }));
(red.swatch, blue.swatch) = (Some("Ink".into()), Some("Paper".into()));
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![red, blue])
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue, (Some(0), Some(2))).b);
let linked = |name: &str| match &s.paint {
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some(name)).map(|st| st.offset).collect::<Vec<_>>(),
p => panic!("a gradient: {p:?}"),
};
assert!(linked("Paper").contains(&0.0) && linked("Paper").contains(&1.0), "{:?}", s.paint);
assert!(linked("Ink").contains(&0.5), "{:?}", s.paint);
// Two stops of one color at one place keep their own links, in reverse in a mirrored run.
let hue_step = keyed(square(100.0), &|s| {
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
let (mut before, mut after) = (GradientStop::new(0.5, green), GradientStop::new(0.5, green));
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
let stops = vec![
GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }),
before,
after,
GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }),
];
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, stops)
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_step, (Some(0), Some(2))).b);
// The links at `u` in order, a link repeated by the next stop listed once.
let links_at = |u: f32| match &s.paint {
Paint::Gradient(g) => {
let mut links =
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
links.dedup();
links
}
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links_at(0.25), vec!["Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
assert_eq!(links_at(0.75), vec!["Ink".to_string(), "Paper".to_string()], "{:?}", s.paint);
// Where two runs meet, each run's stops keep their own links.
let hue_end = keyed(square(100.0), &|s| {
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
let (mut a, mut b) = (GradientStop::new(1.0, green), GradientStop::new(1.0, green));
(a.swatch, b.swatch) = (Some("Ink".into()), Some("Paper".into()));
let g = Gradient {
method: GradientMethod::HueClockwise,
spread: GradientSpread::Reflect,
repeats: 2,
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), a, b])
};
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_end, (Some(0), Some(1))).b);
let links_at = |u: f32| match &s.paint {
Paint::Gradient(g) => {
let mut links =
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
links.dedup();
links
}
p => panic!("a gradient: {p:?}"),
};
assert_eq!(links_at(0.25), vec!["Ink".to_string(), "Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
// Blended with a gradient of other stops, the steps keep that step.
let three = keyed(square(0.0), &|s| {
let mut g = Gradient::default();
g.stops.insert(1, GradientStop::new(0.5, Color::BLACK));
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
s.gradient_mode = StrokeGradientMode::Along;
});
let s = stroke(&Lerp::new(&three, &key, (Some(0), Some(2))).at(0.75));
assert!(light(&s, 0.501) - light(&s, 0.499) > 1.5, "{:?}", s.paint);
// Subpaths whose lengths call for different dash offsets keep the offset.
let rings = |x: f64, turn: usize| {
let mut inner = shapes::rectangle(Rect::new(x, 20.0, x + 7.0, 27.0)).subpaths.remove(0);
inner.anchors.rotate_left(turn);
PathData::new(vec![square(x).subpaths.remove(0), inner])
};
let key = keyed(rings(100.0, 2), &graded(StrokeGradientMode::Along));
let blend = Lerp::new(&keyed(rings(0.0, 0), &|_| {}), &key, (Some(0), Some(2)));
let turned = match &blend.shape {
Shape::Path { pair, .. } => pair.orient.1,
_ => panic!("a path blend"),
};
assert!((turned.seam() - 0.5).abs() < 1e-9, "both rings turn half way round: {turned:?}");
let s = stroke(&blend.at(1.0));
assert_eq!(s.dash.map(|d| d.offset), Some(0.75));
}
#[test]
fn gradients_of_other_stop_counts_keep_their_steps() {
let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
let stepped = Gradient::new(
vectorcraft_color::GradientKind::Linear,
vec![
GradientStop::new(0.0, Color::WHITE),
GradientStop::new(0.5, Color::BLACK),
GradientStop::new(0.5, Color::WHITE),
GradientStop::new(0.50015, red),
GradientStop::new(1.0, Color::BLACK),
],
);
let (a, b) = common_stops(&stepped, &Gradient::default()).unwrap_or_else(|| panic!("one kind"));
let at = |g: &Gradient| g.stops.iter().map(|s| (s.offset, s.color)).collect::<Vec<_>>();
assert_eq!(at(&a), vec![(0.0, Color::WHITE), (0.5, Color::BLACK), (0.5, Color::WHITE), (0.50015, red), (1.0, Color::BLACK)]);
assert_eq!(b.stops.len(), 5);
assert_eq!(b.stops.get(1).map(|s| s.color), b.stops.get(2).map(|s| s.color), "a gradient without the step paints one color there");
// A gradient with two stops close to the other's step, but no step of its own, does not step there.
let close = Gradient::new(
vectorcraft_color::GradientKind::Linear,
vec![
GradientStop::new(0.0, Color::WHITE),
GradientStop::new(0.5, Color::BLACK),
GradientStop::new(0.50005, red),
GradientStop::new(1.0, Color::BLACK),
],
);
let (_, b) = common_stops(&stepped, &close).unwrap_or_else(|| panic!("one kind"));
assert_eq!(b.stops.get(1).map(|s| s.color), Some(Color::BLACK));
assert_eq!(b.stops.get(2).map(|s| s.color), Some(Color::BLACK), "{:?}", b.stops);
}
#[test]
fn odd_dash_blends_to_solid_with_closed_gaps() {
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
@@ -2943,4 +3599,46 @@ mod tests {
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![99]);
}
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
/// color difference or the keys' reach sits where its count changes, or keys of the same color
/// are at most four times 0.01 pt wide.
#[test]
fn steps_settle_unless_rounding_can_change_their_count() {
let (length, color) = (0.01, 0.001);
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
let spec = BlendSpec { spacing, ..Default::default() };
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
};
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
// (settled) and by 51.5 (where the count changes).
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
// 10.0625 pt (80.5 steps) is not.
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
assert!(near(10.0));
assert!(!near(10.0625));
// Keys without bounds are counted by their colors alone.
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
// are never settled.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
}
}
+1532 -199
View File
File diff suppressed because it is too large. Load diff
+96
View File
@@ -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 }))
}
+58
View File
@@ -251,6 +251,45 @@ fn undrawable(heights: &Heights, used: Def, depth: usize) -> bool {
heights.get(&used).is_some_and(|h| h.is_none_or(|h| depth + h > MAX_DRAWN_DEPTH))
}
/// How deep the art of a document's symbols and patterns draws, to measure objects that use them
/// outside the document's layers ([`Self::deepest`]).
#[derive(Clone, Debug, Default)]
pub struct DrawnHeights {
symbols: HashMap<String, usize>,
patterns: HashMap<String, usize>,
}
impl DrawnHeights {
/// The heights of `doc`'s symbols and patterns, as [`Document::too_deep`] counts them: the art
/// is 1 deep, and what it uses is counted under it. A symbol or pattern that uses itself, or
/// draws deeper than [`MAX_DRAWN_DEPTH`], has none.
pub fn of(doc: &Document) -> Self {
let mut out = Self::default();
for ((pattern, name), h) in heights(doc) {
if let Some(h) = h {
let map = if pattern { &mut out.patterns } else { &mut out.symbols };
map.insert(name.to_string(), h);
}
}
out
}
/// The deepest `n`, placed `depth` deep, draws: its own objects and the art of their opacity
/// masks, and under the objects the art of the symbols and patterns they use. A use of a
/// symbol or pattern without a height ([`Self::of`]) counts as the object alone. `n`'s own
/// nesting may pass [`MAX_DEPTH`]. Without recursion.
pub fn deepest(&self, n: &Node, depth: usize) -> usize {
let mut out = depth;
let mut stack = vec![(n, depth)];
while let Some((n, d)) = stack.pop() {
let used = uses(n).filter_map(|(pattern, name)| if pattern { self.patterns.get(name) } else { self.symbols.get(name) }).max();
out = out.max(d + used.copied().unwrap_or(0));
stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| (&**c, d + 1)));
}
out
}
}
/// Take out of `nodes` (each `depth` deep) the uses `bad` picks (given the depth of the object):
/// an instance goes, a pattern paint becomes no paint. Returns whether anything changed. For trees
/// within [`MAX_DEPTH`].
@@ -623,4 +662,23 @@ mod tests {
d.patterns.push(crate::PatternDef::new("q", vec![painted(3, "none")]));
assert!(!d.too_deep(None) && !d.limit_depth());
}
#[test]
fn drawn_heights_measure_objects_outside_the_layers() {
// s0 holds s1 two groups deep, which holds s2, which holds an instance of nothing known:
// s2 draws 3 deep, s1 6 and s0 9.
let d = symbols(3, 2, "none");
let heights = DrawnHeights::of(&d);
let on_layer = instance(1, "s0");
assert_eq!(heights.deepest(&on_layer, 2), 2 + 9);
// An object's own nesting and its mask's art count past MAX_DEPTH.
let mut deep = Node::group(NodeId(5), vec![nested(MAX_DEPTH + 10)]);
deep.extras_mut().mask = Some(Box::new(OpacityMask::new((*instance(6, "s2")).clone(), true)));
assert_eq!(heights.deepest(&deep, 1), 1 + 1 + MAX_DEPTH + 10);
let shallow = Node::group(NodeId(5), vec![instance(7, "s1")]);
assert_eq!(heights.deepest(&shallow, 100), 101 + 6);
// A symbol that holds itself has no height, so its instance counts alone.
let looped = DrawnHeights::of(&symbols(2, 1, "s0"));
assert_eq!(looped.deepest(&instance(1, "s0"), 2), 2);
}
}
+4
View File
@@ -815,6 +815,10 @@ impl Dimension {
if self.line_between_points() && !old.line_between_points() {
self.keep_gap(&old);
}
} else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 {
// A reflection turns the left normal of a → b to the other side, so an aligned
// dimension's line stays on the reflected side of its points.
self.offset = -self.offset;
}
if self.mode == DimensionMode::Linear {
self.length = self.measured();
+17 -1
View File
@@ -79,6 +79,7 @@ impl Document {
index: _,
guide_cache: _,
inline_cycles: _,
mounted_art: _,
} = self;
*version == other.version
&& *title == other.title
@@ -264,6 +265,7 @@ impl Document {
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))));
@@ -750,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> =
@@ -768,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.
+4 -2
View File
@@ -128,8 +128,8 @@ impl Document {
}
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
/// pattern swatches, the original of the pattern being edited and [`Self::mounted_art`].
/// Opacity masks hang off nodes in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
@@ -137,6 +137,7 @@ impl Document {
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
.chain(self.mounted_art.iter().map(|(n, _)| n))
}
/// [`Self::art_roots`], to change.
@@ -147,6 +148,7 @@ impl Document {
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
+13 -63
View File
@@ -1,6 +1,7 @@
use super::document_ext::free_id;
use super::guides::Guide;
use super::limits::MAX_NEXT_ID;
use super::node::{held_guides, map_held, strip_held};
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
use std::collections::{BTreeMap, HashSet};
@@ -272,8 +273,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
drop_picked(l, held);
if let Some(held) = held_guides(l, &Node::is_ruler_guide) {
strip_held(Arc::make_mut(l), held);
}
}
self.saved_guides.extend(guides);
@@ -347,14 +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)?;
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { 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()));
}
});
drop_picked(&mut layer, held);
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,8 +419,8 @@ impl Document {
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &pick) {
drop_picked(l, held);
if let Some(held) = held_guides(l, &pick) {
strip_held(Arc::make_mut(l), held);
}
}
sel.guides.retain(|id| !gone.contains(id));
@@ -434,8 +435,8 @@ impl Document {
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &pick) {
edit_picked(l, held, f);
if let Some(held) = held_guides(l, &pick) {
map_held(Arc::make_mut(l), held, f);
}
}
}
@@ -569,57 +570,6 @@ impl Picked {
}
}
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
/// each child of the layers once.
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let children = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
.collect();
Picked { children, mask: None }.some()
}
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
/// Only the layers holding one are copied, and only those are visited.
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.children.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 child picked itself has nothing inside.
if inner.is_empty() {
return false;
}
drop_picked(c, inner);
true
});
}
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
/// the layers holding one, and the guides, are copied, and only those layers are visited.
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for (i, inner) in held.children {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.is_empty() {
edit_picked(c, inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
/// `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> {
@@ -872,9 +822,9 @@ mod tests {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
let held = held_guides(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
drop_picked(&mut d.layers[0], held);
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");
@@ -932,10 +882,10 @@ mod tests {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
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![];
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
map_held(Arc::make_mut(&mut d.layers[0]), held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
+114 -1
View File
@@ -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")]
@@ -176,12 +180,32 @@ pub struct LabelStyles {
/// 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
@@ -363,6 +387,22 @@ 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")]
@@ -451,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")]
@@ -511,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 {
@@ -521,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>>> {
@@ -615,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,
@@ -635,6 +747,7 @@ impl Default for GraphSpec {
connect_points: true,
edge_to_edge: false,
placed: None,
placed_art: None,
}
}
}
+1204 -205
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+233 -25
View File
@@ -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);
+177 -36
View File
@@ -8,13 +8,20 @@ use std::sync::{Arc, RwLock, Weak};
use vectorcraft_geom::{Affine, Rect};
use crate::{Document, Node, NodeId, NodeKind, Symbol, 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)
@@ -35,27 +42,38 @@ 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 in other symbols' art, so that its size would depend on itself.
/// 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> {
if self.inline_cycles().contains(name) { None } else { self.symbol_art_bounds(name) }
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,
/// found once while the symbols stay as they are.
fn inline_cycles(&self) -> Arc<HashSet<String>> {
/// 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 found = Arc::new(InlineGraph::of(self).cyclic);
let graph = InlineGraph::of(self);
let found = (Arc::new(graph.cyclic), graph.names);
self.inline_cycles.set(&self.symbols, &found);
found
}
@@ -94,7 +112,8 @@ impl Document {
/// 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 show, so a symbol's art is measured with its type already laid out; a
/// 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> {
@@ -241,34 +260,48 @@ fn inline_symbols(n: &Node) -> Vec<String> {
out
}
/// Each symbol name of `d` → the index of the first symbol of that name (the one a name finds).
fn symbol_index(d: &Document) -> HashMap<&str, usize> {
let mut index = HashMap::with_capacity(d.symbols.len());
for (i, s) in d.symbols.iter().enumerate() {
index.entry(s.name.as_str()).or_insert(i);
}
index
}
/// The symbols of a document as their inline graphics depend on each other.
/// 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 shows inline (except along a cycle).
/// 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.
/// 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 the order and cycles are
/// found in time linear in the symbols and their inline references (Tarjan's strongly
/// connected components, without recursion).
/// 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 index = symbol_index(d);
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()
.map(|s| {
let mut e: Vec<usize> = inline_symbols(&s.art).iter().filter_map(|n| index.get(n.as_str()).copied()).collect();
.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
@@ -276,12 +309,13 @@ impl InlineGraph {
.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 }
Self { order, cyclic, names }
}
/// [`Document::inline_art_bounds`] with the cycles found in this graph.
/// [`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(name) }
if self.cyclic.contains(name) { None } else { d.symbol_art_bounds_in(name, &d.symbol_boxes().with_names(&self.names)) }
}
}
@@ -354,12 +388,16 @@ fn components(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<bool>) {
#[derive(Default)]
pub(crate) struct InlineCycles(RwLock<Option<Arc<Found>>>);
/// The name and art of each symbol the cycles were found in, and the names of the symbols on one.
type Found = (Vec<(String, Weak<Node>)>, Arc<HashSet<String>>);
/// 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<Arc<HashSet<String>>> {
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()
@@ -368,7 +406,7 @@ impl InlineCycles {
}
/// Keep `found`, found in `symbols`.
fn set(&self, symbols: &[Symbol], found: &Arc<HashSet<String>>) {
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())));
}
@@ -485,6 +523,109 @@ mod tests {
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;
+18 -4
View File
@@ -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,6 +29,7 @@ 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;
@@ -37,6 +39,7 @@ pub use 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, LabelRows, 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,6 +123,8 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
pub use style_libs::StyleLibrary;
pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::GlyphForm;
pub use text::PATH_LEAD_MAX;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
@@ -124,7 +132,7 @@ pub use text::{
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;
@@ -367,6 +375,12 @@ pub struct Document {
/// 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
View File
@@ -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());
}
}
+55 -1
View File
@@ -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.
+1
View File
@@ -316,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),
+25
View File
@@ -338,6 +338,31 @@ 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
+36 -5
View File
@@ -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
View File
@@ -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>() }
}
+1
View File
@@ -32,6 +32,7 @@ pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_b
pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
pub(crate) use ops::{held_guides, map_held, strip_held};
use wire::NodeWire;
pub(crate) use wire::counted_list;
pub use wire::{MAX_READ_NODES, with_node_budget};
+42 -5
View File
@@ -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 {
+5
View File
@@ -79,6 +79,10 @@ pub struct NodeExtras {
/// 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.
@@ -108,6 +112,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
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
+54 -7
View File
@@ -211,7 +211,9 @@ impl Node {
/// A quick box round everything the object can paint, for culling clicks: paths and compound
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
/// clipping layer's box takes in the region that the live geometry effects of its clipping
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
@@ -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;
@@ -823,11 +870,11 @@ 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(super) struct HeldGuides(Vec<(usize, HeldGuides)>);
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(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
pub(crate) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
@@ -843,7 +890,7 @@ pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option
/// 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(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
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;
@@ -863,7 +910,7 @@ pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
/// 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(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
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 };
+31
View File
@@ -24,6 +24,7 @@ fn extras_are_written_flat_in_order() {
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>);
@@ -71,11 +72,13 @@ fn extras_are_written_flat_in_order() {
"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();
@@ -802,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
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)]);
}
+5
View File
@@ -57,6 +57,7 @@ impl Serialize for Node {
is_default(&e.pixel_aligned),
e.color_mask.is_none(),
is_default(&e.warp_piece),
is_default(&e.clip_pieces),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -102,6 +103,7 @@ impl Serialize for Node {
field!("pixel_aligned", &e.pixel_aligned);
field!("color_mask", &e.color_mask);
field!("warp_piece", &e.warp_piece);
field!("clip_pieces", &e.clip_pieces);
st.end()
}
}
@@ -249,6 +251,8 @@ pub(super) struct NodeWire {
color_mask: Option<Box<crate::color_mask::ColorMask>>,
#[serde(default)]
warp_piece: bool,
#[serde(default)]
clip_pieces: bool,
}
impl From<NodeWire> for Node {
@@ -279,6 +283,7 @@ impl From<NodeWire> for Node {
pixel_aligned: w.pixel_aligned,
color_mask: w.color_mask,
warp_piece: w.warp_piece,
clip_pieces: w.clip_pieces,
};
Node {
id: w.id,
+42 -9
View File
@@ -234,8 +234,14 @@ pub fn is_objects_on_path(n: &Node) -> bool {
/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path
/// (not a guide) whose first subpath has a length ([`path_length`]).
pub fn attachable_path(n: &Node) -> Option<&PathData> {
attachable(n).map(|(path, _)| path)
}
/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks
/// its length.
pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path),
NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)),
_ => None,
}
}
@@ -301,20 +307,51 @@ pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
/// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that
/// one flattening serves both measuring the path and finding points along it.
struct Measured {
pub struct Measured {
spine: Spine,
len: f64,
closed: bool,
}
impl std::fmt::Debug for Measured {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive()
}
}
impl Measured {
/// `None` for a path without length, or with a length too large to be finite.
fn new(path: &PathData) -> Option<Self> {
pub fn new(path: &PathData) -> Option<Self> {
let spine = Spine::new(path)?;
let len = spine.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed })
}
/// The flattened first subpath, to measure along.
pub fn spine(&self) -> &Spine {
&self.spine
}
/// The length of the first subpath (points), as [`path_length`] gives it.
pub fn length(&self) -> f64 {
self.len
}
/// Is the first subpath closed?
pub fn closed(&self) -> bool {
self.closed
}
/// [`stops`] on this path.
pub fn stops(&self, n: usize, spacing: Option<f64>, start: f64) -> Vec<(Point, f64)> {
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
(0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect()
}
/// [`stop`] on this path: `None` for an `i` of `n` or more.
pub fn stop(&self, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
if i >= n {
return None;
}
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i)))
}
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
@@ -359,9 +396,7 @@ fn wrap(s: f64, len: f64) -> f64 {
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
Some(Measured::new(path)?.stops(n, spacing, start))
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
@@ -370,9 +405,7 @@ pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usiz
if i >= n {
return None;
}
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some(spine.at_length(nth_length(len, closed, start, gap, i)))
Measured::new(path)?.stop(n, spacing, start, i)
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
+119 -7
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
use crate::{Document, Node, NodeId, NodeKind};
@@ -46,14 +46,21 @@ impl Default for OverprintBlack {
}
impl OverprintBlack {
/// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with
/// [`Self::spot`]), or a gradient whose every stop is.
/// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with
/// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points
/// whose every point is (it draws from its points, not its stops).
fn black(&self, p: &Paint, spots: &[String]) -> bool {
let ink = |color: &Color, swatch: &Option<String>| {
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
};
match p {
Paint::Solid { color, swatch, .. } => {
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
}
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
Paint::Solid { color, swatch, .. } => ink(color, swatch),
// Only a freeform gradient draws its points; another kind draws its stops whatever it holds.
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)),
// Without points of its own a freeform gradient places them from its stops.
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)),
},
_ => false,
}
}
@@ -85,6 +92,52 @@ impl OverprintBlack {
}
changed
}
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
/// that change. Returns whether anything changed.
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
match self.marked(a, spots) {
Some(n) => {
*a = n;
true
}
None => false,
}
}
/// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None`
/// otherwise). Each node is visited once, and only the nodes on the way to a change are copied.
fn marked(&self, n: &Arc<Node>, spots: &[String]) -> Option<Arc<Node>> {
let members: Vec<(usize, Arc<Node>)> =
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect();
if members.is_empty() && !self.changes(n, spots) {
return None;
}
let mut copy = Arc::clone(n);
let m = Arc::make_mut(&mut copy);
self.apply(m, spots);
if let Some(children) = m.children_mut() {
for (i, c) in members {
if let Some(slot) = children.get_mut(i) {
*slot = c;
}
}
}
Some(copy)
}
/// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself.
fn changes(&self, n: &Node, spots: &[String]) -> bool {
let on = !self.remove;
let item = |it: &crate::AppearanceItem| {
it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots)
};
let run = |r: &crate::TextRun| {
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
};
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
}
}
impl Node {
@@ -236,6 +289,65 @@ mod tests {
assert!(tx.runs[0].style.overprint_fill);
}
#[test]
fn a_freeform_gradient_is_black_when_every_point_is() {
use vectorcraft_color::freeform::{Freeform, FreeformPoint};
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() });
for s in &mut g.gradient.stops {
s.color = k;
}
let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))];
g.freeform = Some(Freeform { points, ..Default::default() });
let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0);
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops");
// Another kind of gradient draws its black stops, not the points it still holds.
let mut linear = g.clone();
linear.gradient.kind = GradientKind::Linear;
let mut n = Node::path(NodeId(1), Default::default(), fill(&linear));
assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops");
if let Some(f) = &mut g.freeform {
f.points[1].color = Color::gray(1.0);
}
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black");
g.freeform = Some(Freeform::default());
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops");
}
#[test]
fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() {
let mut g = vectorcraft_color::GradientPaint::new(Default::default());
for s in &mut g.gradient.stops {
s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0);
}
g.gradient.stops[0].swatch = Some("Ink".into());
let k = Paint::Gradient(Box::new(g));
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0));
let spots = ["Ink".to_string()];
assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black");
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
}
#[test]
fn apply_deep_copies_only_the_nodes_that_change() {
let k = cmyk(0.0, 0.0, 0.0, 1.0);
let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0)));
let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0)));
let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()]));
let before = group.clone();
assert!(OverprintBlack::default().apply_deep(&mut group, &[]));
let members = group.children().unwrap();
assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original");
assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied");
assert!(!before.has_overprint());
let marked = group.clone();
assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change");
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
}
#[test]
fn legacy_overprint_black_list_migrates() {
let mut d = Document::new(100.0, 100.0);
+5
View File
@@ -173,6 +173,10 @@ pub struct PatternDef {
/// Size Tile to Art: the tile is the art bounds grown by the spacing.
#[serde(default)]
pub size_tile_to_art: bool,
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by
/// the same offset.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub move_tile_with_art: bool,
#[serde(default)]
pub h_spacing: f64,
#[serde(default)]
@@ -202,6 +206,7 @@ impl PatternDef {
art,
overlap: Overlap::default(),
size_tile_to_art: false,
move_tile_with_art: false,
h_spacing: 0.0,
v_spacing: 0.0,
copies: 5,
+126 -23
View File
@@ -20,15 +20,41 @@ pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool)
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
/// of what it becomes here (#1717).
fn rgba_within(bytes: &[u8], max: u64) -> Option<image::RgbaImage> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
if u64::from(w) * u64::from(h) > max / 4 {
Some(crate::decode::decode_within(bytes, max).ok()??.0.into_rgba8())
}
/// An image file's stored size in pixels, read from its header by craft-image-codecs without
/// decoding any pixels: PNG's IHDR, a JPEG's frame, a TIFF's first full-resolution page, a
/// still or animated WebP's canvas, BMP's header ([`craft_image_codecs::probe_allocation_size`],
/// with no size limit), and a GIF's logical screen and the other formats' headers
/// ([`craft_image_codecs::probe_size`]). Not turned by an EXIF orientation. `None` when no header
/// gives a size.
pub fn header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::Gif) {
// A GIF frame may be larger than the logical screen the image crate gave as its size.
return craft_image_codecs::probe_size(bytes).ok();
}
craft_image_codecs::probe_allocation_size(bytes)
.ok()
.or_else(|| craft_image_codecs::probe_size(bytes).ok())
// A BMP whose pixel data does not match its header (a truncated file, or a header that
// declares more pixels than the file holds) is refused by the image crate decoder the
// probes use. The BITMAPINFOHEADER still names the size, which Place, Paste and Open
// need so they can say the image is too large to draw instead of that its size can't
// be read.
.or_else(|| bmp_header_size(bytes))
}
/// Width and height from a BMP file's BITMAPINFOHEADER, without opening it as a decoder would.
/// Height may be negative (top-down storage); the stored magnitude is the size.
fn bmp_header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.get(..2) != Some(b"BM") {
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(max);
reader.limits(limits);
Some(reader.decode().ok()?.into_rgba8())
let dim = |at: usize| -> Option<i32> { Some(i32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) };
let width = u32::try_from(dim(18)?).ok().filter(|&n| n > 0)?;
let height = dim(22)?.unsigned_abs();
(height > 0).then_some((width, height))
}
impl ImageBlob {
@@ -385,30 +411,43 @@ mod tests {
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
let mut gif = b"GIF89a".to_vec();
gif.extend_from_slice(&w.to_le_bytes());
gif.extend_from_slice(&h.to_le_bytes());
// Flags for a global color table of two colors, the background and aspect bytes, then the
// table: red and black.
gif.extend_from_slice(&[0x80, 0, 0, 255, 0, 0, 0, 0, 0]);
// A 1 × 1 image at (0, 0), its LZW data (clear, color 0, end), and the end of the file.
gif.extend_from_slice(&[0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 0x01, 0, 0x3B]);
gif
/// An RGBA PNG of `w` × `h` pixels with one opaque red pixel at the top left, the rest
/// transparent. Written row by row so the 11,586² allowance image is not held decoded
/// while it is encoded.
fn png_with_one_red_pixel(w: u32, h: u32) -> Vec<u8> {
use std::io::Write;
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
let mut row = vec![0u8; 1 + w as usize * 4];
row[1..5].copy_from_slice(&[255, 0, 0, 255]);
z.write_all(&row).unwrap();
row[1..5].fill(0);
for _ in 1..h {
z.write_all(&row).unwrap();
}
let idat = [&b"IDAT"[..], &z.finish().unwrap()].concat();
let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[8, 6, 0, 0, 0]].concat();
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
for chunk in [&ihdr[..], &idat[..], b"IEND"] {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
let mut crc = flate2::Crc::new();
crc.update(chunk);
out.extend(crc.sum().to_be_bytes());
}
out
}
/// The pixels are decoded within the allowance, not within the decoder's own 512 MB: an RGBA
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled.
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled. A PNG, not a
/// sparse GIF: craft-image-codecs refuses a GIF whose unbacked logical screen is past 256 MiB.
#[test]
fn pixels_past_the_decoders_own_limit_are_decoded_within_the_allowance() {
let (w, h) = (11_586, 11_586);
let rgba = u64::from(w) * u64::from(h) * 4;
assert!(rgba > 512 << 20);
let gif = gif_with_one_red_pixel(w, h);
assert!(rgba_within(&gif, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::new("image/gif", gif);
let png = png_with_one_red_pixel(w, h);
assert!(rgba_within(&png, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::png(png);
assert!(b.map_rgb(|[r, g, bl]| [bl, g, r]).is_some(), "red becomes blue");
assert_eq!(b.sample(0.5, 0.5, 1), Some([255, 0, 0, 255]));
assert_eq!(b.sample(f64::from(w) - 0.5, f64::from(h) - 0.5, 1), None, "transparent");
@@ -556,4 +595,68 @@ mod tests {
assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128])));
assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None);
}
/// Embedded-image pixels through craft-image-codecs (#778) are those the image crate decoded:
/// the same layout and samples for PNG, GIF, WebP, TIFF and BMP at each depth the image
/// crate writes, and JPEG samples within two steps.
#[test]
fn decoded_pixels_are_those_the_image_crate_read() {
use image::{DynamicImage as D, ImageFormat as F};
let rgba =
image::RgbaImage::from_fn(9, 5, |x, y| image::Rgba([(x * 29) as u8, (y * 47) as u8, ((x + 2 * y) * 9) as u8, 255 - (x * y * 6) as u8]));
let deep = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(9, 5, |x, y| {
image::Rgba([(x * 7_001) as u16, (y * 12_007) as u16, 5, 65_535 - (x * y) as u16])
});
let images = [
D::ImageRgba8(rgba.clone()),
D::ImageRgb8(D::ImageRgba8(rgba.clone()).to_rgb8()),
D::ImageLuma8(D::ImageRgba8(rgba.clone()).to_luma8()),
D::ImageLumaA8(D::ImageRgba8(rgba).to_luma_alpha8()),
D::ImageRgba16(deep.clone()),
D::ImageLuma16(D::ImageRgba16(deep).to_luma16()),
];
let mut checked = 0;
for img in &images {
for f in [F::Png, F::Gif, F::WebP, F::Tiff, F::Bmp, F::Jpeg] {
let mut bytes = Vec::new();
if img.write_to(&mut Cursor::new(&mut bytes), f).is_err() {
continue;
}
let what = format!("{f:?} {:?}", img.color());
let want = image::load_from_memory_with_format(&bytes, f).unwrap();
let (got, _) = crate::decode::decode_within(&bytes, MAX_RASTER_ALLOC)
.unwrap_or_else(|e| panic!("{what}: {e}"))
.unwrap_or_else(|| panic!("{what}: past the allowance"));
let tolerance = if f == F::Jpeg { 2 * 257 } else { 0 };
if f != F::Jpeg {
assert_eq!(got.color(), want.color(), "{what}");
}
let worst = got.to_rgba16().as_raw().iter().zip(want.to_rgba16().as_raw()).map(|(a, b)| a.abs_diff(*b)).max();
assert!(worst.is_some_and(|w| w <= tolerance), "{what}: {worst:?}");
// Link previews and the checked-image path read the same pixels.
let handed = ImageBlob::new(format!("image/{f:?}").to_ascii_lowercase(), bytes.clone())
.checked_with_pixels(false)
.unwrap_or_else(|| panic!("{what}: checked"))
.1
.unwrap_or_else(|| panic!("{what}: checked past the allowance"));
assert_eq!(handed.color(), got.color(), "{what} checked");
assert_eq!(handed.as_bytes(), got.as_bytes(), "{what} checked");
checked += 1;
}
}
assert!(checked >= 20, "{checked}");
}
/// A BMP header that declares 30,000 × 30,000 pixels, with only one pixel of data, still
/// reports that size: Paste and Place can then say the image is too large to draw.
#[test]
fn a_truncated_bmp_header_still_gives_its_declared_size() {
let mut bmp = vec![];
image::RgbImage::from_pixel(1, 1, image::Rgb([200, 40, 40])).write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
bmp[18..22].copy_from_slice(&30_000i32.to_le_bytes());
bmp[22..26].copy_from_slice(&30_000i32.to_le_bytes());
assert_eq!(header_size(&bmp), Some((30_000, 30_000)));
let (w, h, _) = crate::decode::decoded_layout(&bmp, craft_image_codecs::Format::Bmp).expect("layout from the header");
assert_eq!((w, h), (30_000, 30_000));
}
}
+11 -8
View File
@@ -1,5 +1,5 @@
//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked
//! ([`PlacedDocument`]).
//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file,
//! placed linked ([`PlacedDocument`]).
//!
//! The object keeps the link to the file and the file's bytes, stored like image data in
//! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the
@@ -7,9 +7,9 @@
//! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting
//! expand it like a live object ([`crate::live::expanded`]).
//!
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives
//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache
//! by content. Before exporting,
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files),
//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a
//! small cache by content. Before exporting,
//! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses
//! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy
//! of the document, so they never meet the user's or show in panels. Placed documents inside a
@@ -27,8 +27,8 @@ use vectorcraft_color::Paint;
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file,
/// shown as one locked object.
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
/// an EPS file's art, shown as one locked object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlacedDocument {
/// The file (its `page` is the artboard or page shown, 1-based).
@@ -166,13 +166,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
}
}
/// The roots of `d`'s art: layers, symbol definitions and pattern swatches.
/// The roots of `d`'s art: layers, symbol definitions, pattern swatches and
/// [`Document::mounted_art`].
fn roots(d: &Document) -> impl Iterator<Item = &Arc<Node>> {
d.layers
.iter()
.chain(d.symbols.iter().map(|s| &s.art))
.chain(d.graph_designs.iter().map(|g| &g.art))
.chain(d.patterns.iter().flat_map(|p| &p.art))
.chain(d.mounted_art.iter().map(|(n, _)| n))
}
fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
@@ -181,6 +183,7 @@ fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
.chain(d.symbols.iter_mut().map(|s| &mut s.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(d.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(d.mounted_art.iter_mut().map(|(n, _)| n))
}
impl Document {
+287
View File
@@ -0,0 +1,287 @@
//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`,
//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image
//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]).
const INCH_M: f64 = 0.0254;
const INCH_CM: f64 = 2.54;
/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads?
pub fn reads(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(&[0xff, 0xd8])
|| bytes.starts_with(b"II*\0")
|| bytes.starts_with(b"MM\0*")
|| (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP")
|| bytes.starts_with(b"BM")
}
/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each
/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files.
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png(bytes)
} else if bytes.starts_with(&[0xff, 0xd8]) {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
bmp(bytes)
} else {
None
};
r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v)))
}
/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either).
fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> {
b.get(at..at.checked_add(n)?)
}
fn bytes<const N: usize>(b: &[u8], at: usize) -> Option<[u8; N]> {
slice(b, at, N)?.try_into().ok()
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
bytes(b, at).map(u16::from_be_bytes)
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_be_bytes)
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
bytes(b, at).map(u32::from_le_bytes)
}
/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when
/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi).
fn per_metre(ppm: u32) -> f64 {
let v = ppm as f64 * INCH_M;
let whole = v.round();
if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v }
}
/// PNG chunks after the signature: (type, data).
pub fn png_chunks(b: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut at = 8;
std::iter::from_fn(move || {
let len = be32(b, at)? as usize;
let ty = slice(b, at + 4, 4)?;
let data = slice(b, at + 8, len)?;
at = at.checked_add(12 + len)?;
Some((ty, data))
})
}
fn png(b: &[u8]) -> Option<(f64, f64)> {
let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?;
// Unit 1 = metre; 0 only gives the pixel aspect ratio.
(d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0))))
}
fn jpeg(b: &[u8]) -> Option<(f64, f64)> {
let (mut jfif, mut exif) = (None, None);
let mut at = 2;
while at + 4 <= b.len() && b[at] == 0xff {
let marker = b[at + 1];
// 0xff fill bytes pad between segments.
if marker == 0xff {
at += 1;
continue;
}
if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
at += 2;
continue;
}
// Start of scan or end of image: no more metadata.
if marker == 0xda || marker == 0xd9 {
break;
}
let len = be16(b, at + 2)? as usize;
let seg = slice(b, at + 4, len.checked_sub(2)?)?;
match marker {
0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => {
let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64);
jfif = match seg[7] {
1 => Some((x, y)),
2 => Some((x * INCH_CM, y * INCH_CM)),
_ => None,
};
}
0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]),
_ => {}
}
at += 2 + len;
}
jfif.or(exif)
}
/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi
/// in the stored pixels' axes, unchecked; `None` without an absolute unit.
pub fn tiff(b: &[u8]) -> Option<(f64, f64)> {
let le = b.starts_with(b"II");
let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes });
let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes });
let ifd = u32_at(4)? as usize;
let (mut x, mut y, mut unit) = (None, None, 2);
for i in 0..u16_at(ifd)? as usize {
let e = ifd.checked_add(2 + i * 12)?;
let rational = || -> Option<f64> {
let at = u32_at(e + 8)? as usize;
let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?);
(d != 0).then(|| n as f64 / d as f64)
};
match u16_at(e)? {
282 => x = rational(),
283 => y = rational(),
296 => unit = u16_at(e + 8)?,
_ => {}
}
}
let k = match unit {
2 => 1.0,
3 => INCH_CM,
_ => return None,
};
let x = x?;
Some((x * k, y.unwrap_or(x) * k))
}
fn webp(b: &[u8]) -> Option<(f64, f64)> {
let mut at = 12;
while at + 8 <= b.len() {
let len = le32(b, at + 4)? as usize;
let data = slice(b, at + 8, len)?;
if &b[at..at + 4] == b"EXIF" {
return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data));
}
at += 8 + len + (len & 1);
}
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
return None;
}
let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre);
Some((ppm(38)?, ppm(42)?))
}
/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores).
pub fn pixels_per_metre(ppi: f64) -> u32 {
(ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32
}
/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another.
fn crc32(parts: &[&[u8]]) -> u32 {
let mut crc = !0u32;
for &b in parts.iter().flat_map(|p| p.iter()) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
}
}
!crc
}
/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch.
pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> {
let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes());
// x, y, unit 1 = metre.
let data = [x.as_slice(), y.as_slice(), &[1]].concat();
let mut out = Vec::with_capacity(21);
out.extend_from_slice(&9u32.to_be_bytes());
out.extend_from_slice(b"pHYs");
out.extend_from_slice(&data);
out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes());
out
}
/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced).
pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> {
let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() };
let chunk = phys_chunk(x, y);
let mut out = Vec::with_capacity(png.len() + chunk.len());
out.extend_from_slice(head);
out.extend_from_slice(&chunk);
let mut at = head.len();
while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) {
if chunk.get(4..8) != Some(b"pHYs") {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(png.get(at..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn png_of(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
/// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there.
#[test]
fn a_png_takes_its_resolution_and_still_decodes() {
let png = png_of(4, 3);
assert_eq!(resolution(&png), None);
let tagged = with_png_resolution(&png, (300.0, 150.0));
assert_eq!(resolution(&tagged), Some((300.0, 150.0)));
let again = with_png_resolution(&tagged, (72.0, 72.0));
assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated");
assert_eq!(again.len(), tagged.len());
let img = image::load_from_memory(&again).unwrap();
assert_eq!((img.width(), img.height()), (4, 3));
// Every PNG ends with this IEND chunk CRC.
assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082);
}
/// RIFF chunk `ty` holding `data`, padded to an even length.
fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> {
let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat();
if data.len() % 2 == 1 {
out.push(0);
}
out
}
fn webp_of(chunks: &[Vec<u8>]) -> Vec<u8> {
let body = chunks.concat();
let size = u32::try_from(body.len() + 4).unwrap();
[b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat()
}
/// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose
/// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to
/// an offset) gives no resolution.
#[test]
fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() {
// Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch.
let mut tiff = b"II*\0".to_vec();
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&2u16.to_le_bytes());
for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&ty.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
}
tiff.extend_from_slice(&0u32.to_le_bytes());
tiff.extend_from_slice(&300u32.to_le_bytes());
tiff.extend_from_slice(&1u32.to_le_bytes());
let exif = [b"Exif\0\0".as_slice(), &tiff].concat();
let exif_len = u32::try_from(exif.len()).unwrap();
let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]);
assert_eq!(resolution(&ok), Some((300.0, 300.0)));
for len in [u32::MAX, u32::MAX - 7, 1_000] {
let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]);
assert_eq!(resolution(&bad), None, "chunk length {len}");
}
}
}
+8
View File
@@ -16,6 +16,11 @@ pub trait ColorVisitor {
fn color(&mut self, c: Color) -> Color;
/// The key of embedded image `key` recoloured, `None` when it stays as it is.
fn image(&mut self, key: &str) -> Option<String>;
/// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside
/// it as they are.
fn enters(&mut self, _n: &Node) -> bool {
true
}
}
/// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh
@@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi
}
_ => {
for c in n.children_mut().into_iter().flatten() {
if !v.enters(c) {
continue;
}
let mut m = (**c).clone();
let k = recolor_node(&mut m, reach, v);
if k > 0 {
+259
View File
@@ -0,0 +1,259 @@
//! Scaling images whose pixels carry straight (not premultiplied) alpha.
//!
//! `image`'s filtered resampling filters each channel on its own, which is correct only for
//! premultiplied pixels, and its thumbnail averages each channel on its own too, so on
//! straight-alpha pixels the color under clear pixels bleeds into the opaque ones next to them
//! (clear black darkens a cut-out's edge). [`resized`], [`fitted`] and [`averaged`] weight each
//! pixel's color by its alpha while scaling, as the streaming shrink in the renderer does.
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
/// How [`resized`] makes each new pixel from the old ones.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Resample {
/// `image`'s filtered resampling with this filter.
Filter(FilterType),
/// The mean of the old pixels each new one covers ([`averaged`]).
Average,
}
/// `img` scaled to `w` × `h` pixels as `how` says, each pixel's color weighted by its alpha.
/// Filtered or averaged, an image with clear or partly clear pixels comes back as 8-bit RGBA
/// whatever its own pixel format, and a pixel that ends up wholly clear is transparent black. An
/// image without clear pixels is scaled as `image` scales it, in its own pixel format.
/// Nearest-neighbor picking leaves the pixels as they are, in their own format, and is not
/// weighted. Filtered, the colors keep the precision of premultiplied 8-bit pixels, and an 8-bit
/// RGBA image is premultiplied in place.
pub fn resized(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
if (w, h) == (img.width(), img.height()) {
return img;
}
let f = match how {
Resample::Average => return averaged(&img, w, h),
Resample::Filter(f) => f,
};
if f == FilterType::Nearest || opaque(&img) {
return img.resize_exact(w, h, f);
}
let mut rgba = img.into_rgba8();
for p in rgba.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = times_alpha(*c, *a);
}
}
let mut out = image::imageops::resize(&rgba, w, h, f);
for p in out.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = over_alpha(*c, *a);
}
}
DynamicImage::ImageRgba8(out)
}
/// [`resized`] to the largest size that fits `w` × `h` pixels and keeps `img`'s proportions, the
/// size `image`'s own `resize` and `thumbnail` pick.
pub fn fitted(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
let (nw, nh) = fit_size(img.width(), img.height(), w, h);
resized(img, nw, nh, how)
}
/// `img` scaled to `w` × `h` pixels, each new pixel the mean of the old pixels it covers, each old
/// pixel counted by the area of it covered and its color weighted by its alpha. `img` is read one
/// row at a time, so besides the result this takes one row of 8-bit RGBA at most. An image
/// without clear pixels is scaled as `image`'s thumbnail scales it.
pub fn averaged(img: &DynamicImage, w: u32, h: u32) -> DynamicImage {
let (sw, sh) = (img.width(), img.height());
if opaque(img) || w == 0 || h == 0 || sw == 0 || sh == 0 {
return img.thumbnail_exact(w, h);
}
// Per new pixel of the row being made: red, green and blue times alpha, alpha (all times the
// area covered), and the area covered.
let mut sums = vec![([0f64; 4], 0f64); w as usize];
let mut out = Vec::with_capacity(w as usize * h as usize * 4);
for ty in 0..h {
for (y, wy) in covered(ty, sh, h) {
let row = rgba_row(img, y as u32);
for ((s, area), tx) in sums.iter_mut().zip(0..w) {
for (x, wx) in covered(tx, sw, w) {
let Some(p) = row.get(x * 4..x * 4 + 4) else { continue };
let k = wx * wy;
let a = f64::from(p[3]) * k;
s[0] += f64::from(p[0]) * a;
s[1] += f64::from(p[1]) * a;
s[2] += f64::from(p[2]) * a;
s[3] += a;
*area += k;
}
}
}
let byte = |v: f64| v.round().clamp(0.0, 255.0) as u8;
for (s, area) in &mut sums {
out.extend(if s[3] <= 0.0 { [0; 4] } else { [byte(s[0] / s[3]), byte(s[1] / s[3]), byte(s[2] / s[3]), byte(s[3] / *area)] });
(*s, *area) = ([0.0; 4], 0.0);
}
}
RgbaImage::from_raw(w, h, out).map_or_else(|| img.thumbnail_exact(w, h), DynamicImage::ImageRgba8)
}
/// Row `y` of `img` as 8-bit RGBA: borrowed from an 8-bit RGBA image, converted from others.
fn rgba_row(img: &DynamicImage, y: u32) -> std::borrow::Cow<'_, [u8]> {
let n = img.width() as usize * 4;
match img {
DynamicImage::ImageRgba8(b) => std::borrow::Cow::Borrowed(b.as_raw().get(y as usize * n..(y as usize + 1) * n).unwrap_or_default()),
other => std::borrow::Cow::Owned(other.crop_imm(0, y, other.width(), 1).into_rgba8().into_raw()),
}
}
/// The old pixels that new pixel `t` of `tn` covers along a side of `n` old pixels, each with the
/// length of it covered (in old pixels), worked out as they are read so that nothing is stored.
fn covered(t: u32, n: u32, tn: u32) -> impl Iterator<Item = (usize, f64)> {
let scale = f64::from(n) / f64::from(tn);
let (a, b) = (f64::from(t) * scale, (f64::from(t) + 1.0) * scale);
let (first, end) = (a.floor() as u32, (b.ceil() as u32).min(n));
(first..end.max(first + 1).min(n)).filter_map(move |i| {
let len = b.min(f64::from(i) + 1.0) - a.max(f64::from(i));
(len > 0.0).then_some((i as usize, len))
})
}
/// Each 4-channel pixel of `px` with all four channels multiplied by its value in `alpha` (one
/// sample a pixel, 0 to 255): ink amounts or colors made ready for scaling beside a separate alpha
/// channel. Pixels past the end of `alpha` are left as they are.
pub fn premultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = times_alpha(*c, a);
}
}
}
/// [`premultiply`] undone after scaling: each 4-channel pixel of `px` divided by its value in the
/// scaled `alpha`, and 0 where that is 0.
pub fn unpremultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = over_alpha(*c, a);
}
}
}
/// Does `img` have no alpha channel, or is every pixel of it opaque?
fn opaque(img: &DynamicImage) -> bool {
match img {
DynamicImage::ImageRgba8(b) => b.pixels().all(|p| p[3] == u8::MAX),
DynamicImage::ImageLumaA8(b) => b.pixels().all(|p| p[1] == u8::MAX),
DynamicImage::ImageRgba16(b) => b.pixels().all(|p| p[3] == u16::MAX),
DynamicImage::ImageLumaA16(b) => b.pixels().all(|p| p[1] == u16::MAX),
DynamicImage::ImageRgba32F(b) => b.pixels().all(|p| p[3] >= 1.0),
other => !other.color().has_alpha(),
}
}
/// Channel `c` times alpha `a`, both 0 to 255.
fn times_alpha(c: u8, a: u8) -> u8 {
((u16::from(c) * u16::from(a) + 127) / 255) as u8
}
/// Premultiplied channel `c` divided by alpha `a` (0 when `a` is 0).
fn over_alpha(c: u8, a: u8) -> u8 {
if a == 0 {
return 0;
}
let a = u32::from(a);
((u32::from(c) * 255 + a / 2) / a).min(255) as u8
}
/// The largest size of at most `nw` × `nh` with the proportions of `w` × `h`, at least a pixel a
/// side.
pub fn fit_size(w: u32, h: u32, nw: u32, nh: u32) -> (u32, u32) {
if w == 0 || h == 0 {
return (nw.max(1), nh.max(1));
}
let ratio = (f64::from(nw) / f64::from(w)).min(f64::from(nh) / f64::from(h));
let side = |n: u32| ((f64::from(n) * ratio).round() as u32).max(1);
(side(w), side(h))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 4 × 2 image whose left half is opaque red and whose right half is clear black.
fn half_clear() -> DynamicImage {
DynamicImage::ImageRgba8(RgbaImage::from_fn(4, 2, |x, _| if x < 2 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }))
}
/// Is the color of `p`, premultiplied by its alpha, within a step of `rgb` premultiplied by the
/// same alpha (the precision of premultiplied 8-bit pixels)?
fn close(p: [u8; 4], rgb: [u8; 3]) -> bool {
p[..3].iter().zip(rgb).all(|(&c, want)| times_alpha(c, p[3]).abs_diff(times_alpha(want, p[3])) <= 1)
}
#[test]
fn averaging_keeps_the_color_of_the_opaque_pixels() {
let p = resized(half_clear(), 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0;
assert!(close(p, [200, 30, 30]) && p[3].abs_diff(128) <= 1, "{p:?}");
}
/// Three pixels averaged into two: each new pixel takes one old pixel whole and half of the
/// clear one in the middle.
#[test]
fn averaging_counts_the_part_of_a_pixel_covered() {
let img = RgbaImage::from_fn(3, 1, |x, _| if x == 1 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([200, 30, 30, 255]) });
let out = averaged(&DynamicImage::ImageRgba8(img), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 30, 30, 170], [200, 30, 30, 170]].concat());
// Gray with alpha is read the same way.
let gray = image::GrayAlphaImage::from_fn(3, 1, |x, _| image::LumaA(if x == 1 { [0, 0] } else { [200, 255] }));
let out = averaged(&DynamicImage::ImageLumaA8(gray), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 200, 200, 170], [200, 200, 200, 170]].concat());
}
#[test]
fn filtering_keeps_the_color_of_the_opaque_pixels() {
for f in [FilterType::Triangle, FilterType::CatmullRom, FilterType::Lanczos3] {
let out = resized(half_clear(), 2, 1, Resample::Filter(f)).into_rgba8();
for x in 0..2 {
let p = out.get_pixel(x, 0).0;
assert!(p[3] == 0 || close(p, [200, 30, 30]), "{f:?} pixel {x}: {p:?}");
}
}
}
#[test]
fn fitted_keeps_proportions() {
let img = DynamicImage::ImageRgba8(RgbaImage::new(400, 100));
let out = fitted(img, 64, 64, Resample::Average);
assert_eq!((out.width(), out.height()), (64, 16));
}
#[test]
fn opaque_and_alpha_free_images_scale_as_image_scales_them() {
let rgb = DynamicImage::ImageRgb8(image::RgbImage::from_fn(5, 3, |x, y| image::Rgb([x as u8 * 40, y as u8 * 60, 7])));
let ours = resized(rgb.clone(), 2, 2, Resample::Filter(FilterType::Triangle));
assert_eq!(ours, rgb.resize_exact(2, 2, FilterType::Triangle));
let opaque = DynamicImage::ImageRgba8(rgb.to_rgba8());
assert_eq!(resized(opaque.clone(), 2, 2, Resample::Average), opaque.thumbnail_exact(2, 2));
}
#[test]
fn a_wholly_clear_result_is_transparent_black() {
let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 0])));
assert_eq!(resized(img, 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0, [0, 0, 0, 0]);
}
#[test]
fn premultiply_and_unpremultiply_scale_beside_a_separate_alpha() {
// Two pixels of inks, the second clear: averaged, the first one's inks remain.
let mut px = vec![40, 80, 120, 160, 0, 0, 0, 0];
premultiply(&mut px, &[255, 0]);
let img = RgbaImage::from_raw(2, 1, px).unwrap();
let mut out = image::imageops::thumbnail(&img, 1, 1).into_raw();
let alpha = image::imageops::thumbnail(&image::GrayImage::from_raw(2, 1, vec![255, 0]).unwrap(), 1, 1).into_raw();
unpremultiply(&mut out, &alpha);
let want = [40, 80, 120, 160];
assert!(out.iter().zip(want).all(|(&c, w)| times_alpha(c, alpha[0]).abs_diff(times_alpha(w, alpha[0])) <= 1), "{out:?} {alpha:?}");
}
}
+59 -2
View File
@@ -49,6 +49,13 @@ pub struct Selection {
/// it when no object is selected to align to it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_guide: Option<NodeId>,
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
/// point is no longer a selected anchor, or fewer than two points are selected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_anchor: Option<(NodeId, AnchorRef)>,
/// The new art on a locked artboard that this selection keeps editable
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
/// the engine then sets the document's from it. Editing state, never saved.
@@ -98,6 +105,7 @@ impl Selection {
self.slices.clear();
self.guides.clear();
self.key_guide = None;
self.key_anchor = None;
self.symbol_part = None;
self.on_path_member = None;
}
@@ -113,9 +121,15 @@ impl Selection {
self.set([instance]);
self.symbol_part = Some(SymbolPart { instance, path });
}
/// Is there a key for Align: an object or a guide?
/// Is there a key for Align: an object, a guide or an anchor point?
pub fn has_key(&self) -> bool {
self.key.is_some() || self.key_guide.is_some()
self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some()
}
/// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is
/// gone from its path.
pub fn key_anchor_point(&self, doc: &Document) -> Option<vectorcraft_geom::Point> {
let (id, (si, ai)) = self.key_anchor?;
Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p)
}
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
@@ -143,6 +157,9 @@ impl Selection {
if self.key == Some(id) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| k == id) {
self.key_anchor = None;
}
}
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
@@ -162,6 +179,9 @@ impl Selection {
if self.key.is_some_and(|k| ids.contains(&k)) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) {
self.key_anchor = None;
}
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
@@ -271,6 +291,40 @@ impl Selection {
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
self.key_guide = None;
}
// A key anchor needs its point on its path and selected as an anchor point (not as a
// selected segment's end), with another point selected too: another anchor, or a path
// selected whole (Align and Distribute act on path points only). It takes the place of a
// key object or key guide.
let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data());
let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some());
// Selected anchor points that are on their paths, counted up to two.
let points = || {
self.anchors
.iter()
.flat_map(|(o, set)| {
let path = path_of(o);
set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())))
})
.take(2)
.count()
};
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
self.objects.contains(&id)
&& !self.segments.contains_key(&id)
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
&& found
.get(&id)
.and_then(|p| doc.node_at(p))
.and_then(|n| n.path_data())
.is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))
&& (points() >= 2 || self.objects.iter().any(whole_path))
});
if anchor_kept {
self.key = None;
self.key_guide = None;
} else {
self.key_anchor = None;
}
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
// and the object still in the symbol's art as a path, compound path or type, where neither
// it nor a group or layer around it is hidden, locked or a template.
@@ -348,6 +402,9 @@ impl Selection {
if self.key.is_some_and(|k| gone.contains(&k)) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) {
self.key_anchor = None;
}
}
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
/// (the art of its sublayers too), anything else is selected itself.
+26
View File
@@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() {
assert_eq!(none, s);
}
#[test]
fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() {
for kept in [false, true] {
let mut s = Selection::default();
for i in 1..=4 {
s.add(NodeId(i));
}
s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)]));
s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)]));
s.key_anchor = Some((NodeId(2), (0, 0)));
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
s.guides = vec![NodeId(10)];
s.key_guide = Some(NodeId(10));
let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] };
let mut one_by_one = s.clone();
for id in ids {
one_by_one.remove(id);
}
let mut all = s.clone();
all.remove_all(ids);
assert_eq!(all, one_by_one);
assert_eq!(all.key_anchor.is_some(), kept);
assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10))));
}
}
#[test]
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
+17
View File
@@ -206,6 +206,13 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Assamese", "as", Quotes::ENGLISH),
("Sanskrit", "sa", Quotes::ENGLISH),
("Urdu", "ur", Quotes::ENGLISH),
// “…” outside, ‘…’ inside: CLDR gives these no delimiters of their own (`↑↑↑`, inherited), so
// they take root's (https://github.com/unicode-org/cldr/blob/main/common/main/root.xml,
// `delimiters`): sa.xml, ne.xml, as.xml, kok.xml and sd.xml (Arabic script; sd_Deva.xml for
// Devanagari inherits too) in https://github.com/unicode-org/cldr/blob/main/common/main/.
("Nepali", "ne", Quotes::ENGLISH),
("Konkani", "kok", Quotes::ENGLISH),
("Sindhi", "sd", Quotes::ENGLISH),
];
/// The quotes of a [`LANGUAGES`] entry (case-insensitive).
@@ -420,6 +427,11 @@ mod tests {
assert_eq!(char_language("BG"), Ok(Some("bg")));
assert_eq!(char_language_name(Some("bg")), Some("Bulgarian"));
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
// Sanskrit, Nepali, Assamese, Konkani (a three-letter tag) and Sindhi, by name or tag.
for (name, tag) in [("Sanskrit", "sa"), ("Nepali", "ne"), ("Assamese", "as"), ("Konkani", "kok"), ("Sindhi", "sd")] {
assert_eq!((char_language(name), char_language(&tag.to_uppercase())), (Ok(Some(tag)), Ok(Some(tag))), "{name}");
assert_eq!(char_language_name(Some(tag)), Some(name));
}
// Every entry has a tag of its own, and a name of its own.
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}");
@@ -443,6 +455,11 @@ mod tests {
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Sanskrit, Nepali, Assamese, Konkani and Sindhi take CLDR root's quotes.
for name in ["Sanskrit", "Nepali", "Assamese", "Konkani", "Sindhi"] {
let mut prev = None;
assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "“a ‘b’ c”", "{name}");
}
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
+57 -5
View File
@@ -20,6 +20,8 @@ pub enum StoredRoot {
GraphDesign(usize),
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
Pattern { pattern: usize, art: usize },
/// Root `index` of [`Document::mounted_art`].
Mounted(usize),
}
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
@@ -170,10 +172,12 @@ impl Document {
.iter()
.enumerate()
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
symbols.chain(designs).chain(patterns)
let mounted = self.mounted_art.iter().enumerate().map(|(i, (n, _))| (n, StoredRoot::Mounted(i)));
symbols.chain(designs).chain(patterns).chain(mounted)
}
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns.
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns,
/// then [`Document::mounted_art`].
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
}
@@ -185,12 +189,13 @@ impl Document {
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
StoredRoot::Mounted(i) => self.mounted_art.get_mut(i).map(|(n, _)| n),
}
}
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
/// once each, never the copies instances and tiles draw).
/// once each, never the copies instances and tiles draw), then [`Document::mounted_art`].
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
self.visit_stored_arcs(|n, place| f(n, place));
}
@@ -238,6 +243,29 @@ impl Document {
/// visited before them (the layer tree's own objects first) a new id, so every stored object
/// can be named by its id. Returns how many changed; the id counter then stands above them.
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
self.renumber_duplicates_in(|_| true)
}
/// Raises the id counter above the ids of [`Document::mounted_art`]'s objects, then gives those
/// objects whose id is 0, past the id range, or already taken by an object visited before them
/// (every other stored object first) a new id, as [`Self::renumber_stored_duplicates`] gives
/// them. Returns how many changed.
pub fn number_mounted_art(&mut self) -> usize {
let mut max = 0;
for (i, (root, _)) in self.mounted_art.iter().enumerate() {
visit(root, StoredPlace { root: StoredRoot::Mounted(i), mask_of: None }, &mut |n, _| {
if n.id.0 < MAX_NEXT_ID {
max = max.max(n.id.0);
}
});
}
self.raise_next_id(max.saturating_add(1));
self.renumber_duplicates_in(|r| matches!(r, StoredRoot::Mounted(_)))
}
/// [`Self::renumber_stored_duplicates`] for the roots `pick` holds for only; the objects of the
/// others still count as taken.
fn renumber_duplicates_in(&mut self, pick: impl Fn(StoredRoot) -> bool) -> usize {
let mut seen: HashSet<NodeId> = HashSet::new();
for l in &self.layers {
l.walk(&mut |n| {
@@ -250,9 +278,9 @@ impl Document {
// Per root, the visiting indices of the nodes that take a new id.
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
for (root, r) in self.stored_roots() {
let (mut i, mut here) = (0, HashSet::new());
let (mut i, mut here, take) = (0, HashSet::new(), pick(r));
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) && take {
here.insert(i);
}
i += 1;
@@ -355,6 +383,30 @@ mod tests {
assert_eq!(d, again);
}
/// Mounted art is found and changed by id after the other stored art, and numbering it gives
/// its objects that repeat another stored object's id, or have none, new ids above the counter,
/// leaving every other object's id and its own unique ones as they are.
#[test]
fn mounted_art_is_found_and_numbered_after_the_rest() {
let mut d = doc([12, 13, 14]);
let owner = serde_json::json!({ "kind": "brush" });
d.mounted_art = vec![(Arc::new(masked(10, rect(0))), owner.clone()), (Arc::new(rect(15)), owner)];
assert_eq!(d.stored_node(NodeId(15)).map(|(_, p)| p.root), Some(StoredRoot::Mounted(1)));
let before = d.clone();
assert_eq!(d.number_mounted_art(), 2);
let mut ids = vec![];
d.visit_stored(|n, _| ids.push(n.id.0));
let unique: HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
assert_eq!(&ids[..6], &[d.layers[0].id.0, 10, 11, 12, 13, 14], "the other art keeps its ids");
assert_eq!(ids[8], 15, "a unique id is kept");
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art) && Arc::ptr_eq(&d.mounted_art[1].0, &before.mounted_art[1].0));
d.stored_node_mut(NodeId(15)).unwrap().name = Some("changed".into());
assert_eq!(d.mounted_art[1].0.name.as_deref(), Some("changed"));
assert_eq!(d.number_mounted_art(), 0, "a second pass changes nothing");
}
#[test]
fn renumbered_objects_on_path_keep_their_path_and_members() {
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
+71
View File
@@ -162,6 +162,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
BuiltinStyleLibrary { id: "neon-glow", name: "Neon & Glow", make: neon_glow },
];
/// Built-in library `id`, made once.
@@ -619,6 +620,44 @@ fn status_effects() -> Vec<GraphicStyle> {
]
}
/// Neon & Glow: original multi-layer procedural styles with neon tubes, laser beams, and glowing halos.
fn neon_glow() -> Vec<GraphicStyle> {
vec![
style(
"Cyan Neon",
vec![S(StrokeLayer { opacity: 0.7, ..round("#00e5ff", 6.0) }), S(round("#ffffff", 1.5))],
vec![fx("stylize.dropShadow", json!({"mode": "screen", "opacity": 85.0, "x": 0.0, "y": 0.0, "blur": 8.0, "color": "#00e5ff"}))],
),
GraphicStyle {
blend: BlendMode::Screen,
..style(
"Magenta Laser",
vec![S(StrokeLayer { blend: BlendMode::Screen, ..round("#ff007f", 5.0) }), S(round("#ffffff", 1.5))],
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#ff007f"}))],
)
},
style(
"Amber Tube",
vec![S(StrokeLayer { opacity: 0.8, ..round("#ff8c00", 6.0) }), S(round("#ffea00", 1.5))],
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#ff8c00"}))],
),
style(
"Electric Lime",
vec![S(StrokeLayer { opacity: 0.75, ..round("#39ff14", 6.0) }), S(round("#ffffff", 1.5))],
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#39ff14"}))],
),
style(
"Pulse Violet",
vec![S(StrokeLayer { opacity: 0.75, ..round("#7b2cbf", 5.0) }), S(round("#e0aaff", 1.5))],
vec![
fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 75.0, "blur": 6.0, "color": "#c77dff", "source": "edge"})),
fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#7b2cbf"})),
],
),
style("Cobalt Phosphor", vec![S(round("#0047ab", 6.0)), S(round("#ffffff", 1.5))], vec![fx("blur.gaussian", json!({"radius": 2.0}))]),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -750,4 +789,36 @@ mod tests {
let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") };
assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0));
}
#[test]
fn neon_and_glow_styles_are_defined_with_multi_strokes_and_effects() {
let lib = builtin_style_library("neon-glow").expect("neon-glow library exists");
assert_eq!(lib.name, "Neon & Glow");
assert_eq!(lib.len(), 6);
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]);
for g in &lib.styles {
let strokes = g.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
assert!(strokes >= 2, "{} has {} strokes, expected >= 2", g.name, strokes);
assert!(!g.appearance.effects.is_empty(), "{} has effects", g.name);
}
let cyan = lib.style("Cyan Neon").unwrap();
assert_eq!(cyan.appearance.effects[0].id, "stylize.dropShadow");
let magenta = lib.style("Magenta Laser").unwrap();
assert_eq!(magenta.blend, BlendMode::Screen);
let pulse = lib.style("Pulse Violet").unwrap();
let pulse_fx: Vec<&str> = pulse.appearance.effects.iter().map(|e| e.id.as_str()).collect();
assert_eq!(pulse_fx, ["stylize.innerGlow", "stylize.outerGlow"]);
let cobalt = lib.style("Cobalt Phosphor").unwrap();
assert_eq!(cobalt.appearance.effects[0].id, "blur.gaussian");
}
#[test]
fn neon_glow_round_trips_through_vcstyles() {
let lib = builtin_style_library("neon-glow").unwrap();
let text = write(&lib);
assert!(sniff(&text));
let read_back = read(&text, "Fallback").unwrap();
assert_eq!(*lib, read_back);
}
}
+335 -15
View File
@@ -8,6 +8,7 @@
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::sync::Arc;
use vectorcraft_color::swatch::REGISTRATION;
@@ -206,11 +207,13 @@ impl Document {
impl Document {
/// Visit every paint held by the art (opacity masks included), symbol definitions, pattern
/// tiles and graphic styles (fills, strokes and text runs), and the colour of every
/// gradient-mesh point as a solid paint.
/// gradient-mesh point as a solid paint. A graph's default black legend fill is left out.
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
let default_legend = default_legend_fill(m);
graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p));
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -338,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
/// and gradient stops (with their link), a dynamic symbol instance's own paints
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
let _ = try_node_colors::<()>(n, &mut |c, s| {
f(c, s);
ControlFlow::Continue(())
});
}
/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one.
pub fn node_has_colors(n: &Node) -> bool {
try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break()
}
/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no
/// paint or node after it is visited.
fn try_node_colors<B>(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow<B>) -> ControlFlow<B> {
n.try_walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?,
Paint::Gradient(g) => {
for s in &g.gradient.stops {
f(&s.color, s.swatch.as_deref())?;
}
}
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
for p in &mesh.points {
f(&p.color, None)?;
}
}
});
ControlFlow::Continue(())
})
}
fn item_paint(it: &AppearanceItem) -> &Paint {
@@ -382,14 +406,14 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
}
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which
/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out.
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
let g = n.extras().graph.as_deref();
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
let l = g.map(|g| &g.label_styles);
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten();
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten())
}
@@ -398,12 +422,25 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
let l = &mut g.label_styles;
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten();
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten();
series
.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
}
/// The place in [`graph_paints`] of the legend fill graph `n` keeps when it is the default black of a graph that picks
/// its legend labels' fill ([`crate::graph::GraphSpec::picks_legend_fill`]). Other graphs draw the kept fill as it is,
/// so it is visited and mapped.
fn default_legend_fill(n: &Node) -> Option<usize> {
let g = n.extras().graph.as_deref()?;
let l = &g.label_styles;
if l.legend.is_none() || !g.picks_legend_fill() {
return None;
}
let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum();
Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some())))
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -446,11 +483,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
// The default black legend fill, which is not the legend labels' own, stays black.
let default_legend = default_legend_fill(n);
let graph: Vec<(usize, Paint)> =
graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
// A legend fill of the labels' own stays theirs when the change makes it black.
spec.label_styles.mark_own_legend_fill();
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
@@ -698,6 +740,14 @@ mod tests {
paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() },
..Default::default()
}),
axis_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
..Default::default()
}),
ring_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
..Default::default()
}),
..Default::default()
},
..Default::default()
@@ -705,21 +755,79 @@ mod tests {
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == red));
assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row");
assert_eq!(seen, 7, "the fill and the graph's series fill, series stroke, legend fill, value label fill row and axis and ring stroke rows");
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
assert_eq!(d.map_solid_paints(&mut to_blue), 5);
assert_eq!(d.map_solid_paints(&mut to_blue), 7);
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
let legend = g.label_styles.legend.unwrap();
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand")));
assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four");
assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six");
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn a_legend_fill_mapped_to_black_stays_the_labels_own() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() },
..Default::default()
};
assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark");
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut to_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| {
s.as_deref() == Some("Brand") && {
*c = Color::BLACK;
*s = None;
true
}
};
assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK));
assert!(styles.legend_fill_set, "the black fill is still the labels' own");
}
#[test]
fn the_default_black_legend_fill_is_left_as_it_is() {
use crate::graph::GraphKind;
// Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black.
for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] {
let (mut d, a, _) = doc();
let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() };
let spec = crate::graph::GraphSpec {
kind,
legend: true,
pie_legend_in_wedges: in_wedges,
series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }],
label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() },
..Default::default()
};
let blacks = |d: &Document| {
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK)));
seen
};
let before = blacks(&d);
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let want = if picks { 2 } else { 3 };
assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited");
let mut link_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none();
assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") };
assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill");
assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black"));
}
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
@@ -735,4 +843,216 @@ mod tests {
node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string))));
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
}
});
}
/// Whether [`full_walk`] finds a color in `n`.
fn full_walk_has_colors(n: &Node) -> bool {
let mut found = false;
full_walk(n, &mut |_, _| found = true);
found
}
/// The colors of `n` by [`full_walk`], in order.
fn full_walk_colors(n: &Node) -> Vec<(Color, Option<String>)> {
let mut out = vec![];
full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string))));
out
}
fn square(id: u64, fill: Paint, stroke: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0))
}
fn holder(id: u64, kind: fn(Vec<Arc<Node>>) -> NodeKind, children: Vec<Node>) -> Node {
Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect()))
}
/// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color.
fn color_cases() -> Vec<(&'static str, Node, bool)> {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let gradient = |stops: usize| {
let mut g = vectorcraft_color::Gradient::default();
g.stops.truncate(stops);
Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g)))
};
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
let mut empty_mesh = mesh.clone();
empty_mesh.points.clear();
let text = |fill: Paint| {
let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() };
let mut n =
Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style))));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n
};
let image = |colorize: Option<Paint>| {
let im = crate::ImageObject {
key: "k".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im)));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n.extras_mut().colorize = colorize.map(Box::new);
n
};
let overridden = |fill: Option<Paint>| {
let mut n = square(22, Paint::None, Paint::None);
n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }];
n
};
let masked = {
let mut n = square(23, Paint::None, Paint::None);
n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true)));
n
};
let group = |children| NodeKind::Group { children, clip: false };
let clip = |children| NodeKind::Group { children, clip: true };
let compound = |children| NodeKind::Compound { children, rule: Default::default() };
let blend = |children| NodeKind::Blend { children, spec: Default::default() };
let blank = |id| square(id, Paint::None, Paint::None);
vec![
("no paint", blank(1), false),
("solid fill", square(2, red.clone(), Paint::None), true),
("solid stroke", square(3, Paint::None, red.clone()), true),
("pattern only", square(4, pattern.clone(), pattern.clone()), false),
("gradient without stops", square(5, gradient(0), Paint::None), false),
("gradient with stops", square(6, gradient(2), Paint::None), true),
("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true),
("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false),
("text run fill", text(red.clone()), true),
("text without paint", text(Paint::None), false),
("image colorize", image(Some(red.clone())), true),
("image without colorize", image(None), false),
("image with a pattern colorize", image(Some(pattern.clone())), false),
("symbol override fill", overridden(Some(red.clone())), true),
("symbol override without paint", overridden(None), false),
("color only in the opacity mask", masked, false),
("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true),
("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true),
("group without color", holder(38, group, vec![blank(39), blank(40)]), false),
("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true),
("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true),
("blend", holder(47, blend, vec![blank(48), blank(49)]), false),
(
"nested groups, color deepest",
holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]),
true,
),
]
}
#[test]
fn has_colors_matches_the_full_walk() {
for (label, n, expected) in color_cases() {
let all = full_walk_colors(&n);
assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}");
assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}");
assert_eq!(node_has_colors(&n), expected, "{label}");
let mut listed = vec![];
node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string))));
assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order");
}
}
#[test]
fn has_colors_stops_at_the_first_color() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let mut stops = vectorcraft_color::Gradient::default();
stops.stops.push(stops.stops[0].clone());
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops)));
let mut later = vec![square(2, gradient, red.clone())];
later.extend((3..100).map(|id| square(id, red.clone(), red.clone())));
let n = holder(1, |children| NodeKind::Group { children, clip: false }, later);
let (mut colors, mut nodes) = (0, 0);
let flow = try_node_colors(&n, &mut |_, _| {
colors += 1;
ControlFlow::Break(())
});
assert!(flow.is_break());
assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read");
let flow = n.try_walk(&mut |m| {
nodes += 1;
if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});
assert!(flow.is_break());
assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it");
}
/// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in
/// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn has_colors_timing() {
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
fn clock(start: std::time::Instant) -> u128 {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
}
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let count = 100_000u64;
let group = |colored: &dyn Fn(u64) -> bool| {
let children =
(0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) });
holder(0, |children| NodeKind::Group { children, clip: false }, children.collect())
};
let cases = [
("every path filled", group(&|_| true)),
("only the last path filled", group(&|i| i == count - 1)),
("no path filled", group(&|_| false)),
];
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
// The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms.
let per_call = |f: fn(&Node) -> bool, n: &Node| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(std::hint::black_box(n)));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 30 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
for (label, n) in &cases {
assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}");
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(full_walk_has_colors, n));
new.push(per_call(node_has_colors, n));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, nw) = (old[3], new[3]);
println!(
"{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs",
o.0, o.1, nw.0, nw.1
);
}
}
}
+36 -18
View File
@@ -463,8 +463,13 @@ impl NineSliceMap {
///
/// Strokes keep their weight, as they do for any instance.
pub fn place(&self, art: &Node, doc: &Document) -> Node {
let boxes = doc.symbol_boxes().quick();
self.place_at(art, &boxes, 0)
self.place_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node {
self.place_at(art, boxes, 0)
}
/// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF):
@@ -480,16 +485,25 @@ impl NineSliceMap {
/// object drawn in clip groups counts one group plus a clip path and a copy for each cell its
/// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`.
pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 {
let boxes = doc.symbol_boxes().quick();
self.most_at(art, &boxes, 0)
self.most_placed_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 {
self.most_at(art, boxes, 0)
}
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
/// origin when it has no box. `None` when its box crosses a guide.
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
let boxes = doc.symbol_boxes().quick();
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
self.one_cell_with(n, &doc.symbol_boxes().quick())
}
/// [`Self::one_cell`] with the instances in `n` measured by `boxes`.
pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option<Affine> {
let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
return Some(self.cell_at(Point::ZERO));
};
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
@@ -501,6 +515,11 @@ impl NineSliceMap {
Self { clips: false, ..*self }.most_placed(art, doc)
}
/// This map placing without clip groups, as [`Self::place_unclipped`] does.
pub(crate) fn unclipped(&self) -> Self {
Self { clips: false, ..*self }
}
/// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`].
fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let whole = n.count_with_masks() as u64;
@@ -671,7 +690,7 @@ impl NineSliceMap {
}
/// `n` moved by `a`, its strokes at their own weight.
fn transformed(n: &Node, a: Affine) -> Node {
pub(crate) fn transformed(n: &Node, a: Affine) -> Node {
let mut out = n.clone();
out.transform(a, false);
out
@@ -765,10 +784,7 @@ impl Document {
/// `None` when the symbol has no guides or the instance is at its natural size. The guides cut
/// the art's box with the instances in it measured by their own art.
pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.symbol_nine_slice(name)?;
let sym = self.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?;
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
self.symbol_boxes().quick().slice_map(name, xf)
}
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
@@ -782,9 +798,10 @@ impl Document {
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
/// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]).
pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf) {
Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
@@ -795,8 +812,8 @@ impl Document {
pub fn edited_nine_slice(&self) -> Option<EditedNineSlice> {
let se = self.symbol_edit.as_ref()?;
let guides = self.symbol_nine_slice(&se.symbol)?;
let sym = self.symbols.iter().find(|s| s.name == se.symbol)?;
let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?;
let boxes = self.symbol_boxes().quick();
let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?;
let natural = self.symbol_natural_xf(&se.symbol);
let b = natural.transform_rect_bbox(art);
if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 {
@@ -811,8 +828,9 @@ impl Document {
/// [`Self::place_symbol_art`] for writers that do not apply clipping
/// ([`NineSliceMap::place_unclipped`]).
pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf).map(|m| m.unclipped()) {
Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
+80
View File
@@ -0,0 +1,80 @@
//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their
//! actual size wherever they are placed
//! (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28>).
//!
//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned
//! (the default) is left out of the map.
use std::collections::HashSet;
use crate::Document;
/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol.
pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned";
impl Document {
/// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off).
pub fn symbol_pixel_aligned(&self, name: &str) -> bool {
self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false)
}
/// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map,
/// and the map goes when it is empty.
pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) {
if on {
let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({}));
if let Some(o) = m.as_object_mut() {
o.insert(name.into(), serde_json::json!(true));
}
return;
}
let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return };
o.remove(name);
if o.is_empty() {
self.unknown.remove(SYMBOL_PIXEL_ALIGNED);
}
}
/// Move the stored setting when a symbol is renamed.
pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) {
if from == to {
return;
}
let on = self.symbol_pixel_aligned(from);
self.set_symbol_pixel_aligned(from, false);
self.set_symbol_pixel_aligned(to, on);
}
/// The names of the pixel-aligned symbols the document holds (empty for most documents).
pub fn pixel_aligned_symbols(&self) -> HashSet<String> {
let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() };
o.iter()
.filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name))
.map(|(name, _)| name.clone())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_setting_is_off_by_default_and_follows_a_rename() {
let mut d = Document::new(100.0, 100.0);
let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![]));
d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art });
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
d.set_symbol_pixel_aligned("A", true);
assert!(d.symbol_pixel_aligned("A"));
assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()]));
d.symbols[0].name = "B".into();
d.rename_symbol_pixel_aligned("A", "B");
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.symbol_pixel_aligned("B"));
d.set_symbol_pixel_aligned("B", false);
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
assert!(d.pixel_aligned_symbols().is_empty());
}
}
+532 -37
View File
@@ -2,13 +2,14 @@
//! the document and measures it once, and an instance's bounds are its art's box placed by the
//! instance's transform ([`Node::geometric_bounds_with`]).
use std::cell::{Cell, RefCell};
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -26,6 +27,9 @@ const MAX_REACHES: usize = 4096;
/// A symbol's name and the bits of the linear part of a transform that places its art.
type Placing = (String, [u64; 4]);
/// Each symbol name of a document → the index of the first symbol of that name.
pub(crate) type SymbolNames = HashMap<String, usize>;
/// A symbol's art measured in symbol space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ArtBox {
@@ -43,6 +47,11 @@ pub(crate) struct ArtBox {
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
/// holds one at any depth.
pub(crate) sliced: bool,
/// The box of the regions that the live geometry effects of the clipping paths in the art give
/// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such
/// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has
/// one.
pub(crate) reshaped: Option<Rect>,
}
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
@@ -51,6 +60,10 @@ pub(crate) struct ArtBox {
/// symbols change.
pub struct SymbolBoxes<'a> {
doc: &'a Document,
/// Each symbol name of the document → the index of the first symbol of that name (the one a
/// name finds), made the first time a name is looked up ([`Self::symbol_art`]) or given by
/// [`Self::with_names`].
names: OnceCell<Arc<SymbolNames>>,
/// The art boxes measured so far, by symbol name (`None` for a symbol whose instances are
/// measured by [`SYMBOL_SQUARE`]).
measured: RefCell<HashMap<String, Option<ArtBox>>>,
@@ -89,6 +102,137 @@ pub struct SymbolBoxes<'a> {
sliced_most: u64,
/// The widths [`Self::measured_width`] has measured, by kind and symbol name.
widths: RefCell<HashMap<(&'static str, String), Option<f64>>>,
/// While [`Self::consulted`] runs: the symbols whose art boxes [`Self::art`] has given outside
/// the measuring of symbol art.
consulted: RefCell<Option<HashSet<String>>>,
}
/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and
/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and
/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]).
/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's
/// art is held by a weak pointer. 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::make_mut` moves it), so art
/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`.
struct KeptKey {
symbols: Vec<(String, std::sync::Weak<Node>)>,
guides: Option<serde_json::Value>,
inputs: (u64, bool),
}
impl KeptKey {
/// The key of the document's 9-slice guides.
const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE;
fn of(doc: &Document, inputs: (u64, bool)) -> Self {
KeptKey {
symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(),
guides: doc.unknown.get(Self::GUIDES).cloned(),
inputs,
}
}
/// Does this describe `doc`'s symbols as they are now, with inputs `inputs`?
fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool {
self.inputs == inputs
&& self.symbols.len() == doc.symbols.len()
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name)
&& self.guides.as_ref() == doc.unknown.get(Self::GUIDES)
}
fn same(&self, other: &KeptKey) -> bool {
self.inputs == other.inputs
&& self.symbols.len() == other.symbols.len()
&& self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m)
&& self.guides == other.guides
}
}
/// Art boxes, nesting depths and the name index measured by boxes made by
/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols.
struct Kept {
key: KeptKey,
names: Option<Arc<SymbolNames>>,
measured: HashMap<String, Option<ArtBox>>,
depths: HashMap<String, Option<usize>>,
}
/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread:
/// clicks can alternate between two open documents.
const KEPT_SETS: usize = 2;
thread_local! {
/// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first.
static KEPT: RefCell<Vec<Kept>> = const { RefCell::new(Vec::new()) };
}
/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the
/// next ones when dropped.
pub(crate) struct KeptBoxes<'a> {
boxes: SymbolBoxes<'a>,
/// What the measurements depend on, under which they are kept.
key: Option<KeptKey>,
/// Other boxes of the same document whose measurements are kept with these
/// ([`Self::keeping`]).
also: Option<&'a SymbolBoxes<'a>>,
}
impl<'a> std::ops::Deref for KeptBoxes<'a> {
type Target = SymbolBoxes<'a>;
fn deref(&self) -> &SymbolBoxes<'a> {
&self.boxes
}
}
impl<'a> KeptBoxes<'a> {
/// These boxes, which also keep the art boxes and nesting depths `other` has measured when
/// dropped. `other` measures the same document, as the boxes of
/// [`Document::locked_artboards_kept`] do.
pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self {
self.also = Some(other);
self
}
}
impl Drop for KeptBoxes<'_> {
/// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive
/// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice
/// guides are left out: measuring them places art within a budget the boxes share
/// ([`SymbolBoxes::sliced_visual`]).
fn drop(&mut self) {
let Some(key) = self.key.take() else { return };
let b = &self.boxes;
let mut measured = b.measured.take();
let mut depths = b.depths.take();
if let Some(other) = self.also {
for (name, a) in other.measured.borrow().iter() {
measured.entry(name.clone()).or_insert(*a);
}
for (name, d) in other.depths.borrow().iter() {
depths.entry(name.clone()).or_insert(*d);
}
}
measured.retain(|_, a| a.is_none_or(|a| !a.sliced));
let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths };
// Nothing is kept while the thread ends or the list is in use.
let _ = KEPT.try_with(|k| {
if let Ok(mut k) = k.try_borrow_mut() {
if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) {
let other = k.remove(i);
kept.names = kept.names.or(other.names);
for (name, a) in other.measured {
kept.measured.entry(name).or_insert(a);
}
for (name, d) in other.depths {
kept.depths.entry(name).or_insert(d);
}
}
k.insert(0, kept);
k.truncate(KEPT_SETS);
}
});
}
}
impl Document {
@@ -96,6 +240,7 @@ impl Document {
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
SymbolBoxes {
doc: self,
names: OnceCell::new(),
measured: RefCell::default(),
depths: RefCell::default(),
quick: Cell::new(false),
@@ -110,8 +255,79 @@ impl Document {
sliced_placed: Cell::new(0),
sliced_most: MAX_SYMBOL_NODES,
widths: RefCell::default(),
consulted: RefCell::default(),
}
}
/// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured
/// by the last such boxes made on this thread for the same symbols, and keep theirs for the next
/// ones when dropped. The measurements are made again when a symbol's name or art, the symbols'
/// 9-slice guides, or the inputs of the live geometry effects of clipping paths have
/// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept.
pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> {
self.kept_boxes(false)
}
/// [`Self::symbol_boxes`] that start with a copy of the measurements
/// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves.
pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> {
let mut kept = self.kept_boxes(true);
kept.key = None;
std::mem::replace(&mut kept.boxes, self.symbol_boxes())
}
/// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them.
fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> {
let mut boxes = self.symbol_boxes();
let inputs = crate::hit::clip_region_inputs();
let found = KEPT
.try_with(|k| {
let mut k = k.try_borrow_mut().ok()?;
let i = k.iter().position(|e| e.key.is_of(self, inputs))?;
if copy {
let e = k.get(i)?;
let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs };
Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() })
} else {
Some(k.remove(i))
}
})
.ok()
.flatten();
let key = match found {
Some(e) => {
if let Some(names) = e.names {
// The boxes were just made, so no index is set yet.
let _ = boxes.names.set(names);
}
*boxes.measured.get_mut() = e.measured;
*boxes.depths.get_mut() = e.depths;
e.key
}
None => KeptKey::of(self, inputs),
};
KeptBoxes { boxes, key: Some(key), also: None }
}
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
names.entry(s.name.clone()).or_insert(i);
}
names
}
}
#[cfg(test)]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
/// How many art boxes [`SymbolBoxes::art`] has measured on this thread.
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
}
impl<'a> SymbolBoxes<'a> {
@@ -120,6 +336,26 @@ impl<'a> SymbolBoxes<'a> {
self.doc
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
let _ = self.names.set(names.clone());
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
}
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -160,21 +396,39 @@ impl<'a> SymbolBoxes<'a> {
/// art boxes. Returns `None` when [`Self::depth`] is `None` and when the art has no finite
/// bounds: instances of the symbol are then measured by [`SYMBOL_SQUARE`].
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
if let Some(b) = self.measured.borrow().get(name) {
return *b;
let cached = self.measured.borrow().get(name).copied();
let b = cached.unwrap_or_else(|| {
#[cfg(test)]
ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1));
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
});
if b.is_some()
&& let Some(seen) = self.consulted.borrow_mut().as_mut()
&& !seen.contains(name)
{
seen.insert(name.to_string());
}
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
}
/// Runs `measure`, and returns the names of the symbols whose art boxes it took from these
/// boxes, the art of symbols it measured left out: the symbols whose art the instances it
/// measured are measured by.
pub(crate) fn consulted(&self, measure: impl FnOnce()) -> HashSet<String> {
let was = self.consulted.replace(Some(HashSet::new()));
measure();
self.consulted.replace(was).unwrap_or_default()
}
/// Runs `measure` on the art of the symbol named `name`. Returns `None` when [`Self::depth`]
/// is `None`, without running it.
pub fn measure_art<R>(&self, name: &str, measure: impl FnOnce(&Arc<Node>) -> R) -> Option<R> {
self.depth(name)?;
let sym = self.doc.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_art(name)?;
self.runs.set(self.runs.get() + 1);
Some(measure(&sym.art))
Some(measure(art))
}
/// How many times [`Self::measure_art`] has run a measure on symbol art for these boxes, the
@@ -297,10 +551,9 @@ impl<'a> SymbolBoxes<'a> {
/// other symbols it reaches: the depth of each one it walks to the end, and `None` for those on
/// the way down to a symbol that holds an instance of itself or nests too deep.
fn find_depth(&self, name: &str, learned: &mut HashMap<String, Option<usize>>) -> Option<usize> {
let art = |n: &str| self.doc.symbols.iter().find(|s| s.name == n).map(|s| &s.art);
// The symbols on the way down from `name`: each with the symbols its art shows that are
// still to be walked, and the deepest nesting found under it so far.
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), shown(self.doc, art(name)?), 0)];
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), self.shown(self.symbol_art(name)?), 0)];
loop {
let (_, todo, _) = path.last_mut()?;
let Some(next) = todo.pop() else {
@@ -330,8 +583,8 @@ impl<'a> SymbolBoxes<'a> {
// Symbols nested MAX_DEPTH deep under `name`.
None if path.len() >= MAX_DEPTH => return None,
None => {
if let Some(a) = art(&next) {
let todo = shown(self.doc, a);
if let Some(a) = self.symbol_art(&next) {
let todo = self.shown(a);
path.push((next, todo, 0));
}
}
@@ -379,9 +632,9 @@ impl<'a> SymbolBoxes<'a> {
None => {
// The most objects placing makes, the art of opacity masks included, is set aside
// while the art is placed and measured, and what placing did not make is given back.
let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art;
let most = match self.doc.symbol_slice_map(name, linear) {
Some(m) => m.most_placed(art, self.doc),
let art = self.symbol_art(name)?;
let most = match self.slice_map(name, linear) {
Some(m) => self.in_art(|| m.most_placed_with(art, self)),
None => art.count_with_masks() as u64,
};
let used = self.sliced_placed.get();
@@ -398,6 +651,14 @@ impl<'a> SymbolBoxes<'a> {
v.map(|v| moved.transform_rect_bbox(v))
}
/// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for
/// the symbol (its geometric part, which does not depend on the mode of the boxes).
pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.doc.symbol_nine_slice(name)?;
let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?;
NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf)
}
/// The box [`Self::placed_visual_within`] returns outside quick boxes.
fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
self.place_and_count(name, xf, most).and_then(|(v, _)| v)
@@ -407,10 +668,10 @@ impl<'a> SymbolBoxes<'a> {
/// opacity masks included. `None` when the art is not placed.
fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option<Rect>, u64)> {
self.measure_art(name, |art| {
let art = match self.doc.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self.doc) > most => return None,
Some(m) => m.place(art, self.doc),
None => self.doc.place_symbol_art(name, art, xf)?,
let art = match self.slice_map(name, xf) {
Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None,
Some(m) => self.in_art(|| m.place_with(art, self)),
None => transformed(art, xf),
};
Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64))
})
@@ -431,11 +692,28 @@ impl<'a> SymbolBoxes<'a> {
fn in_art<R>(&self, f: impl FnOnce() -> R) -> R {
let pad = self.brush_art.replace(false);
let strokes = self.art_strokes.replace(true);
let consulted = self.consulted.take();
let r = self.quickly(f);
self.brush_art.set(pad);
self.art_strokes.set(strokes);
*self.consulted.borrow_mut() = consulted;
r
}
/// The names of the symbols of the document that the instances in `art` show, each once.
fn shown(&self, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& self.symbol_art(symbol).is_some()
{
names.push(symbol.clone());
}
});
names
}
}
/// Records every symbol on `path` in `learned` as one whose instances are measured by
@@ -447,21 +725,6 @@ fn give_up(path: &[(String, Vec<String>, usize)], learned: &mut HashMap<String,
None
}
/// The names of the symbols of `doc` that the instances in `art` show, each once.
fn shown(doc: &Document, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& doc.symbols.iter().any(|s| s.name == *symbol)
{
names.push(symbol.clone());
}
});
names
}
/// Measures symbol art `art`, with the instances in it measured by `symbols`.
fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite());
@@ -486,16 +749,27 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
}
});
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
let mut reshaped = None;
if effects {
art.walk(&mut |n| {
let b = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)),
_ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)),
_ => None,
};
reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite));
});
}
Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped })
}
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
use vectorcraft_geom::shapes;
use vectorcraft_geom::{Point, shapes};
use super::*;
use crate::{Appearance, Symbol};
use crate::{Appearance, NodeId, Symbol};
/// A rectangle filled black, with a `stroke` pt black stroke (0: none).
fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node {
@@ -630,6 +904,39 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
// scaled 2 times across, each shown by 200 instances scaled by different amounts.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Dot {i}"), vec![dot]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default()));
let scaled = |d: &mut Document, name: &str| -> Vec<Node> {
(1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect()
};
let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder"));
// What each instance measures in boxes of its own.
let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect();
let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect();
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), exact);
let s = d.symbol_boxes().quick();
assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), quick);
// Each set of boxes reads the list once to find symbols by name.
let symbols = d.symbols.len();
assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before);
}
#[test]
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
let mut d = Document::new(200.0, 200.0);
@@ -786,4 +1093,192 @@ mod tests {
assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0);
assert_eq!(runs.get(), MAX_REACHES + 2);
}
/// How many art boxes `f` measures on this thread.
fn art_boxes_measured(f: impl FnOnce()) -> usize {
let before = ART_BOXES_MEASURED.with(Cell::get);
f();
ART_BOXES_MEASURED.with(Cell::get) - before
}
/// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an
/// instance of each at (40 i + 20, 20).
fn ten_symbols() -> Document {
let mut d = Document::new(400.0, 100.0);
let layer = d.layers.first().map(|l| l.id);
for i in 0..10 {
let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0);
symbol(&mut d, &format!("S {i}"), vec![square]);
let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0)));
d.insert(layer, usize::MAX, at).unwrap();
}
d
}
#[test]
fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit");
assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1);
}
assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10);
};
let first = art_boxes_measured(clicks);
assert_eq!(first, 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
}
#[test]
fn hit_tests_measure_a_symbol_again_after_it_changes() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
// Past the square of "S 1" at (60, 20).
let past = Point::new(71.0, 20.0);
assert!(hit::hit_test(&d, past, HitOptions::default()).is_none());
// The art grows 3 times in place: no other copy of it is held in the document.
Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false);
let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit"));
assert!(measured > 0);
// New art for "S 2", 40 wide.
let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0);
d.symbols[2].art = Arc::new(wide);
assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit");
// "S 3" renamed: its instance now shows the 20 × 20 square.
d.symbols[3].name = "Renamed".into();
assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit");
assert_eq!(hits(&d), fresh_hits(&d));
}
/// What clicks on a grid over `d` hit, and what a marquee over it selects.
fn hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
use crate::hit::{self, HitOptions};
let mut clicks = Vec::new();
for y in (0..400).step_by(5) {
for x in (0..400).step_by(5) {
let p = Point::new(f64::from(x), f64::from(y));
clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry));
}
}
(clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false))
}
/// [`hits`] with no measurements kept from earlier hit tests.
fn fresh_hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
KEPT.with_borrow_mut(Vec::clear);
hits(d)
}
/// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is
/// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without
/// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150.
fn sliced_holder(guides: bool) -> Document {
let mut d = Document::new(400.0, 400.0);
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
symbol(&mut d, "Bar", vec![bar]);
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
symbol(&mut d, "Panel", vec![frame, inner]);
if guides {
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
}
let panel = instance(&mut d, "Panel", Affine::IDENTITY);
symbol(&mut d, "Holder", vec![panel]);
let layer = d.layers.first().map(|l| l.id);
let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0));
d.insert(layer, usize::MAX, holder).unwrap();
d
}
#[test]
fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() {
use crate::hit::{self, HitOptions};
let mut d = sliced_holder(false);
// Left of the frame, where only the bar placed through the guides draws.
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_none());
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit");
assert_eq!(hits(&d), fresh_hits(&d));
let before = hits(&d);
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] }));
let after = hits(&d);
assert_ne!(after, before, "the size moves the guides");
assert_eq!(after, fresh_hits(&d));
}
#[test]
fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() {
use crate::hit::{self, HitOptions};
let d = sliced_holder(true);
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some());
// The holder's art holds an instance of a symbol with guides; the panel's art holds none.
KEPT.with_borrow(|k| {
let measured = &k[0].measured;
assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys());
});
let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()));
assert!(again > 0, "the holder's art box measured again");
}
#[test]
fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() {
let d = ten_symbols();
let key = KeptKey::of(&d, (0, false));
assert!(key.is_of(&d, (0, false)));
assert!(!key.is_of(&d, (1, false)), "live inputs changed");
assert!(!key.is_of(&d, (0, true)), "a clip region registered");
}
#[test]
fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
d.artboards[0].locked = true;
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard");
assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty());
}
};
assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
// A marquee passes over the objects on a locked artboard without measuring them itself: only
// its locks measure their art.
let mut d = ten_symbols();
d.artboards[0].locked = true;
let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty());
assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again");
}
#[test]
fn hit_tests_hold_no_symbol_art() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default()));
assert!(KEPT.with_borrow(|k| !k.is_empty()));
assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art");
}
#[test]
fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() {
use crate::hit::{self, HitOptions};
let docs = [ten_symbols(), ten_symbols(), ten_symbols()];
let p = Point::new(20.0, 20.0);
for d in &docs {
drop(hit::hit_test(d, p, HitOptions::default()));
}
assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS);
// The last two are kept, the first is measured again.
let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default()))));
assert_eq!(kept, 0);
let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default())));
assert!(first > 0);
}
}
+15
View File
@@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() {
}
}
/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing
/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing.
#[test]
fn a_very_long_expression_reads_as_nothing() {
let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1));
assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0));
assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0)));
// Long text with no signs still reads.
assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0));
for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] {
assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len());
assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len());
}
}
proptest! {
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
/// or as nothing and does not panic.
+12 -5
View File
@@ -18,23 +18,24 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
WARICHU_SCALE, WarichuAlign,
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
};
pub use runs::PATH_LEAD_MAX;
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
};
pub use wrap::{resolve_wrap, wrap_work};
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
///
@@ -66,6 +67,12 @@ pub struct TextObject {
/// it on a frame that leaves its thread and on a copy. Not saved.
#[serde(skip)]
pub first_para_continues: bool,
/// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the
/// last character of that paragraph in the frames before that a repeat mark could stand for
/// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout
/// reads it only while `first_para_continues` is on. Not saved.
#[serde(skip)]
pub first_para_lead: Option<char>,
/// Area Type Options (area type only).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub area: AreaOptions,
+152 -2
View File
@@ -44,6 +44,16 @@ pub struct CharStyle {
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Tsume (Character panel, East Asian options): the percentage of the blank space on each side
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
/// after it. In vertical type an upright character is measured above and below its ink, inside
/// its cell down the column.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
/// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html>
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub tsume: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -172,6 +182,18 @@ pub struct CharStyle {
/// these characters are drawn in, whatever digits were typed.
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub digits: Digits,
/// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's
/// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points)
/// move right by a positive value and left by a negative one, relative to their letters, in
/// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`].
/// Saved only when not 0.
/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549>
#[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")]
pub diacritic_horizontal: f64,
/// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by
/// a negative one, as [`Self::diacritic_horizontal`] moves them across.
#[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")]
pub diacritic_vertical: f64,
/// Font height reference (Character panel menu › Show Font Height Options): the height of the
/// font that [`Self::size`] measures, the em box by default.
#[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")]
@@ -197,6 +219,108 @@ pub struct CharStyle {
/// default glyph otherwise. Saved only when set.
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
pub glyph_alternate: Option<GlyphChoice>,
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
/// font's default glyphs. The text keeps its characters. Saved only when set.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
pub glyph_form: GlyphForm,
}
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GlyphForm {
/// The font's default glyphs.
#[default]
Default,
/// Traditional forms (`trad`).
Traditional,
/// Expert forms (`expt`).
Expert,
/// JIS 2004 forms (`jp04`).
Jis04,
/// JIS 90 forms (`jp90`).
Jis90,
/// JIS 78 forms (`jp78`).
Jis78,
/// JIS 83 forms (`jp83`).
Jis83,
/// Monospaced full-width forms (`fwid`).
FullWidth,
/// Monospaced half-width forms (`hwid`).
HalfWidth,
/// Monospaced third-width forms (`twid`).
ThirdWidth,
/// Monospaced quarter-width forms (`qwid`).
QuarterWidth,
}
impl GlyphForm {
/// Every form, in menu order, the default last.
pub const ALL: [GlyphForm; 11] = [
GlyphForm::Traditional,
GlyphForm::Expert,
GlyphForm::Jis04,
GlyphForm::Jis90,
GlyphForm::Jis78,
GlyphForm::Jis83,
GlyphForm::FullWidth,
GlyphForm::HalfWidth,
GlyphForm::ThirdWidth,
GlyphForm::QuarterWidth,
GlyphForm::Default,
];
/// The name files and commands give this form (as it is saved).
pub fn id(self) -> &'static str {
match self {
GlyphForm::Default => "default",
GlyphForm::Traditional => "traditional",
GlyphForm::Expert => "expert",
GlyphForm::Jis04 => "jis04",
GlyphForm::Jis90 => "jis90",
GlyphForm::Jis78 => "jis78",
GlyphForm::Jis83 => "jis83",
GlyphForm::FullWidth => "fullWidth",
GlyphForm::HalfWidth => "halfWidth",
GlyphForm::ThirdWidth => "thirdWidth",
GlyphForm::QuarterWidth => "quarterWidth",
}
}
/// The form [`GlyphForm::id`] names; `None` for any other name.
pub fn from_id(id: &str) -> Option<GlyphForm> {
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
}
/// The OpenType feature that draws this form; `None` for the default glyphs.
pub fn feature(self) -> Option<&'static [u8; 4]> {
Some(match self {
GlyphForm::Default => return None,
GlyphForm::Traditional => b"trad",
GlyphForm::Expert => b"expt",
GlyphForm::Jis04 => b"jp04",
GlyphForm::Jis90 => b"jp90",
GlyphForm::Jis78 => b"jp78",
GlyphForm::Jis83 => b"jp83",
GlyphForm::FullWidth => b"fwid",
GlyphForm::HalfWidth => b"hwid",
GlyphForm::ThirdWidth => b"twid",
GlyphForm::QuarterWidth => b"qwid",
})
}
/// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may
/// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and
/// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied
/// with them.
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
pub fn is_width(self) -> bool {
matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth)
}
}
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
@@ -440,6 +564,13 @@ fn hundred() -> f64 {
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
/// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink.
pub const MAX_TSUME: f64 = 100.0;
/// The largest Adjust Horizontal or Vertical Diacritic Position either way
/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em.
pub const MAX_DIACRITIC_POSITION: f64 = 1000.0;
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
@@ -534,6 +665,7 @@ impl Default for CharStyle {
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
tsume: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -570,10 +702,13 @@ impl Default for CharStyle {
warichu_align: WarichuAlign::Auto,
small_caps: None,
digits: Digits::Default,
diacritic_horizontal: 0.0,
diacritic_vertical: 0.0,
font_height_reference: FontHeightReference::EmBox,
no_break: false,
language: None,
glyph_alternate: None,
glyph_form: GlyphForm::Default,
}
}
}
@@ -588,10 +723,12 @@ impl CharStyle {
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0. The Warichu Settings Lines and Scale
/// [`MAX_AKI`], and one that is not a number becomes 0; Tsume is kept from 0 to [`MAX_TSUME`] the
/// same way. The Warichu Settings Lines and Scale
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
/// own units.
/// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within
/// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -606,6 +743,10 @@ impl CharStyle {
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) };
let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) };
self.diacritic_horizontal = diacritic(self.diacritic_horizontal);
self.diacritic_vertical = diacritic(self.diacritic_vertical);
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
self.warichu_scale =
@@ -677,6 +818,15 @@ impl CharStyle {
self.position = self.position.in_range();
self.small_caps = self.small_caps.map(small_caps_in_range);
}
/// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default
/// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would
/// otherwise keep drawing its own glyph; the default form keeps it.
pub fn set_glyph_form(&mut self, form: GlyphForm) {
self.glyph_form = form;
if form != GlyphForm::Default {
self.glyph_alternate = None;
}
}
}
impl crate::Document {
+247 -26
View File
@@ -1,11 +1,16 @@
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
//! family; the layout sets each character in its class's font.
//! of their own, sized, raised and scaled against it). Custom character sets give characters the
//! user picks a font of their own too, ahead of their class; of two sets that list a character,
//! the later one sets it. Type set in a composite font names it as its family; the layout sets each
//! character in its set's or its class's font.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
//! custom character sets:
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's
//! own.
use serde::{Deserialize, Serialize};
@@ -179,12 +184,76 @@ impl CompositeParts {
}
}
/// A custom character set of a composite font: characters chosen by the user, set in a part of
/// their own instead of their class's part.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomCharSet {
/// The set's name, unique in its composite font in any case.
pub name: String,
/// The set's characters, each once, in the order they were added.
#[serde(default)]
pub characters: String,
/// The font, style, size, baseline and scales its characters take.
#[serde(flatten)]
pub part: CompositePart,
}
impl CustomCharSet {
/// An empty set named `name`, its characters set in `part`.
pub fn new(name: impl Into<String>, part: CompositePart) -> Self {
Self { name: name.into(), characters: String::new(), part }
}
/// Whether `c` can be in a custom character set: not a control character, and in the Basic
/// Multilingual Plane (U+0000 to U+FFFF).
pub fn takes(c: char) -> bool {
!c.is_control() && (c as u32) <= 0xFFFF
}
/// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x`
/// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses.
pub fn char_from_code(code: &str) -> Option<char> {
let code = code.trim();
let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code);
if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c))
}
}
/// Where a composite font sets a character: the part of one of its six classes, or the part of
/// one of its custom character sets (an index into [`CompositeFont::custom`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CompositeClass {
Fixed(CharClass),
Custom(usize),
}
/// The custom character set each character of a composite font's sets falls in
/// ([`CompositeFont::classes`]): the last set that lists it.
#[derive(Clone, Debug, Default)]
pub struct CompositeClasses {
custom: std::collections::HashMap<char, usize>,
}
impl CompositeClasses {
/// Where the composite font sets `c`: the last custom set that lists it, else its class.
pub fn of(&self, c: char) -> CompositeClass {
self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i))
}
}
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
/// that type set in it names.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeFont {
pub name: String,
pub parts: CompositeParts,
/// Custom character sets, checked before the classes. A character two sets list is set in the
/// later set's part.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub custom: Vec<CustomCharSet>,
}
/// The size a part can take, in percent of the type's size.
@@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
pub const COMPOSITE_NAME_MAX: usize = 255;
/// The most composite fonts a document or a file keeps.
pub const COMPOSITE_FONTS_MAX: usize = 256;
/// The most custom character sets a composite font keeps.
pub const CUSTOM_SETS_MAX: usize = 64;
/// The most characters a custom character set keeps.
pub const CUSTOM_CHARS_MAX: usize = 8192;
impl CompositeFont {
/// A composite font named `name` setting every class in `font` and `style`.
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() }
}
/// The part that sets the characters of `class`, `None` for a custom set the font doesn't have.
pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> {
match class {
CompositeClass::Fixed(c) => Some(self.parts.get(c)),
CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part),
}
}
/// Where this font sets character `c`: the last custom set that lists it, else its class. For
/// many characters, [`Self::classes`] looks each up faster.
pub fn class_of(&self, c: char) -> CompositeClass {
self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom)
}
/// The custom set each character of this font's sets falls in, to look up many characters.
pub fn classes(&self) -> CompositeClasses {
let mut custom = std::collections::HashMap::new();
for (i, s) in self.custom.iter().enumerate() {
for c in s.characters.chars() {
custom.insert(c, i);
}
}
CompositeClasses { custom }
}
/// Do `a` and `b` name the same composite font: equal in any case?
@@ -223,36 +321,50 @@ impl CompositeFont {
}
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
/// that has none.
/// part without a font, a value out of its range, a scale or Scale at Center on a class that
/// has none, or a custom character set [`Self::check_custom`] refuses.
pub fn check(&self) -> Result<(), String> {
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
return Err(format!("`{}` can't name a composite font", self.name));
}
for class in CharClass::ALL {
let p = self.parts.get(class);
let k = class.key();
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?;
}
self.check_custom()
}
/// Why this font's custom character sets can't be used, if they can't: more than
/// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a
/// character [`CustomCharSet::takes`] refuses or a set lists twice, more than
/// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's
/// characters can be scaled across and up; only kana are scaled at the center.
pub fn check_custom(&self) -> Result<(), String> {
if self.custom.len() > CUSTOM_SETS_MAX {
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
}
let mut names = std::collections::HashSet::new();
for s in &self.custom {
let name = &s.name;
if Self::clean_name(name).as_deref() != Some(name.as_str()) {
return Err(format!("`{name}` can't name a character set"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
if !names.insert(name.to_lowercase()) {
return Err(format!("two character sets are named `{name}`"));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
let mut seen = std::collections::HashSet::new();
for (n, c) in s.characters.chars().enumerate() {
if n == CUSTOM_CHARS_MAX {
return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"));
}
if v != 100.0 && !class.scales() {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
let code = c as u32;
if !CustomCharSet::takes(c) {
return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF"));
}
if !seen.insert(c) {
return Err(format!("`{name}`: U+{code:04X} is listed twice"));
}
}
if p.scale_at_center && class != CharClass::Kana {
return Err(format!("{k}: only kana can be scaled at the center"));
}
check_part(&s.part, name, true, false)?;
}
Ok(())
}
@@ -264,9 +376,41 @@ impl CompositeFont {
let mut names = std::collections::HashSet::new();
let mut kept: Vec<CompositeFont> =
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase())));
(kept.len() != fonts.len()).then_some(kept)
}
/// The fonts of the parts, each class's then each custom set's.
pub fn part_fonts(&self) -> impl Iterator<Item = &str> {
CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str()))
}
}
/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out
/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false.
fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> {
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
}
if v != 100.0 && !scales {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
}
}
if p.scale_at_center && !center {
return Err(format!("{k}: only kana can be scaled at the center"));
}
Ok(())
}
#[cfg(test)]
@@ -341,4 +485,81 @@ mod tests {
spaced.name = " Mixed".into();
assert!(spaced.check().is_err());
}
/// A character a custom set lists falls in that set ahead of its class, the later of two sets
/// that list it wins, and the quick lookup agrees with the one-character one.
#[test]
fn custom_sets_take_their_characters_before_the_classes() {
let mut f = CompositeFont::new("Mixed", "Inter", "Regular");
let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold"));
a.characters = "※A".into();
let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic"));
b.characters = "AB".into();
f.custom = vec![a, b];
let classes = f.classes();
for (c, want) in [
('※', CompositeClass::Custom(0)),
('A', CompositeClass::Custom(1)),
('B', CompositeClass::Custom(1)),
('C', CompositeClass::Fixed(CharClass::Roman)),
('漢', CompositeClass::Fixed(CharClass::Kanji)),
] {
assert_eq!(f.class_of(c), want, "{c:?}");
assert_eq!(classes.of(c), want, "{c:?}");
}
assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold"));
assert_eq!(f.part(CompositeClass::Custom(2)), None);
assert_eq!(f.check(), Ok(()));
// Read and written with the part's fields beside the set's name and characters.
let json = serde_json::to_value(&f).unwrap();
assert_eq!(json["custom"][1]["characters"], "AB");
assert_eq!(json["custom"][1]["style"], "Italic");
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
// A font without sets is written as before.
assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none());
}
/// Set names, characters and limits are checked; sets scale like Roman letters.
#[test]
fn custom_sets_check_their_names_and_characters() {
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| {
let mut f = ok.clone();
for (name, chars) in sets {
let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular"));
s.characters = chars.into();
edit(&mut s.part);
f.custom.push(s);
}
f.check()
};
let none = |_: &mut CompositePart| {};
assert_eq!(with(vec![("Empty", "")], none), Ok(()));
assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(()));
assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err());
assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err());
assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets"));
assert!(with(vec![(" Pad", "A")], none).is_err());
assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice"));
assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009"));
assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B"));
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect();
let mut f = ok.clone();
f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") });
assert!(f.check().unwrap_err().contains("at most"));
let mut f = ok.clone();
f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect();
assert!(f.check().is_err());
}
/// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane.
#[test]
fn custom_set_codes_name_characters() {
assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ'));
assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※'));
assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A'));
for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] {
assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}");
}
}
}
+38 -8
View File
@@ -27,7 +27,11 @@ impl TextObject {
/// Character attributes as presented by controls (stored runs stay local for layout
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
let scale = self.style_scale()?;
Self::scaled_char_style(style, self.style_scale()?)
}
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
let mut style = style.clone();
style.size *= scale.points;
style.leading = style.leading.map(|v| v * scale.points);
@@ -57,19 +61,27 @@ impl TextObject {
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
/// transform).
///
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
/// non-uniform scale of the path would move, and a uniform one keeps.
pub fn scale_text_attributes(&mut self) -> bool {
let Some(scale) = self.style_scale() else { return false };
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
let Some(mut scale) = self.style_scale() else { return false };
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
return false;
}
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
if matches!(self.kind, TextKind::OnPath { .. }) {
scale.horizontal = 1.0;
sx = sy;
}
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
return false;
}
let mut baked = Vec::with_capacity(self.runs.len());
for run in &self.runs {
let Some(eff) = self.effective_char_style(&run.style) else { return false };
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
baked.push(eff);
}
for (run, style) in self.runs.iter_mut().zip(baked) {
@@ -78,6 +90,14 @@ impl TextObject {
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
self.scale_char_strokes(1.0 / sy);
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
let grow = Affine::scale_non_uniform(sx, sy);
match &mut self.kind {
TextKind::Area { frame } => frame.transform(grow),
TextKind::OnPath { path, .. } => path.transform(grow),
TextKind::Point => {}
}
self.cached_bounds = None;
self.cached_baselines.clear();
self.cached_ink = None;
@@ -94,6 +114,7 @@ impl TextObject {
para: ParaStyle::default(),
paras: Vec::new(),
first_para_continues: false,
first_para_lead: None,
area: AreaOptions::default(),
path_effect: PathEffect::default(),
path_align: PathAlign::default(),
@@ -352,7 +373,10 @@ impl TextObject {
}
/// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its
/// centre bracket dragged across the path): the path runs the other way and the brackets swap
/// ends, so the type keeps its stretch of the path. False, changing nothing, for other type.
/// ends, so the type keeps its stretch of the path. Type that starts before an open path's start
/// ([`TextKind::path_text_start`]) starts at its start bracket after the flip: the part of its
/// span before the path's start would come after the path's end. False, changing nothing, for
/// other type.
pub fn flip_on_path(&mut self) -> bool {
let Some((s, e)) = self.kind.path_span() else { return false };
let TextKind::OnPath { path, start, end } = &mut self.kind else { return false };
@@ -507,6 +531,9 @@ impl crate::Document {
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.tsume = num("tsume").unwrap_or(st.tsume);
st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal);
st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical);
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
st.keep_dimensions_in_range();
@@ -532,6 +559,9 @@ impl crate::Document {
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("tsume", Some(st.tsume)),
("diacriticHorizontal", Some(st.diacritic_horizontal)),
("diacriticVertical", Some(st.diacritic_vertical)),
("leading", st.leading),
];
for (k, v) in kept {
+43 -4
View File
@@ -17,22 +17,52 @@ pub enum Justify {
JustifyAll,
}
/// Paragraph composer (Paragraph panel menu): how lines are broken.
/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts
/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South
/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set
/// here, and are what documents saved before the four composers existed use. The `Standard`
/// composers break lines the same way but set a complex script glyph by glyph as the font maps its
/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's
/// glyphs on Latin character codes (legacy ANSI Indic fonts) need.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Composer {
/// Break each line as soon as it is full.
/// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full.
SingleLine,
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
/// spacing, ragged lines an even rag.
/// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph
/// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag.
#[default]
EveryLine,
/// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped.
StandardSingleLine,
/// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped.
StandardEveryLine,
}
impl Composer {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Does this composer break lines one at a time (as opposed to a total fit)?
pub fn is_single_line(self) -> bool {
matches!(self, Self::SingleLine | Self::StandardSingleLine)
}
/// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])?
pub fn shapes_complex_scripts(self) -> bool {
matches!(self, Self::SingleLine | Self::EveryLine)
}
/// The same shaping with the other line breaking (`single_line`: one line at a time).
pub fn with_breaking(self, single_line: bool) -> Self {
match (single_line, self.shapes_complex_scripts()) {
(true, true) => Self::SingleLine,
(true, false) => Self::StandardSingleLine,
(false, true) => Self::EveryLine,
(false, false) => Self::StandardEveryLine,
}
}
}
/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic
@@ -241,6 +271,9 @@ pub struct ParaStyle {
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
/// with kinsoku None, where it has no effect. Off by default.
pub bunri_kinshi: bool,
/// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts
/// a line is drawn as the character it repeats, and the text keeps the mark. Off by default.
pub kurikaeshi_moji_shori: bool,
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
@@ -345,6 +378,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
bunri_kinshi: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kurikaeshi_moji_shori: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -382,6 +417,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -409,6 +445,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -440,6 +477,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -466,6 +504,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
+18 -2
View File
@@ -93,8 +93,10 @@ pub enum TextKind {
/// Area type flowed inside `frame` (document coordinates, untransformed by `xf`).
Area { frame: PathData },
/// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the
/// path length; no `end`: the end of the path, or once round a closed path). See
/// [`TextKind::path_span`].
/// path length; no `end`: the end of the path, or once round a closed path). On an open path
/// `start` may be below 0: the type starts that far before the path's start, and the characters
/// whose middle falls before the path's start are not drawn ([`TextKind::path_text_start`]).
/// See [`TextKind::path_span`].
OnPath {
path: PathData,
start: f64,
@@ -117,8 +119,22 @@ impl TextKind {
(s, end.map_or(1.0, |e| fraction(e).max(s)))
})
}
/// Where type on a path's text starts, as a fraction of its path's length: its start bracket
/// ([`Self::path_span`]), or on an open path a start before the path's start (below 0, at most
/// [`PATH_LEAD_MAX`] path lengths before it). None for other type.
pub fn path_text_start(&self) -> Option<f64> {
let TextKind::OnPath { path, start, .. } = self else { return None };
if !path.is_closed() && start.is_finite() && *start < 0.0 { Some(start.max(-PATH_LEAD_MAX)) } else { self.path_span().map(|(s, _)| s) }
}
/// Does type on an open path start before its path's start ([`Self::path_text_start`])?
pub fn starts_before_path(&self) -> bool {
self.path_text_start().is_some_and(|s| s < 0.0)
}
}
/// How far before its path's start type on an open path may start, in lengths of the path.
pub const PATH_LEAD_MAX: f64 = 1e6;
/// Move anchors `refs` of `path`, in text space, by `d` in document space (`to_text`: the
/// document → text map). False when an anchor doesn't exist.
pub(super) fn move_anchors(path: &mut PathData, to_text: Affine, refs: &[(usize, usize)], d: Vec2) -> bool {
Loaded 100 of 1266 files, more files were not shown because too many files have changed in this diff. Show more