mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # crates/text/src/fontdb/lookup.rs
This commit is contained in:
882 files changed
+97025
-9052
No files matched your search
Generated
+397
-106
File diff suppressed because it is too large.
Load diff
+46
-35
@@ -11,29 +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-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" }
|
||||
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 = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
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" }
|
||||
@@ -91,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.
|
||||
@@ -106,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
|
||||
@@ -130,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"
|
||||
@@ -173,13 +184,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -146,3 +146,125 @@ Indic hyphenation patterns (crates/text/patterns/):
|
||||
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
jpeg-encoder 0.6.1, https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Licensed under (MIT OR Apache-2.0) AND IJG. The MIT option and the IJG and SIMD
|
||||
notices are reproduced below. Original license texts and provenance hashes are
|
||||
retained in licenses/jpeg-encoder-0.6.1/.
|
||||
|
||||
--- jpeg-encoder 0.6.1: LICENSE-MIT ---
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
|
||||
--- jpeg-encoder 0.6.1: IJG-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
--- jpeg-encoder 0.6.1: SIMD-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
+10
-3
@@ -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
|
||||
@@ -131,9 +131,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 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.
|
||||
@@ -141,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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -155,8 +155,18 @@ 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() {
|
||||
@@ -197,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>
|
||||
(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;
|
||||
@@ -278,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
|
||||
#[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
|
||||
@@ -370,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(|| {
|
||||
@@ -390,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
|
||||
@@ -727,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)]
|
||||
@@ -741,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,
|
||||
@@ -813,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 {
|
||||
@@ -1441,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 copied files, SVG, text or PNG (by the types offered, nothing read).
|
||||
/// 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.
|
||||
/// 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) {
|
||||
@@ -1455,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1619,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() {
|
||||
@@ -1925,7 +2054,7 @@ 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, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
|
||||
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`.
|
||||
@@ -2016,11 +2145,6 @@ mod wayland {
|
||||
Some(first)
|
||||
}
|
||||
|
||||
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
|
||||
fn takes_files(mimes: &[&'static str]) -> bool {
|
||||
mimes.iter().any(|&m| m != TEXT)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
@@ -3092,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 {
|
||||
@@ -3103,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 })
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -3296,6 +3423,102 @@ mod tests {
|
||||
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<_>>();
|
||||
@@ -3349,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]
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,6 +63,7 @@ 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;
|
||||
@@ -72,6 +77,7 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_screen_color;
|
||||
mod windows_stylus;
|
||||
mod xwayland;
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -427,7 +458,10 @@ fn main() -> std::process::ExitCode {
|
||||
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()));
|
||||
@@ -458,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")]
|
||||
@@ -498,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);
|
||||
|
||||
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
|
||||
/// makes.
|
||||
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Metadata Templates") {
|
||||
session.attach_metadata_templates_dir(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Have File › New start each category's documents from its profile in the `New Document
|
||||
/// Profiles` folder, which `file.newProfiles.edit` makes.
|
||||
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! `--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.
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
for flag in [
|
||||
"--control",
|
||||
"--automation-read-root",
|
||||
"--automation-write-root",
|
||||
"--in-window-menus",
|
||||
"--safe-mode",
|
||||
"--present-mode",
|
||||
"--frame-latency",
|
||||
"--version",
|
||||
"--help",
|
||||
] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// A bad presentation variable stops the app with a message before it starts; `--help` and the
|
||||
/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail.
|
||||
#[test]
|
||||
fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() {
|
||||
for (var, value, need) in [
|
||||
("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"),
|
||||
("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"),
|
||||
] {
|
||||
let out = run(&[], &[(var, value)]);
|
||||
assert!(!out.status.success(), "{var}");
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n"));
|
||||
prints_usage(&["--help"], &[(var, value)]);
|
||||
}
|
||||
for (args, env) in [
|
||||
(&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")),
|
||||
(&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")),
|
||||
(&[], ("VECTORCRAFT_FRAME_LATENCY", "3")),
|
||||
] {
|
||||
let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}");
|
||||
}
|
||||
let out = run(&["--frame-latency", "4"], &[]);
|
||||
assert!(!out.status.success());
|
||||
assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n");
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
|
||||
@@ -20,4 +20,4 @@ craft-affinity = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# The tests build containers and decode previews.
|
||||
crc32fast = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
@@ -50,8 +50,8 @@ fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||||
assert_eq!((image.width, image.height), (400, 300));
|
||||
assert_eq!(image.transform, Affine::IDENTITY);
|
||||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
|
||||
let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8();
|
||||
assert_eq!(pixels.as_slice(), expected.as_raw());
|
||||
let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8();
|
||||
assert_eq!(pixels.as_slice(), expected.as_slice());
|
||||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||||
}
|
||||
|
||||
@@ -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
@@ -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};
|
||||
+21
-6
@@ -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)]
|
||||
@@ -429,8 +444,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
|
||||
return Err("the export region is not finite".into());
|
||||
}
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let baked =
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
|
||||
let 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
@@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
+46
-4
@@ -852,8 +852,19 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
|
||||
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
|
||||
/// `fill`'s rectangle.
|
||||
fn image_and_fill_doc(fill: Paint) -> Document {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 0, 255, 255].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
@@ -1312,8 +1323,19 @@ fn a_font_height_reference_is_written_as_the_size_drawn() {
|
||||
|
||||
#[test]
|
||||
fn images_link_png_or_jpeg_files() {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
4,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[255u8, 0, 0, 128].repeat(8),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
@@ -1451,3 +1473,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
|
||||
let cases: [(&str, DxfVersion, Document); 2] =
|
||||
[("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())];
|
||||
for (name, version, doc) in cases {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -1,674 +0,0 @@
|
||||
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
|
||||
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
|
||||
//! add layouts and plot styles, which CAD apps expect to find.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::DxfVersion;
|
||||
|
||||
/// An object handle (written in hex).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Handle(pub u32);
|
||||
|
||||
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
|
||||
/// [`FIRST_FREE`].
|
||||
pub(crate) mod fixed {
|
||||
use super::Handle;
|
||||
pub const LAYER_TABLE: Handle = Handle(0x1);
|
||||
pub const LTYPE_TABLE: Handle = Handle(0x2);
|
||||
pub const APPID_TABLE: Handle = Handle(0x3);
|
||||
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
|
||||
pub const STYLE_TABLE: Handle = Handle(0x5);
|
||||
pub const UCS_TABLE: Handle = Handle(0x6);
|
||||
pub const VIEW_TABLE: Handle = Handle(0x7);
|
||||
pub const VPORT_TABLE: Handle = Handle(0x8);
|
||||
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
|
||||
pub const ROOT: Handle = Handle(0xA);
|
||||
pub const GROUPS: Handle = Handle(0xB);
|
||||
pub const LAYOUTS: Handle = Handle(0xC);
|
||||
pub const MODEL_RECORD: Handle = Handle(0xD);
|
||||
pub const PAPER_RECORD: Handle = Handle(0xE);
|
||||
pub const MODEL_BLOCK: Handle = Handle(0xF);
|
||||
pub const MODEL_END: Handle = Handle(0x10);
|
||||
pub const PAPER_BLOCK: Handle = Handle(0x11);
|
||||
pub const PAPER_END: Handle = Handle(0x12);
|
||||
pub const MODEL_LAYOUT: Handle = Handle(0x13);
|
||||
pub const PAPER_LAYOUT: Handle = Handle(0x14);
|
||||
pub const ACTIVE_VPORT: Handle = Handle(0x15);
|
||||
pub const ACAD_APPID: Handle = Handle(0x16);
|
||||
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
|
||||
pub const IMAGE_DICT: Handle = Handle(0x18);
|
||||
pub const IMAGE_VARS: Handle = Handle(0x19);
|
||||
pub const PLOT_STYLES: Handle = Handle(0x1A);
|
||||
pub const PLOT_NORMAL: Handle = Handle(0x1B);
|
||||
pub const FIRST_FREE: u32 = 0x30;
|
||||
}
|
||||
|
||||
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
|
||||
pub(crate) fn num(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{v:.6}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
|
||||
}
|
||||
|
||||
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
|
||||
/// every character outside ASCII as `\U+XXXX`.
|
||||
pub(crate) fn text(s: &str, utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\r' | '\n' | '\t' => out.push(' '),
|
||||
c if c.is_control() => {}
|
||||
'^' => out.push_str("^ "),
|
||||
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
|
||||
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
|
||||
Err(_) => out.push('?'),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Group-code/value pairs in the order they are written.
|
||||
pub(crate) struct Codes {
|
||||
pub v: DxfVersion,
|
||||
out: String,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
pub fn new(v: DxfVersion) -> Self {
|
||||
Self { v, out: String::new() }
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.out
|
||||
}
|
||||
|
||||
pub fn append(&mut self, other: &str) {
|
||||
self.out.push_str(other);
|
||||
}
|
||||
|
||||
/// A value written as it is (names and keywords the writer itself chose).
|
||||
pub fn raw(&mut self, code: u16, value: &str) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
/// Text from the document, encoded for the version (see [`text`]).
|
||||
pub fn str(&mut self, code: u16, value: &str) {
|
||||
let t = text(value, self.v.utf8());
|
||||
self.raw(code, &t);
|
||||
}
|
||||
|
||||
pub fn int(&mut self, code: u16, value: i64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
pub fn num(&mut self, code: u16, value: f64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, code: u16, h: Handle) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
|
||||
}
|
||||
|
||||
/// A 2D point at `code` (x), `code + 10` (y).
|
||||
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.num(code, x);
|
||||
self.num(code + 10, y);
|
||||
}
|
||||
|
||||
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
|
||||
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.xy(code, x, y);
|
||||
self.num(code + 20, 0.0);
|
||||
}
|
||||
|
||||
/// The extrusion direction of planar entities: the z axis.
|
||||
pub fn normal(&mut self) {
|
||||
self.num(210, 0.0);
|
||||
self.num(220, 0.0);
|
||||
self.num(230, 1.0);
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
self.raw(0, kind);
|
||||
if self.v.handles() {
|
||||
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
|
||||
self.handle(330, owner);
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table entry: the shared record subclass, then the table's own (from R13).
|
||||
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
|
||||
self.object(kind, h, table, "AcDbSymbolTableRecord");
|
||||
if self.v.handles() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, name: &str) {
|
||||
self.raw(0, "SECTION");
|
||||
self.raw(2, name);
|
||||
}
|
||||
|
||||
fn end_section(&mut self) {
|
||||
self.raw(0, "ENDSEC");
|
||||
}
|
||||
|
||||
fn table(&mut self, name: &str, h: Handle, count: usize) {
|
||||
self.raw(0, "TABLE");
|
||||
self.raw(2, name);
|
||||
if self.v.handles() {
|
||||
self.handle(5, h);
|
||||
self.raw(330, "0");
|
||||
self.raw(100, "AcDbSymbolTable");
|
||||
}
|
||||
self.int(70, count as i64);
|
||||
if name == "DIMSTYLE" && self.v.r2000() {
|
||||
self.raw(100, "AcDbDimStyleTable");
|
||||
}
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
self.raw(0, "ENDTAB");
|
||||
}
|
||||
}
|
||||
|
||||
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct EntityStyle {
|
||||
pub aci: u8,
|
||||
/// `0xRRGGBB` (DXF 2004 and later).
|
||||
pub rgb: Option<u32>,
|
||||
/// Hundredths of a millimetre (DXF 2000 and later).
|
||||
pub lineweight: Option<i32>,
|
||||
pub linetype: Option<String>,
|
||||
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
|
||||
pub alpha: Option<u8>,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
|
||||
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
|
||||
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
|
||||
self.object(kind, h, owner, "AcDbEntity");
|
||||
self.str(8, layer);
|
||||
if let Some(lt) = &style.linetype {
|
||||
self.str(6, lt);
|
||||
}
|
||||
self.int(62, i64::from(style.aci.max(1)));
|
||||
if self.v.r2000()
|
||||
&& let Some(lw) = style.lineweight
|
||||
{
|
||||
self.int(370, i64::from(lw));
|
||||
}
|
||||
if self.v.true_color() {
|
||||
if let Some(rgb) = style.rgb {
|
||||
self.int(420, i64::from(rgb));
|
||||
}
|
||||
if let Some(a) = style.alpha {
|
||||
self.int(440, 0x0200_0000 | i64::from(a));
|
||||
}
|
||||
}
|
||||
if self.v.handles() && !subclass.is_empty() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DXF layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Layer {
|
||||
pub name: String,
|
||||
pub aci: u8,
|
||||
/// Switched off (a hidden layer).
|
||||
pub off: bool,
|
||||
pub locked: bool,
|
||||
/// Plotted (printable).
|
||||
pub plot: bool,
|
||||
}
|
||||
|
||||
/// A dash pattern: dash, gap, dash… lengths in drawing units.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LineType {
|
||||
pub name: String,
|
||||
pub pattern: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A placed image file and the image entities that show it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageDef {
|
||||
pub name: String,
|
||||
pub size: (u32, u32),
|
||||
pub handle: Handle,
|
||||
/// `(reactor, image entity)` per image entity.
|
||||
pub reactors: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
/// Everything around the entities, collected while they were written.
|
||||
pub(crate) struct Drawing {
|
||||
pub version: DxfVersion,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<LineType>,
|
||||
/// Text styles: (style name, font family).
|
||||
pub styles: Vec<(String, String)>,
|
||||
pub images: Vec<ImageDef>,
|
||||
/// The entities' group codes.
|
||||
pub entities: String,
|
||||
/// `[x0, y0, x1, y1]` of everything written (drawing units).
|
||||
pub extents: [f64; 4],
|
||||
/// The export region (drawing units).
|
||||
pub limits: [f64; 4],
|
||||
/// `$INSUNITS`.
|
||||
pub insunits: u8,
|
||||
pub metric: bool,
|
||||
/// The next free handle.
|
||||
pub next: u32,
|
||||
}
|
||||
|
||||
/// The text style every drawing has.
|
||||
pub(crate) const STANDARD_STYLE: &str = "Standard";
|
||||
|
||||
impl Drawing {
|
||||
/// The whole file.
|
||||
pub fn write(self) -> String {
|
||||
let v = self.version;
|
||||
let mut c = Codes::new(v);
|
||||
// Table entries get the handles after the entities'.
|
||||
let mut next = self.next;
|
||||
let mut take = |n: usize| {
|
||||
let start = next;
|
||||
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
|
||||
start
|
||||
};
|
||||
let ltype_base = take(3 + self.linetypes.len());
|
||||
let layer_base = take(1 + self.layers.len());
|
||||
let style_base = take(1 + self.styles.len());
|
||||
self.header(&mut c, next);
|
||||
if v.handles() {
|
||||
self.classes(&mut c);
|
||||
}
|
||||
c.section("TABLES");
|
||||
self.vport(&mut c);
|
||||
self.ltypes(&mut c, ltype_base);
|
||||
self.layer_table(&mut c, layer_base);
|
||||
self.style_table(&mut c, style_base);
|
||||
if v.handles() {
|
||||
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
|
||||
c.table(name, h, 0);
|
||||
c.end_table();
|
||||
}
|
||||
c.table("APPID", fixed::APPID_TABLE, 1);
|
||||
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
|
||||
c.raw(2, "ACAD");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
|
||||
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
|
||||
c.raw(2, "Standard");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
|
||||
for (name, h, layout) in
|
||||
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
|
||||
{
|
||||
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
|
||||
c.raw(2, name);
|
||||
if v.r2000() {
|
||||
c.handle(340, layout);
|
||||
c.int(70, 0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
c.section("BLOCKS");
|
||||
for (name, record, begin, end) in [
|
||||
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
|
||||
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
|
||||
] {
|
||||
c.object("BLOCK", begin, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockBegin");
|
||||
c.raw(2, name);
|
||||
c.int(70, 0);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
c.raw(3, name);
|
||||
c.raw(1, "");
|
||||
c.object("ENDBLK", end, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
c.section("ENTITIES");
|
||||
c.append(&self.entities);
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
self.objects(&mut c);
|
||||
}
|
||||
c.raw(0, "EOF");
|
||||
c.into_string()
|
||||
}
|
||||
|
||||
fn header(&self, c: &mut Codes, handseed: u32) {
|
||||
let v = self.version;
|
||||
let var = |c: &mut Codes, name: &str| c.raw(9, name);
|
||||
c.section("HEADER");
|
||||
var(c, "$ACADVER");
|
||||
c.raw(1, v.acadver());
|
||||
var(c, "$DWGCODEPAGE");
|
||||
c.raw(3, "ANSI_1252");
|
||||
var(c, "$INSBASE");
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
var(c, "$EXTMIN");
|
||||
c.xyz(10, x0, y0);
|
||||
var(c, "$EXTMAX");
|
||||
c.xyz(10, x1, y1);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
var(c, "$LIMMIN");
|
||||
c.xy(10, lx0, ly0);
|
||||
var(c, "$LIMMAX");
|
||||
c.xy(10, lx1, ly1);
|
||||
if v.r2000() {
|
||||
var(c, "$LWDISPLAY");
|
||||
c.int(290, 1);
|
||||
var(c, "$INSUNITS");
|
||||
c.int(70, i64::from(self.insunits));
|
||||
var(c, "$MEASUREMENT");
|
||||
c.int(70, i64::from(self.metric));
|
||||
}
|
||||
if v.handles() {
|
||||
var(c, "$HANDSEED");
|
||||
c.handle(5, Handle(handseed));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
fn classes(&self, c: &mut Codes) {
|
||||
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
|
||||
if self.version.r2000() {
|
||||
classes.extend([
|
||||
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
|
||||
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
|
||||
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
|
||||
]);
|
||||
}
|
||||
if !self.images.is_empty() {
|
||||
classes.extend([
|
||||
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
|
||||
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
|
||||
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
|
||||
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
|
||||
]);
|
||||
}
|
||||
c.section("CLASSES");
|
||||
for (name, cpp, app, flags, entity) in classes {
|
||||
c.raw(0, "CLASS");
|
||||
c.raw(1, name);
|
||||
c.raw(2, cpp);
|
||||
c.raw(3, app);
|
||||
c.int(90, flags);
|
||||
if self.version.true_color() {
|
||||
c.int(91, 0);
|
||||
}
|
||||
c.int(280, 0);
|
||||
c.int(281, i64::from(entity));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// The active viewport, zoomed to the drawing's extents.
|
||||
fn vport(&self, c: &mut Codes) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.table("VPORT", fixed::VPORT_TABLE, 1);
|
||||
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
|
||||
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
|
||||
c.int(70, 0);
|
||||
c.xy(10, 0.0, 0.0);
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
c.xy(13, 0.0, 0.0);
|
||||
c.xy(14, 1.0, 1.0);
|
||||
c.xy(15, 10.0, 10.0);
|
||||
// The view direction looks down the z axis: (0, 0, 1), each code once.
|
||||
c.xy(16, 0.0, 0.0);
|
||||
c.num(36, 1.0);
|
||||
c.xyz(17, 0.0, 0.0);
|
||||
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
// The view's height, with a margin; its width follows from the aspect ratio.
|
||||
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
|
||||
c.num(41, 1.5);
|
||||
c.num(42, 50.0);
|
||||
c.num(43, 0.0);
|
||||
c.num(44, 0.0);
|
||||
c.num(50, 0.0);
|
||||
c.num(51, 0.0);
|
||||
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
|
||||
c.int(code, value);
|
||||
}
|
||||
if self.version.r2000() {
|
||||
c.int(281, 0);
|
||||
c.int(65, 0);
|
||||
c.num(146, 0.0);
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn ltypes(&self, c: &mut Codes, base: u32) {
|
||||
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
|
||||
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
|
||||
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
|
||||
for (i, (name, desc, pattern)) in rows.enumerate() {
|
||||
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
|
||||
c.int(72, 65);
|
||||
c.int(73, pattern.len() as i64);
|
||||
c.num(40, pattern.iter().map(|v| v.abs()).sum());
|
||||
for v in pattern {
|
||||
c.num(49, *v);
|
||||
if self.version.handles() {
|
||||
c.int(74, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn layer_table(&self, c: &mut Codes, base: u32) {
|
||||
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
|
||||
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
|
||||
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
|
||||
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
|
||||
c.str(2, &l.name);
|
||||
c.int(70, if l.locked { 4 } else { 0 });
|
||||
// A negative colour switches the layer off.
|
||||
let aci = i64::from(l.aci.max(1));
|
||||
c.int(62, if l.off { -aci } else { aci });
|
||||
c.raw(6, "Continuous");
|
||||
if self.version.r2000() {
|
||||
c.int(290, i64::from(l.plot));
|
||||
c.int(370, -3);
|
||||
c.handle(390, fixed::PLOT_NORMAL);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn style_table(&self, c: &mut Codes, base: u32) {
|
||||
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
|
||||
let standard = (STANDARD_STYLE.to_string(), String::new());
|
||||
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
|
||||
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.num(40, 0.0);
|
||||
c.num(41, 1.0);
|
||||
c.num(50, 0.0);
|
||||
c.int(71, 0);
|
||||
c.num(42, 2.5);
|
||||
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
|
||||
if family.is_empty() {
|
||||
c.raw(3, "txt");
|
||||
} else {
|
||||
c.str(3, &format!("{family}.ttf"));
|
||||
}
|
||||
c.raw(4, "");
|
||||
if self.version.r2000() && !family.is_empty() {
|
||||
c.raw(1001, "ACAD");
|
||||
c.str(1000, family);
|
||||
c.int(1071, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn objects(&self, c: &mut Codes) {
|
||||
let v = self.version;
|
||||
let images = !self.images.is_empty();
|
||||
c.section("OBJECTS");
|
||||
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
|
||||
c.object("DICTIONARY", h, owner, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
for (name, e) in entries {
|
||||
c.str(3, name);
|
||||
c.handle(350, *e);
|
||||
}
|
||||
};
|
||||
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
|
||||
if images {
|
||||
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
|
||||
}
|
||||
if v.r2000() {
|
||||
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
|
||||
}
|
||||
dict(c, fixed::ROOT, Handle(0), &root);
|
||||
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
|
||||
if v.r2000() {
|
||||
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
|
||||
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
c.raw(3, "Normal");
|
||||
c.handle(350, fixed::PLOT_NORMAL);
|
||||
c.raw(100, "AcDbDictionaryWithDefault");
|
||||
c.handle(340, fixed::PLOT_NORMAL);
|
||||
// A placeholder has no data and no subclass marker of its own.
|
||||
c.raw(0, "ACDBPLACEHOLDER");
|
||||
c.handle(5, fixed::PLOT_NORMAL);
|
||||
c.handle(330, fixed::PLOT_STYLES);
|
||||
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
|
||||
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
|
||||
}
|
||||
if images {
|
||||
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
|
||||
c.int(90, 0);
|
||||
c.int(70, 0);
|
||||
c.int(71, 1);
|
||||
c.int(72, 0);
|
||||
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
|
||||
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
|
||||
for img in &self.images {
|
||||
c.raw(0, "IMAGEDEF");
|
||||
c.handle(5, img.handle);
|
||||
c.raw(102, "{ACAD_REACTORS");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
for (reactor, _) in &img.reactors {
|
||||
c.handle(330, *reactor);
|
||||
}
|
||||
c.raw(102, "}");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
c.raw(100, "AcDbRasterImageDef");
|
||||
c.int(90, 0);
|
||||
c.str(1, &img.name);
|
||||
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
for (reactor, image) in &img.reactors {
|
||||
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
|
||||
c.int(90, 2);
|
||||
c.handle(330, *image);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
|
||||
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
|
||||
c.raw(1, "");
|
||||
c.raw(2, "none_device");
|
||||
c.raw(4, "");
|
||||
c.raw(6, "");
|
||||
for code in 40..=49 {
|
||||
c.num(code, 0.0);
|
||||
}
|
||||
c.num(140, 0.0);
|
||||
c.num(141, 0.0);
|
||||
c.num(142, 1.0);
|
||||
c.num(143, 1.0);
|
||||
// Plot flags; 1024 marks the model space layout.
|
||||
c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 });
|
||||
c.int(72, 1);
|
||||
c.int(73, 0);
|
||||
c.int(74, 5);
|
||||
c.raw(7, "");
|
||||
c.int(75, 16);
|
||||
if self.version.true_color() {
|
||||
// Shade plot mode (as displayed), resolution level (normal) and custom DPI.
|
||||
c.int(76, 0);
|
||||
c.int(77, 2);
|
||||
c.int(78, 300);
|
||||
}
|
||||
c.num(147, 1.0);
|
||||
// The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158.
|
||||
c.num(148, 0.0);
|
||||
c.num(149, 0.0);
|
||||
c.raw(100, "AcDbLayout");
|
||||
c.raw(1, name);
|
||||
c.int(70, 1);
|
||||
c.int(71, tab);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
c.xy(10, lx0, ly0);
|
||||
c.xy(11, lx1, ly1);
|
||||
c.xyz(12, 0.0, 0.0);
|
||||
c.xyz(14, x0, y0);
|
||||
c.xyz(15, x1, y1);
|
||||
c.num(146, 0.0);
|
||||
c.xyz(13, 0.0, 0.0);
|
||||
c.xyz(16, 1.0, 0.0);
|
||||
c.xyz(17, 0.0, 1.0);
|
||||
c.int(76, 1);
|
||||
c.handle(330, record);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_and_text_are_written_plainly() {
|
||||
assert_eq!(num(1.5), "1.5");
|
||||
assert_eq!(num(-0.0000001), "0");
|
||||
assert_eq!(num(2.0), "2");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(text("a^b\nc", true), "a^ b c");
|
||||
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
|
||||
assert_eq!(text("Größe", true), "Größe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
9
|
||||
$DWGCODEPAGE
|
||||
3
|
||||
ANSI_1252
|
||||
9
|
||||
$INSBASE
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMIN
|
||||
10
|
||||
10
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMAX
|
||||
10
|
||||
180
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
9
|
||||
$LIMMIN
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
9
|
||||
$LIMMAX
|
||||
10
|
||||
200
|
||||
20
|
||||
100
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
VPORT
|
||||
70
|
||||
1
|
||||
0
|
||||
VPORT
|
||||
2
|
||||
*ACTIVE
|
||||
70
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
12
|
||||
95
|
||||
22
|
||||
55
|
||||
13
|
||||
0
|
||||
23
|
||||
0
|
||||
14
|
||||
1
|
||||
24
|
||||
1
|
||||
15
|
||||
10
|
||||
25
|
||||
10
|
||||
16
|
||||
0
|
||||
26
|
||||
0
|
||||
36
|
||||
1
|
||||
17
|
||||
0
|
||||
27
|
||||
0
|
||||
37
|
||||
0
|
||||
40
|
||||
124.666667
|
||||
41
|
||||
1.5
|
||||
42
|
||||
50
|
||||
43
|
||||
0
|
||||
44
|
||||
0
|
||||
50
|
||||
0
|
||||
51
|
||||
0
|
||||
71
|
||||
0
|
||||
72
|
||||
1000
|
||||
73
|
||||
1
|
||||
74
|
||||
3
|
||||
75
|
||||
0
|
||||
76
|
||||
0
|
||||
77
|
||||
0
|
||||
78
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
3
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByBlock
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByLayer
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
Continuous
|
||||
70
|
||||
0
|
||||
3
|
||||
Solid line
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LAYER
|
||||
70
|
||||
2
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
0
|
||||
70
|
||||
0
|
||||
62
|
||||
7
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
LAYER_1
|
||||
70
|
||||
0
|
||||
62
|
||||
171
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
STYLE
|
||||
70
|
||||
1
|
||||
0
|
||||
STYLE
|
||||
2
|
||||
Standard
|
||||
70
|
||||
0
|
||||
40
|
||||
0
|
||||
41
|
||||
1
|
||||
50
|
||||
0
|
||||
71
|
||||
0
|
||||
42
|
||||
2.5
|
||||
3
|
||||
txt
|
||||
4
|
||||
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
1
|
||||
41
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
2
|
||||
41
|
||||
2
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
120
|
||||
20
|
||||
50
|
||||
30
|
||||
0
|
||||
42
|
||||
-2.414214
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
150
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
42
|
||||
-0.414214
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
File diff suppressed because it is too large.
Load diff
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
let stop = |&(t, c, o): &(f32, Color, f32)| {
|
||||
let at = if mirrored { 1.0 - t } else { t };
|
||||
format!("{} {}%", css_color(&c, o), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
// Stops that repeat or reflect run that many times across the box. CSS mixes
|
||||
// hex colors evenly in sRGB between two stops
|
||||
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
|
||||
// midpoint and the curve of a Perceptual or hue gradient are written as stops
|
||||
// of their own, each with its color and opacity. A gradient that would need
|
||||
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
|
||||
unrolled.expanded_stops()
|
||||
} else {
|
||||
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
|
||||
};
|
||||
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
|
||||
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
|
||||
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
|
||||
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
|
||||
/// last the end colors hold.
|
||||
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
|
||||
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
|
||||
let stops: Vec<([f64; 3], f64, f64)> = list
|
||||
.split(", ")
|
||||
.map(|stop| {
|
||||
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
|
||||
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
|
||||
let at: f64 = at.trim_end_matches('%').parse().unwrap();
|
||||
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
|
||||
})
|
||||
.collect();
|
||||
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
|
||||
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
|
||||
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
|
||||
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
|
||||
let a = a0 + (a1 - a0) * w;
|
||||
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
|
||||
(c, a)
|
||||
}
|
||||
|
||||
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
|
||||
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
|
||||
/// own, also on a reflected and a mirrored conic swatch.
|
||||
#[test]
|
||||
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
|
||||
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
|
||||
for i in 0..64 {
|
||||
let p = (f64::from(i) + 0.5) / 64.0;
|
||||
let (css, css_alpha) = css_gradient_at(value, p);
|
||||
let (color, opacity) = gp.gradient.sample(at(p) as f32);
|
||||
let want = color.to_rgb();
|
||||
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
|
||||
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
|
||||
}
|
||||
};
|
||||
let ramp = |method| Gradient {
|
||||
method,
|
||||
..Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
|
||||
)
|
||||
};
|
||||
for method in crate::GradientMethod::ALL {
|
||||
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
|
||||
}
|
||||
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
|
||||
let fade = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
|
||||
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
|
||||
],
|
||||
);
|
||||
check("fade", GradientPaint::new(fade), &|p| p);
|
||||
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
|
||||
let spread = reflected.spreader();
|
||||
check("reflect", GradientPaint::new(reflected), &spread);
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
check("mirrored conic", conic, &|p| 1.0 - p);
|
||||
}
|
||||
|
||||
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
|
||||
/// own stops.
|
||||
#[test]
|
||||
fn css_gradient_swatches_keep_their_stop_count_bounded() {
|
||||
let n = 4000;
|
||||
let stops = (0..n)
|
||||
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
|
||||
.collect();
|
||||
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -17,15 +17,19 @@ 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 }
|
||||
+165
-111
@@ -9,10 +9,6 @@
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use zune_jpeg::zune_core::bytestream::ZCursor;
|
||||
use zune_jpeg::zune_core::colorspace::ColorSpace;
|
||||
use zune_jpeg::zune_core::options::DecoderOptions;
|
||||
|
||||
use crate::ImageBlob;
|
||||
|
||||
/// Most pixels a CMYK image is decoded with (256 MB of samples): larger ones decode as RGB.
|
||||
@@ -44,12 +40,7 @@ fn pixels(width: u32, height: u32) -> Option<u64> {
|
||||
/// The number of colour components of JPEG `bytes` (its frame header); `None` when they aren't a
|
||||
/// JPEG.
|
||||
pub fn jpeg_components(bytes: &[u8]) -> Option<usize> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
Some(d.info()?.components as usize)
|
||||
craft_image_codecs::jpeg_inks::jpeg_components(bytes)
|
||||
}
|
||||
|
||||
fn is_tiff(bytes: &[u8]) -> bool {
|
||||
@@ -645,9 +636,7 @@ pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
|
||||
/// `None` without one.
|
||||
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
d.icc_profile().filter(|icc| !icc.is_empty())
|
||||
craft_image_codecs::jpeg_inks::jpeg_icc_profile(bytes)
|
||||
}
|
||||
|
||||
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
|
||||
@@ -664,9 +653,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
|
||||
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
|
||||
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
|
||||
@@ -676,6 +662,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
|
||||
segments.extend_from_slice(chunk);
|
||||
}
|
||||
with_icc_segments(bytes, segments)
|
||||
}
|
||||
|
||||
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
|
||||
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
|
||||
/// segments before the scan can't be read.
|
||||
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
with_icc_segments(bytes, vec![])
|
||||
}
|
||||
|
||||
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
|
||||
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
|
||||
/// their segments before the scan can't be read.
|
||||
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() + segments.len());
|
||||
out.extend_from_slice(&[0xFF, 0xD8]);
|
||||
let mut icc_segments = Some(segments);
|
||||
@@ -837,10 +840,7 @@ impl ImageBlob {
|
||||
pub fn header_size(&self) -> Option<(u32, u32)> {
|
||||
let bytes = self.bytes.as_slice();
|
||||
if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let (w, h) = d.dimensions()?;
|
||||
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
|
||||
return craft_image_codecs::jpeg_inks::jpeg_dimensions(bytes);
|
||||
}
|
||||
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
|
||||
}
|
||||
@@ -918,30 +918,10 @@ fn sample_inks(inks: &Inks, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
|
||||
/// The ink amounts of a four-component JPEG (its samples inverted back; YCCK converted to CMYK
|
||||
/// first, as JPEG readers do).
|
||||
fn jpeg_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let space = d.input_colorspace()?;
|
||||
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = d.dimensions()?;
|
||||
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
|
||||
pixels(w, h)?;
|
||||
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
|
||||
let mut data = d.decode().ok()?;
|
||||
for p in data.as_chunks_mut::<4>().0 {
|
||||
if space == ColorSpace::YCCK {
|
||||
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
|
||||
// libjpeg's YCCK → CMYK: the complement of the YCbCr colour's RGB.
|
||||
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
|
||||
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
|
||||
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
for v in p.iter_mut() {
|
||||
*v = 255 - *v;
|
||||
}
|
||||
}
|
||||
Inks::new(w, h, data)
|
||||
let limits = craft_image_codecs::Limits { max_pixels: MAX_CMYK_PIXELS, ..craft_image_codecs::Limits::default() };
|
||||
let image = craft_image_codecs::jpeg_inks::decode_jpeg_inks(bytes, &limits).ok()?;
|
||||
let (w, h) = image.dimensions();
|
||||
Inks::new(w, h, image.into_data())
|
||||
}
|
||||
|
||||
/// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane
|
||||
@@ -1093,9 +1073,20 @@ pub enum Group3Error {
|
||||
TooLarge { w: u32, h: u32 },
|
||||
/// A strip or tile ends before its last row or can't be decoded (it holds a code the decoder
|
||||
/// doesn't read, such as T.4's uncompressed mode, or a row of the wrong width), or a tile is
|
||||
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA.
|
||||
#[error("could not decode image: {0}")]
|
||||
Damaged(hayro_ccitt::DecodeError),
|
||||
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA, or is wider than
|
||||
/// [`craft_stream_codecs::MAX_CCITT_COLUMNS`].
|
||||
#[error("could not decode image: {}", damage(*.0))]
|
||||
Damaged(craft_stream_codecs::CcittErrorKind),
|
||||
}
|
||||
|
||||
/// What went wrong in a Group 3 strip or tile, as [`Group3Error::Damaged`] says it.
|
||||
fn damage(kind: craft_stream_codecs::CcittErrorKind) -> &'static str {
|
||||
use craft_stream_codecs::CcittErrorKind as K;
|
||||
match kind {
|
||||
K::UnexpectedEof => "unexpected end of input",
|
||||
K::Overflow => "arithmetic overflow in position calculation",
|
||||
K::InvalidData => "invalid CCITT code sequence",
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of a 1-bit TIFF compressed with CCITT Group 3, which the image decoder doesn't read,
|
||||
@@ -1110,7 +1101,7 @@ pub enum Group3Error {
|
||||
/// an error when the pixels would take more than [`crate::MAX_RASTER_ALLOC`] as RGBA, a tile is
|
||||
/// larger than that allowance, or a strip or tile can't be decoded or ends before its last row.
|
||||
pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3Error>> {
|
||||
use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode};
|
||||
use craft_stream_codecs::{CcittErrorKind as DecodeError, CcittParams, decode_ccitt_raw};
|
||||
use tiff::tags::Tag;
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
let compression = d.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten()?;
|
||||
@@ -1129,12 +1120,8 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
|
||||
}
|
||||
let t4_options = d.find_tag_unsigned::<u32>(Tag::Unknown(292)).ok().flatten().unwrap_or(0);
|
||||
let lsb_first = d.find_tag_unsigned::<u16>(Tag::FillOrder).ok().flatten() == Some(2);
|
||||
let encoding = if compression == 3 && t4_options & 1 != 0 {
|
||||
// Each row's tag bit says how it is coded.
|
||||
EncodingMode::Group3_2D { k: 2 }
|
||||
} else {
|
||||
EncodingMode::Group3_1D
|
||||
};
|
||||
// Each row's tag bit says how it is coded (K above 0), or every row is one-dimensional (K 0).
|
||||
let k = if compression == 3 && t4_options & 1 != 0 { 2 } else { 0 };
|
||||
// The width and height of each strip or tile, and the tags of their offsets and byte counts.
|
||||
let tiled = d.get_chunk_type() == tiff::decoder::ChunkType::Tile;
|
||||
let (cw, ch, offsets, counts) = if tiled {
|
||||
@@ -1168,76 +1155,54 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
|
||||
budget -= len;
|
||||
let data = bytes.get(start..start + len)?;
|
||||
let data: std::borrow::Cow<[u8]> = if lsb_first { data.iter().map(|b| b.reverse_bits()).collect() } else { data.into() };
|
||||
let settings = DecodeSettings {
|
||||
columns: cw,
|
||||
// A tile is coded whole; the last strip only has the image's remaining rows.
|
||||
rows: if tiled { ch } else { ch.min(h - y0) },
|
||||
end_of_block: compression == 3,
|
||||
// A tile is coded whole; the last strip only has the image's remaining rows.
|
||||
let rows = if tiled { ch } else { ch.min(h - y0) };
|
||||
let params = CcittParams {
|
||||
k,
|
||||
columns: i64::from(cw),
|
||||
rows: i64::from(rows),
|
||||
end_of_line: compression == 3,
|
||||
rows_are_byte_aligned: compression == 2,
|
||||
encoding,
|
||||
invert_black: false,
|
||||
encoded_byte_align: compression == 2,
|
||||
end_of_block: compression == 3,
|
||||
// 1 bits are black runs, 0 bits white ones.
|
||||
black_is_1: true,
|
||||
};
|
||||
let mut rows = Rows { out: &mut gray, width: w, height: h, x0, y0, x: 0, y: 0, zero };
|
||||
if let Err(e) = hayro_ccitt::decode(&data, &mut rows, &mut DecoderContext::new(settings)) {
|
||||
let Ok(out) = decode_ccitt_raw(&data, ¶ms, rows) else {
|
||||
// Wider than the decoder reads.
|
||||
return damaged(DecodeError::Overflow);
|
||||
};
|
||||
if let Some(e) = out.error {
|
||||
return damaged(e);
|
||||
}
|
||||
// The data ended, or six EOL codes came, before the strip's or tile's last row.
|
||||
if rows.y < settings.rows {
|
||||
if out.rows_decoded < rows {
|
||||
return damaged(DecodeError::UnexpectedEof);
|
||||
}
|
||||
put_rows(&mut gray, (w, h), (x0, y0), cw, &out.data, zero);
|
||||
}
|
||||
let gray = image::GrayImage::from_raw(w, h, gray)?;
|
||||
Some(Ok(image::DynamicImage::ImageLuma8(gray).to_rgba8()))
|
||||
}
|
||||
|
||||
/// Where a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]) puts its decoded pixels: `out`
|
||||
/// holds the image's levels row by row, `width` × `height`, and the strip or tile starts at (`x0`,
|
||||
/// `y0`). Pixels past the image's right or bottom edge (a tile's padding) are dropped.
|
||||
struct Rows<'a> {
|
||||
out: &'a mut [u8],
|
||||
width: u32,
|
||||
height: u32,
|
||||
x0: u32,
|
||||
y0: u32,
|
||||
/// The next pixel in the strip or tile.
|
||||
x: u64,
|
||||
y: u32,
|
||||
/// The level of a white run.
|
||||
zero: u8,
|
||||
}
|
||||
|
||||
impl Rows<'_> {
|
||||
/// The next `n` pixels of the row, a white run's or a black run's.
|
||||
fn run(&mut self, white: bool, n: u64) {
|
||||
let level = if white { self.zero } else { u8::MAX - self.zero };
|
||||
let row = u64::from(self.y0) + u64::from(self.y);
|
||||
let left = u64::from(self.x0) + self.x;
|
||||
let right = left.saturating_add(n).min(u64::from(self.width));
|
||||
if row < u64::from(self.height) && left < right {
|
||||
let at = row * u64::from(self.width);
|
||||
if let (Ok(a), Ok(b)) = (usize::try_from(at + left), usize::try_from(at + right))
|
||||
&& let Some(px) = self.out.get_mut(a..b)
|
||||
{
|
||||
px.fill(level);
|
||||
}
|
||||
/// The decoded rows `packed` of a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]), `columns`
|
||||
/// wide, one bit a pixel (1 a black run's), put into `out`, the image's levels row by row, `size`
|
||||
/// (width, height), from (`x0`, `y0`): a 0 bit as `zero` (the level of a white run), a 1 bit as the
|
||||
/// other level. Pixels past the image's right or bottom edge (a tile's padding) are dropped.
|
||||
fn put_rows(out: &mut [u8], size: (u32, u32), (x0, y0): (u32, u32), columns: u32, packed: &[u8], zero: u8) {
|
||||
let (width, height) = (size.0 as usize, size.1 as usize);
|
||||
let (x0, y0, columns) = (x0 as usize, y0 as usize, columns as usize);
|
||||
let stride = columns.div_ceil(8);
|
||||
if stride == 0 {
|
||||
return;
|
||||
}
|
||||
let across = columns.min(width.saturating_sub(x0));
|
||||
for (y, row) in packed.chunks(stride).enumerate() {
|
||||
let Some(at) = (y0 + y < height).then(|| (y0 + y) * width + x0) else { break };
|
||||
let Some(px) = out.get_mut(at..at + across) else { break };
|
||||
for (x, p) in px.iter_mut().enumerate() {
|
||||
let black = row.get(x / 8).is_some_and(|b| b & (0x80 >> (x % 8)) != 0);
|
||||
*p = if black { u8::MAX - zero } else { zero };
|
||||
}
|
||||
self.x = self.x.saturating_add(n);
|
||||
}
|
||||
}
|
||||
|
||||
impl hayro_ccitt::Decoder for Rows<'_> {
|
||||
fn push_pixel(&mut self, white: bool) {
|
||||
self.run(white, 1);
|
||||
}
|
||||
|
||||
fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
|
||||
self.run(white, u64::from(chunk_count) * 8);
|
||||
}
|
||||
|
||||
fn next_line(&mut self) {
|
||||
self.y = self.y.saturating_add(1);
|
||||
self.x = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2195,4 +2160,93 @@ mod tests {
|
||||
assert_eq!(Inks::new(0, 2, vec![]), None, "empty");
|
||||
assert_eq!(Inks::new(1 << 14, 1 << 13, vec![]), None, "too large");
|
||||
}
|
||||
|
||||
/// The CMYK JPEG reader before craft-image-codecs read the inks (zune-jpeg, every sample
|
||||
/// inverted, libjpeg's truncating YCCK conversion), the reference [`jpeg_inks`] matches.
|
||||
fn zune_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let space = d.input_colorspace()?;
|
||||
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
|
||||
return None;
|
||||
}
|
||||
let (w, h) = d.dimensions()?;
|
||||
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
|
||||
pixels(w, h)?;
|
||||
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
|
||||
let mut data = d.decode().ok()?;
|
||||
for p in data.as_chunks_mut::<4>().0 {
|
||||
if space == ColorSpace::YCCK {
|
||||
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
|
||||
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
|
||||
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
|
||||
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
for v in p.iter_mut() {
|
||||
*v = 255 - *v;
|
||||
}
|
||||
}
|
||||
Inks::new(w, h, data)
|
||||
}
|
||||
|
||||
/// CMYK and YCCK JPEGs of many sizes, samplings and qualities, baseline and progressive, with
|
||||
/// and without Adobe's marker and an ICC profile, read the inks, size, component count and
|
||||
/// profile the zune-jpeg reader read; so do gray and RGB JPEGs (no inks) and cut-off files.
|
||||
/// The frames it panicked on (progressive 4:2:0 CMYK, whose C, M and Y `jpeg-encoder` writes at
|
||||
/// 1×1 and K at 2×2) read as no inks.
|
||||
#[test]
|
||||
fn cmyk_jpegs_read_as_the_zune_reader_read_them() {
|
||||
use jpeg_encoder::{ColorType, Encoder, SamplingFactor};
|
||||
let reference_size = |bytes: &[u8]| {
|
||||
use zune_jpeg::zune_core::{bytestream::ZCursor, options::DecoderOptions};
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let (w, h) = d.dimensions()?;
|
||||
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?, usize::from(d.info()?.components), d.icc_profile().filter(|i| !i.is_empty())))
|
||||
};
|
||||
let (mut files, mut read, mut panicked) = (0, 0, 0);
|
||||
for (i, (w, h)) in [(1u16, 1u16), (7, 3), (16, 16), (33, 31), (100, 77)].into_iter().enumerate() {
|
||||
let n = usize::from(w) * usize::from(h);
|
||||
let px: Vec<u8> = (0..n * 4).map(|k| ((k * 2_654_435_761 + i * 97) >> 7) as u8).collect();
|
||||
for ty in [ColorType::Cmyk, ColorType::CmykAsYcck, ColorType::Rgba, ColorType::Luma] {
|
||||
for (q, sampling, progressive, icc) in [
|
||||
(100, SamplingFactor::R_4_4_4, false, false),
|
||||
(70, SamplingFactor::R_4_2_0, true, true),
|
||||
(40, SamplingFactor::R_4_2_2, false, false),
|
||||
] {
|
||||
let mut out = Vec::new();
|
||||
let mut e = Encoder::new(&mut out, q);
|
||||
e.set_sampling_factor(sampling);
|
||||
e.set_progressive(progressive);
|
||||
if icc {
|
||||
let mut icc = vec![4; 70_000];
|
||||
icc[16..20].copy_from_slice(b"CMYK");
|
||||
e.add_icc_profile(&icc).unwrap();
|
||||
}
|
||||
let samples = if ty == ColorType::Luma { &px[..n] } else { &px[..] };
|
||||
e.encode(samples, w, h, ty).unwrap();
|
||||
let cut = out[..out.len() * 2 / 3].to_vec();
|
||||
for file in [out, cut] {
|
||||
let b = ImageBlob::new("image/jpeg", file.clone());
|
||||
// The zune-jpeg reader panicked on some subsampled CMYK frames; those
|
||||
// read as no inks now.
|
||||
let inks = std::panic::catch_unwind(|| zune_inks(&file)).unwrap_or_else(|_| {
|
||||
panicked += 1;
|
||||
None
|
||||
});
|
||||
read += usize::from(inks.is_some());
|
||||
assert_eq!(b.cmyk(), inks, "{w}x{h} {ty:?} q{q}");
|
||||
let r = reference_size(&file);
|
||||
assert_eq!(b.header_size(), r.as_ref().map(|r| (r.0, r.1)));
|
||||
assert_eq!(jpeg_components(&file), r.as_ref().map(|r| r.2));
|
||||
assert_eq!(jpeg_icc(&file), r.and_then(|r| r.3));
|
||||
files += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(files, 5 * 4 * 3 * 2);
|
||||
assert!(read > 20 && panicked > 0, "{read} read as inks, {panicked} panicked");
|
||||
}
|
||||
}
|
||||
@@ -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 }))
|
||||
}
|
||||
@@ -752,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> =
|
||||
@@ -770,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.
|
||||
|
||||
+32
-1
@@ -140,7 +140,7 @@ impl crate::Document {
|
||||
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
|
||||
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
|
||||
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
|
||||
/// label's alignment.
|
||||
/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct LabelStyles {
|
||||
@@ -180,6 +180,14 @@ 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 {
|
||||
@@ -483,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")]
|
||||
@@ -557,6 +569,24 @@ 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
|
||||
@@ -696,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,
|
||||
|
||||
+596
-81
@@ -239,6 +239,190 @@ thread_local! {
|
||||
static LIVE_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The art an object draws in Preview with the geometry effects in it applied, at every depth, as
|
||||
/// plain art whose objects keep the ids of the objects they are drawn from: `None` when no geometry
|
||||
/// effect in it changes what it draws. Effects are evaluated above this crate, so the engine
|
||||
/// registers one with [`set_drawn_art`].
|
||||
pub type DrawnArt = fn(&SymbolBoxes<'_>, &Node) -> Option<Node>;
|
||||
|
||||
static DRAWN_ART: OnceLock<DrawnArt> = OnceLock::new();
|
||||
|
||||
/// Register how the art an object draws with its geometry effects is found, for clicks and
|
||||
/// marquees (the first registration stays).
|
||||
pub fn set_drawn_art(f: DrawnArt) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = DRAWN_ART.set(f);
|
||||
}
|
||||
|
||||
/// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and
|
||||
/// the box round everything that art can paint.
|
||||
struct EvaluatedDrawn {
|
||||
of: EvaluatedLive,
|
||||
reach: Option<Rect>,
|
||||
}
|
||||
|
||||
/// How many objects' drawn art [`drawn`] keeps on each thread. Every pointer move measures every
|
||||
/// object with effects that it passes, so the art of all of a document's objects with effects is
|
||||
/// kept, within [`LIVE_KEPT_SIZE`], not only the latest few as with live objects.
|
||||
const DRAWN_KEPT: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The drawn art [`drawn`] keeps, by object, and the sum of their sizes.
|
||||
static DRAWN: RefCell<(HashMap<NodeId, EvaluatedDrawn>, usize)> = RefCell::new((HashMap::new(), 0));
|
||||
/// Whether [`drawn`] gives no art: set while art it gave is tested ([`DrawnOff`]).
|
||||
static DRAWN_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many objects' drawn art [`drawn`] evaluated on this thread.
|
||||
static DRAWN_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While a guard lives, [`drawn`] gives no art: the art it gave already has every geometry effect
|
||||
/// in it applied, and is tested as it is.
|
||||
struct DrawnOff {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl DrawnOff {
|
||||
fn set() -> Self {
|
||||
Self { was: DRAWN_OFF.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DrawnOff {
|
||||
fn drop(&mut self) {
|
||||
DRAWN_OFF.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
f()
|
||||
}
|
||||
|
||||
/// The art object `n` draws with the geometry effects in it applied ([`set_drawn_art`]), empty when
|
||||
/// none changes what it draws, and the box round everything that art can paint. `None` while
|
||||
/// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated
|
||||
/// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a
|
||||
/// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the
|
||||
/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and
|
||||
/// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new
|
||||
/// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is
|
||||
/// kept alone.
|
||||
fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect>)> {
|
||||
let f = DRAWN_ART.get()?;
|
||||
if DRAWN_OFF.get() || !evaluates(n) || !(has_own_effects(n) || draws_effects(symbols, n)) {
|
||||
return None;
|
||||
}
|
||||
let doc = symbols.document();
|
||||
let inputs = live_inputs();
|
||||
let kept = DRAWN.with_borrow(|(kept, _)| kept.get(&n.id).filter(|e| e.of.is_of(doc, n, inputs)).map(|e| (e.of.art.clone(), e.reach)));
|
||||
if kept.is_some() {
|
||||
return kept;
|
||||
}
|
||||
#[cfg(test)]
|
||||
DRAWN_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let art = f(symbols, n);
|
||||
let reach = art.as_ref().and_then(|a| a.reach_bounds_with(symbols));
|
||||
let art = Rc::new(art.into_iter().collect::<Vec<_>>());
|
||||
let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n)));
|
||||
if !holds_placed(doc, n) {
|
||||
let of = EvaluatedLive {
|
||||
node: n.clone(),
|
||||
symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(),
|
||||
patterns: doc.patterns.clone(),
|
||||
swatches: doc.swatches.clone(),
|
||||
swatch_groups: doc.swatch_groups.clone(),
|
||||
inputs,
|
||||
art: art.clone(),
|
||||
size,
|
||||
};
|
||||
DRAWN.with_borrow_mut(|(kept, total)| {
|
||||
if let Some(old) = kept.remove(&n.id) {
|
||||
*total = total.saturating_sub(old.of.size);
|
||||
}
|
||||
while kept.len() >= DRAWN_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
|
||||
let Some(other) = kept.keys().next().copied() else { break };
|
||||
if let Some(old) = kept.remove(&other) {
|
||||
*total = total.saturating_sub(old.of.size);
|
||||
}
|
||||
}
|
||||
kept.insert(n.id, EvaluatedDrawn { of, reach });
|
||||
*total = total.saturating_add(size);
|
||||
});
|
||||
}
|
||||
Some((art, reach))
|
||||
}
|
||||
|
||||
/// Is `n` an object whose art [`drawn`] evaluates: a path or compound path, or a group or layer with
|
||||
/// geometry effects or fills and strokes of its own, which paint its members as their effects draw
|
||||
/// them?
|
||||
fn evaluates(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide, .. } => !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => has_own_effects(n) || !n.appearance.items.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The art path or compound path `n` draws with its geometry effects ([`drawn`]) in Preview, or
|
||||
/// group or layer `n` with geometry effects or fills and strokes of its own: `None` in outline
|
||||
/// (`outline`, where the canvas draws no effects), for other objects, and when no geometry effect
|
||||
/// changes what it draws. Also `None` for a clip group or layer whose art holds only its clipping
|
||||
/// path and that path's strokes, not the art it clips: its members are then tested one by one.
|
||||
fn drawn_art(symbols: &SymbolBoxes, n: &Node, outline: bool) -> Option<Rc<Vec<Node>>> {
|
||||
if outline {
|
||||
return None;
|
||||
}
|
||||
drawn(symbols, n).map(|(art, _)| art).filter(|art| !art.is_empty() && (!n.clips() || holds_clipped_art(n, art)))
|
||||
}
|
||||
|
||||
/// Does `art`, the drawn art of clip group or layer `n`, hold any of the objects `n` clips (its
|
||||
/// members after the clipping path), or does `n` clip none?
|
||||
fn holds_clipped_art(n: &Node, art: &[Node]) -> bool {
|
||||
let clipped: HashSet<NodeId> = n.children().into_iter().flatten().skip(1).map(|c| c.id).collect();
|
||||
if clipped.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let mut found = false;
|
||||
for a in art {
|
||||
a.walk(&mut |c| found |= clipped.contains(&c.id));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `base`, a box round what `n` paints without its geometry effects, grown to hold the art they
|
||||
/// draw ([`effects_reach`]). `None` when `base` is.
|
||||
fn drawn_reach(symbols: &SymbolBoxes, n: &Node, base: Option<Rect>) -> Option<Rect> {
|
||||
let base = base?;
|
||||
Some(effects_reach(symbols, n).map_or(base, |r| base.union(r)))
|
||||
}
|
||||
|
||||
/// The box round the art that the geometry effects in `n` draw: that of its own art ([`drawn`])
|
||||
/// when it is evaluated ([`evaluates`]), else the union of its members' in a group, layer or
|
||||
/// Intertwine group. `None` when
|
||||
/// no geometry effect changes what it draws, and while a [`DrawnOff`] guard lives.
|
||||
fn effects_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
if DRAWN_OFF.get() {
|
||||
return None;
|
||||
}
|
||||
if evaluates(n) {
|
||||
return drawn(symbols, n).filter(|(art, _)| !art.is_empty()).and_then(|(_, reach)| reach);
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
|
||||
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, effects_reach(symbols, c)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Topmost editable object under `p`.
|
||||
pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> {
|
||||
hit_test_skipping(doc, p, opt, &|_| false, true)
|
||||
@@ -267,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
|
||||
/// outline, as a click there hits it.
|
||||
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
selected.iter().rev().copied().find(|&id| {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect();
|
||||
@@ -323,38 +508,36 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
|
||||
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
|
||||
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
|
||||
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let walk = ArtWalk::open();
|
||||
let _walk = ArtWalk::open();
|
||||
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
|
||||
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
|
||||
// while a group (including a clipping group) is selected as one object. Repeatedly
|
||||
// searching the full tree for each hit made a stack of n overlapping paths O(n^2).
|
||||
// Isolation and Edit Contents change where selection groups begin; keep the original
|
||||
// traversal for those cases rather than change their Select Behind semantics.
|
||||
if opt.scope.is_some() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) {
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
let mut tops = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let symbols = doc.symbol_boxes();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
// Malformed files may contain non-layer roots; let the general traversal handle them.
|
||||
if !layer.is_layer() {
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
}
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely, with the whole
|
||||
// limit of symbol art to walk.
|
||||
walk.restart();
|
||||
return objects_at_repeated(doc, p, opt, scope);
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
let locks = doc.locked_artboards();
|
||||
if !locks.is_empty() {
|
||||
tops.retain(|id| !doc.node(*id).is_some_and(|n| locks.holds(n)));
|
||||
}
|
||||
@@ -368,6 +551,11 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
|
||||
let Some(children) = layer.children() else { return true };
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
// A layer whose own geometry effects reshape its art is hit where that art is drawn, which the
|
||||
// general traversal finds ([`hit_children`]).
|
||||
if drawn_art(symbols, layer, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
if layer.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -400,11 +588,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
}
|
||||
let skip = |id| seen.contains(&id);
|
||||
let mut chain = Vec::new();
|
||||
let hit = match &c.kind {
|
||||
let hit = plain(i == 0 && layer.clips(), || match &c.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Intertwine { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some(),
|
||||
NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, &skip, &mut chain, true).is_some() || hit_leaf(c, p, opt, symbols).is_some(),
|
||||
_ => hit_leaf(c, p, opt, symbols).is_some(),
|
||||
};
|
||||
});
|
||||
if hit && seen.insert(c.id) {
|
||||
tops.push(c.id);
|
||||
}
|
||||
@@ -414,7 +602,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
|
||||
/// The general selection order also handles isolation and nested Edit Contents.
|
||||
fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let mut tops: Vec<NodeId> = vec![];
|
||||
objects_at_repeated_after(doc, p, opt, scope, vec![])
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
|
||||
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
// Each round leaves out the objects found so far (and everything inside them).
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
|
||||
if tops.contains(&top) {
|
||||
@@ -435,7 +627,7 @@ pub const MAX_LOCKED_AT: usize = 20;
|
||||
/// (`opt.scope`) only what is inside the isolated group or object.
|
||||
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let symbols = doc.symbol_boxes();
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut out = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
@@ -461,6 +653,23 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
// A group or layer whose own geometry effects reshape what it holds: the locked objects drawn
|
||||
// under `p` ([`drawn_hit`]).
|
||||
if !(parent.clips() && edits_inside(parent, opt.scope))
|
||||
&& let Some(art) = drawn_art(symbols, parent, opt.outline)
|
||||
{
|
||||
let _off = DrawnOff::set();
|
||||
let mut list = |id: NodeId, _: HitKind| {
|
||||
if let Some(locked) = locked_member(parent, id, opt)
|
||||
&& !out.contains(&locked)
|
||||
{
|
||||
out.push(locked);
|
||||
}
|
||||
out.len() >= MAX_LOCKED_AT
|
||||
};
|
||||
art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut list));
|
||||
return;
|
||||
}
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
|
||||
return;
|
||||
}
|
||||
@@ -473,7 +682,7 @@ fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
continue;
|
||||
}
|
||||
if c.locked {
|
||||
if locked_hit(c, p, opt, symbols) {
|
||||
if plain(i == 0 && parent.clips(), || locked_hit(c, p, opt, symbols)) {
|
||||
out.push(c.id);
|
||||
}
|
||||
continue;
|
||||
@@ -518,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards();
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
editable_only
|
||||
&& !locks.is_empty()
|
||||
@@ -526,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No
|
||||
&& doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let skip = &|id| skip(id) || on_locked(id);
|
||||
let symbols = doc.symbol_boxes();
|
||||
// `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// Isolation mode: only what is inside the isolated container hits. The art around it is
|
||||
// locked, and clicks pass through it (#833).
|
||||
if editable_only
|
||||
@@ -594,17 +804,36 @@ pub fn set_clip_region(f: ClipRegion) {
|
||||
let _ = CLIP_REGION.set(f);
|
||||
}
|
||||
|
||||
/// What the regions of clipping paths with live effects depend on outside the document: the
|
||||
/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered.
|
||||
pub(crate) fn clip_region_inputs() -> (u64, bool) {
|
||||
(live_inputs(), CLIP_REGION.get().is_some())
|
||||
}
|
||||
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
|
||||
clip.walk(&mut |n| found |= has_own_effects(n));
|
||||
found
|
||||
}
|
||||
|
||||
/// Does `n`, anything it holds, or the art of a symbol an instance in it shows have a visible
|
||||
/// effect? Only then can the registered [`DrawnArt`] find a geometry effect in it.
|
||||
fn draws_effects(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found || has_own_effects(c) || matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.has_effects(symbol));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Does `n` itself have a visible effect, of its own or on one of its own fills or strokes?
|
||||
fn has_own_effects(n: &Node) -> bool {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible))
|
||||
}
|
||||
|
||||
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
|
||||
/// path elements.
|
||||
@@ -747,15 +976,7 @@ pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_
|
||||
/// hidden, when it can't be edited (`editable_only`), when it is the part of a Shaper group that
|
||||
/// isn't shown, or when `p` is outside its reach.
|
||||
fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editable_only: bool) -> bool {
|
||||
if shaper_hides(parent, i, opt.scope) {
|
||||
return false;
|
||||
}
|
||||
// Read-only samples can read locked/template art; hidden art never participates.
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
// A ruler guide is picked by the guide commands, never by an object hit test.
|
||||
if c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
if !may_reach(parent, i, c, opt, editable_only) {
|
||||
return false;
|
||||
}
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
@@ -764,11 +985,28 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols
|
||||
|| cull_reach(c, symbols).is_none_or(|b| b.inflate(opt.tol, opt.tol).contains(p))
|
||||
}
|
||||
|
||||
/// Can a click hit `c`, the child `i` of `parent`, or something inside it, wherever it is? Not
|
||||
/// when it is hidden, when it can't be edited (`editable_only`), when it is a ruler guide or a
|
||||
/// guide while guides are locked or hidden, or when it is the part of a Shaper group that isn't
|
||||
/// shown.
|
||||
fn may_reach(parent: &Node, i: usize, c: &Node, opt: HitOptions, editable_only: bool) -> bool {
|
||||
if shaper_hides(parent, i, opt.scope) {
|
||||
return false;
|
||||
}
|
||||
// Read-only samples can read locked/template art; hidden art never participates.
|
||||
if !c.visible || editable_only && (c.locked || c.is_template()) {
|
||||
return false;
|
||||
}
|
||||
// A ruler guide is picked by the guide commands, never by an object hit test.
|
||||
!(c.is_ruler_guide() || opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }))
|
||||
}
|
||||
|
||||
/// A box round everything `c` can paint, for culling clicks: [`Node::reach_bounds_with`], except
|
||||
/// that paths and compound paths are measured by their control points ([`PathData::control_bounds`],
|
||||
/// which hold the curves) instead of along their curves, which a compound path of thousands of
|
||||
/// members takes milliseconds to do on every click and hover. The box only rules points out, and it
|
||||
/// is at least as large, so the same objects are hit.
|
||||
/// is at least as large, so the same objects are hit. It also holds the art that the geometry
|
||||
/// effects in `c` draw ([`drawn_reach`]), wherever they move it.
|
||||
///
|
||||
/// [`PathData::control_bounds`]: vectorcraft_geom::PathData::control_bounds
|
||||
fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
@@ -777,10 +1015,10 @@ fn cull_reach(c: &Node, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
NodeKind::Compound { children, .. } if children.iter().all(|m| m.path_data().is_some()) => {
|
||||
children.iter().filter_map(|m| m.path_data().and_then(vectorcraft_geom::PathData::control_bounds)).reduce(|a, b| a.union(b))
|
||||
}
|
||||
_ => return c.reach_bounds_with(symbols),
|
||||
_ => return drawn_reach(symbols, c, c.reach_bounds_with(symbols)),
|
||||
};
|
||||
let o = c.appearance.outset();
|
||||
control.map(|b| b.inflate(o, o))
|
||||
drawn_reach(symbols, c, control.map(|b| b.inflate(o, o)))
|
||||
}
|
||||
|
||||
/// The members of compound path `children` that a click at `p` within `tol` can touch, as one
|
||||
@@ -854,19 +1092,36 @@ fn hit_children(
|
||||
editable_only: bool,
|
||||
) -> Option<Hit> {
|
||||
let children = parent.children()?;
|
||||
if parent.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
if let Some(kind) = clip_outline_hit(parent, clip, p, opt, symbols, editable_only).filter(|_| !skip(clip.id)) {
|
||||
let clip = children.first().filter(|_| parent.clips());
|
||||
// The selection tools in isolation mode within a clip group (or a layer with a clipping mask)
|
||||
// hit what it holds outside its clipping mask too.
|
||||
let edited = clip.is_some() && opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
// A group or layer whose own geometry effects reshape what it holds hits where that art is drawn.
|
||||
let art = if edited { None } else { drawn_art(symbols, parent, opt.outline) };
|
||||
if let Some(clip) = clip {
|
||||
// The clipping mask's outline first, where it is drawn.
|
||||
let drawn_clip = art.as_deref().and_then(|a| a.first()).filter(|a| a.clips()).and_then(|a| a.children()?.first());
|
||||
let kind = match drawn_clip {
|
||||
Some(drawn) => {
|
||||
let takes = opt.clip_outlines && editable_only && may_reach(parent, 0, clip, opt, editable_only);
|
||||
takes.then(|| clip_outline(drawn, p, opt)).flatten()
|
||||
}
|
||||
None => clip_outline_hit(parent, clip, p, opt, symbols, editable_only),
|
||||
};
|
||||
if let Some(kind) = kind.filter(|_| !skip(clip.id)) {
|
||||
chain.push(clip.id);
|
||||
return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p, opt.outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if let Some(art) = art {
|
||||
return drawn_hit(parent, &art, p, opt, symbols, skip, chain, editable_only);
|
||||
}
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it.
|
||||
if let Some(clip) = clip
|
||||
&& !edited
|
||||
&& !clip_contains(clip, p, opt.outline)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
@@ -874,7 +1129,7 @@ fn hit_children(
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let hit = match &c.kind {
|
||||
let hit = plain(i == 0 && clip.is_some(), || match &c.kind {
|
||||
// A sublayer whose Preview is off is clicked in outline, like an outline view.
|
||||
NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only),
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => {
|
||||
@@ -887,7 +1142,7 @@ fn hit_children(
|
||||
NodeKind::Blend { .. } => hit_children(c, p, opt, symbols, skip, chain, editable_only)
|
||||
.or_else(|| hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })),
|
||||
_ => hit_leaf(c, p, opt, symbols).map(|kind| Hit { leaf: c.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 }),
|
||||
};
|
||||
});
|
||||
if hit.is_some() {
|
||||
return hit;
|
||||
}
|
||||
@@ -896,6 +1151,123 @@ fn hit_children(
|
||||
None
|
||||
}
|
||||
|
||||
/// What a click at `p` hits in `art`, the art that group or layer `parent` draws with its own
|
||||
/// geometry effects ([`drawn_art`]): the member of `parent` that the topmost object of the art hit
|
||||
/// there is drawn from, found by its id, at the depth [`hit_children`] gives it, or `parent` itself,
|
||||
/// when it is not a layer, for art of its own (its own fills and strokes). Where that member can't be hit (hidden, locked,
|
||||
/// skipped, a guide, a Shaper group's part that isn't shown), the click goes on to the art below.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn drawn_hit(
|
||||
parent: &Node,
|
||||
art: &[Node],
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
editable_only: bool,
|
||||
) -> Option<Hit> {
|
||||
let _off = DrawnOff::set();
|
||||
let mut found = None;
|
||||
let mut accept = |id: NodeId, kind: HitKind| {
|
||||
found = member_chain(parent, id, opt, skip, editable_only).map(|path| (path, kind));
|
||||
found.is_some()
|
||||
};
|
||||
if !art.iter().rev().any(|a| art_hit(a, p, opt, symbols, &mut accept)) {
|
||||
return None;
|
||||
}
|
||||
let (path, kind) = found?;
|
||||
let leaf = path.last().copied().unwrap_or(parent.id);
|
||||
chain.extend(path);
|
||||
Some(Hit { leaf, ancestry: chain.clone(), kind, contents_of: None, layers: 1 })
|
||||
}
|
||||
|
||||
/// The ids from a child of `parent` down to its member `id`, when a click may hit each of them
|
||||
/// ([`may_reach`], and not passed over by `skip`); empty when `id` is `parent` itself, `parent` is
|
||||
/// not a layer and `skip` does not pass over it. `None` otherwise, and when `id` is not in `parent`.
|
||||
fn member_chain(parent: &Node, id: NodeId, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Vec<NodeId>> {
|
||||
// A layer's own fills and strokes are not an object to select.
|
||||
if id == parent.id {
|
||||
return (!skip(id) && !parent.is_layer()).then(Vec::new);
|
||||
}
|
||||
let mut steps = vec![];
|
||||
if !path_to(parent, id, &mut steps) {
|
||||
return None;
|
||||
}
|
||||
let reachable = steps.iter().all(|(n, i, c)| may_reach(n, *i, c, opt, editable_only) && !skip(c.id));
|
||||
reachable.then(|| steps.iter().map(|(_, _, c)| c.id).collect())
|
||||
}
|
||||
|
||||
/// Each container from `n` down to its member `id`, with the index and the child it holds on the
|
||||
/// way, into `path`. `false` when `id` is not in `n`.
|
||||
fn path_to<'a>(n: &'a Node, id: NodeId, path: &mut Vec<(&'a Node, usize, &'a Node)>) -> bool {
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
path.push((n, i, c));
|
||||
if c.id == id || path_to(c, id, path) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The locked object [`locked_objects_at`] lists for member `id` of `parent`: the outermost object
|
||||
/// with its own lock on, from a child of `parent` down to `id`, when a click may reach each of them
|
||||
/// ([`may_reach`] with locked objects counted) and none is a locked or template layer, as
|
||||
/// [`locked_children`] goes down. `None` otherwise.
|
||||
fn locked_member(parent: &Node, id: NodeId, opt: HitOptions) -> Option<NodeId> {
|
||||
let mut steps = vec![];
|
||||
if !path_to(parent, id, &mut steps) {
|
||||
return None;
|
||||
}
|
||||
for (n, i, c) in steps {
|
||||
if !may_reach(n, i, c, opt, false) || c.is_layer() && (c.locked || c.is_template()) {
|
||||
return None;
|
||||
}
|
||||
if c.locked {
|
||||
return Some(c.id);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Does a click at `p` hit an object of `art` (the art [`drawn_art`] gives) that `accept` takes? The
|
||||
/// objects are tried front first, the members of an Intertwine group in the order they are drawn at
|
||||
/// `p` ([`hit_order`]), and `accept` is given the id and the hit kind of each object hit until it
|
||||
/// takes one.
|
||||
fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &mut dyn FnMut(NodeId, HitKind) -> bool) -> bool {
|
||||
if !n.visible {
|
||||
return false;
|
||||
}
|
||||
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return false;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => {
|
||||
// A layer with Preview off is clicked in outline, as [`hit_children`] clicks it.
|
||||
let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt };
|
||||
if n.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
// The selection tools take a clipping path on its outline before the art it clips,
|
||||
// as [`hit_children`] does.
|
||||
if opt.clip_outlines
|
||||
&& clip.visible
|
||||
&& let Some(kind) = clip_outline(clip, p, opt)
|
||||
&& accept(clip.id, kind)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(clip, p, opt.outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The order a click at `p` tries the children of `parent` in, front first: their stacking order
|
||||
/// from the top, except that in an Intertwine group the members are tried in the order they are
|
||||
/// drawn at `p`, from the top ([`crate::intertwine::tier_at`]).
|
||||
@@ -964,10 +1336,17 @@ thread_local! {
|
||||
/// What a click at `p` hits on leaf object `n`: its outline, strokes and fills, its frame or its
|
||||
/// bounds, by kind. Raster effects (drop shadows, glows, blurs) do not take clicks: the area they
|
||||
/// paint beyond the object is left out here and in [`cull_reach`], so a click there reaches the
|
||||
/// object under it.
|
||||
/// object under it. Except in outline, a path or compound path with geometry effects is hit by the
|
||||
/// art they draw ([`drawn_art`]), its own geometry only where that art lies.
|
||||
fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
#[cfg(test)]
|
||||
LEAVES_TESTED.with(|c| c.set(c.get() + 1));
|
||||
// A path or compound path whose geometry effects reshape it is hit where its art is drawn, and
|
||||
// not where its own geometry no longer paints.
|
||||
if let Some(art) = drawn_art(symbols, n, opt.outline) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
if opt.outline
|
||||
@@ -1121,24 +1500,36 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art
|
||||
/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and
|
||||
/// nothing more is tested once the limit is used up.
|
||||
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
// Hidden art does not hit.
|
||||
if !n.visible {
|
||||
if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
// passed by without being measured.
|
||||
if !edits_contents(n) && n.extras().shaper.is_none() && n.reach_bounds_with(symbols).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
if !edits_contents(n)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& drawn_reach(symbols, n, n.reach_bounds_with(symbols)).is_some_and(|b| !b.inflate(opt.tol, opt.tol).contains(p))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A group whose own geometry effects reshape its members hits where that art is drawn.
|
||||
if matches!(n.kind, NodeKind::Group { .. })
|
||||
&& let Some(art) = drawn_art(symbols, n, opt.outline)
|
||||
{
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().rev().find_map(|a| hit_any(a, p, opt, symbols));
|
||||
}
|
||||
match &n.kind {
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
children.iter().enumerate().rev().find_map(|(i, c)| plain(i == 0 && *clip, || hit_any(c, p, opt, symbols)))
|
||||
}
|
||||
// An intertwine group hits by its members, as on the canvas.
|
||||
NodeKind::Intertwine { children } => children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)),
|
||||
@@ -1238,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
|
||||
@@ -1257,8 +1648,12 @@ struct FindPart<'a> {
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit.
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols))
|
||||
let placed = self.art.place(n, whole)?;
|
||||
let _charged = ArtWalk::charge();
|
||||
hit_any(&placed, self.p, opt, self.symbols)
|
||||
}
|
||||
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
@@ -1268,7 +1663,7 @@ impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
|
||||
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
@@ -1277,6 +1672,9 @@ impl FindPart<'_> {
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
if !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
@@ -1303,7 +1701,7 @@ impl FindPart<'_> {
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if let Some(kind) = self.find(c, path, whole, outline) {
|
||||
if let Some(kind) = plain(i == 0 && n.clips(), || self.find(c, path, whole, outline)) {
|
||||
return Some(kind);
|
||||
}
|
||||
path.pop();
|
||||
@@ -1370,6 +1768,8 @@ thread_local! {
|
||||
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
|
||||
/// `None` outside one.
|
||||
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]).
|
||||
static ART_WALK_CHARGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1420,6 +1820,19 @@ impl ArtWalk {
|
||||
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
|
||||
rest.is_some()
|
||||
}
|
||||
|
||||
/// While the guard lives, each object [`hit_any`] visits takes one object from what is left:
|
||||
/// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an
|
||||
/// Intertwine group, and the objects of groups nested deeper than
|
||||
/// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit.
|
||||
fn charge() -> ArtWalkCharge {
|
||||
ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) }
|
||||
}
|
||||
|
||||
/// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])?
|
||||
fn charged() -> bool {
|
||||
ART_WALK_CHARGED.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtWalk {
|
||||
@@ -1430,6 +1843,17 @@ impl Drop for ArtWalk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard of [`ArtWalk::charge`].
|
||||
struct ArtWalkCharge {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl Drop for ArtWalkCharge {
|
||||
fn drop(&mut self) {
|
||||
ART_WALK_CHARGED.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
@@ -1599,7 +2023,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
/// the selection tools' clicks.
|
||||
/// the selection tools' clicks. Except in outline, a path or compound path with geometry effects, and
|
||||
/// the members of a group or layer with geometry effects of its own, are touched where the art those
|
||||
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
}
|
||||
@@ -1625,25 +2051,32 @@ fn previews_off(n: &Node) -> bool {
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let mut out = Vec::new();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None))
|
||||
.collect(),
|
||||
Some(c) => {
|
||||
// In an isolated clip group, its members by their own geometry, as clicks take
|
||||
// them ([`edits_inside`]).
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None, drawn.clone()))
|
||||
.collect()
|
||||
}
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None, None)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
@@ -1652,36 +2085,80 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, r, outline))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
|
||||
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
|
||||
/// shapes ([`mask_marquee`]).
|
||||
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
|
||||
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
|
||||
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
|
||||
/// `l` has such effects.
|
||||
fn layer_objects<'a>(
|
||||
l: &'a Node,
|
||||
s: &SymbolBoxes,
|
||||
r: Rect,
|
||||
outline: bool,
|
||||
whole_compounds: bool,
|
||||
drawn: Option<Rc<HashSet<NodeId>>>,
|
||||
) -> Vec<Top<'a>> {
|
||||
let mut out = vec![];
|
||||
let outline = outline || previews_off(l);
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
if let Some(inner) = inner
|
||||
if let Some(inner) = if drawn.is_some() { Some(r) } else { inner }
|
||||
&& c.visible
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, inner, outline));
|
||||
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r)));
|
||||
if drawn.is_some() {
|
||||
out.push((c, Some(r), outline, None, drawn.clone()));
|
||||
} else if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r), None));
|
||||
} else if inner.is_some() {
|
||||
out.push((c, inner, outline, None));
|
||||
out.push((c, inner, outline, None, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
|
||||
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
|
||||
/// `None` in outline and when it has no such effects.
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
let art = drawn_art(s, n, outline)?;
|
||||
let _off = DrawnOff::set();
|
||||
let mut ids = vec![];
|
||||
for a in art.iter().filter(|a| a.visible) {
|
||||
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
|
||||
}
|
||||
Some(Rc::new(ids.into_iter().collect()))
|
||||
}
|
||||
/// The objects inside `n` that a marquee collects ([`collect_leaves`]) whose ids are in
|
||||
/// `drawn` ([`touched_in_art`]), into `out`: leaves, and groups whose own fills and strokes
|
||||
/// the art paints there.
|
||||
fn collect_drawn(n: &Node, drawn: &HashSet<NodeId>, scope: Option<NodeId>, out: &mut Vec<NodeId>) {
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
continue;
|
||||
}
|
||||
if is_leaf(c) {
|
||||
if drawn.contains(&c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else {
|
||||
if drawn.contains(&c.id) && !c.is_layer() {
|
||||
out.push(c.id);
|
||||
}
|
||||
collect_drawn(c, drawn, scope, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
|
||||
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
|
||||
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
|
||||
@@ -1714,6 +2191,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
@@ -1723,7 +2206,8 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
|
||||
|| clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
}
|
||||
@@ -1777,6 +2261,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let outline = outline || previews_off(n);
|
||||
// The members that the art its own geometry effects draw touches, and a group whose
|
||||
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
|
||||
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
|
||||
if drawn.contains(&n.id) && !n.is_layer() {
|
||||
out.push(n.id);
|
||||
}
|
||||
collect_drawn(n, &drawn, scope, out);
|
||||
return;
|
||||
}
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
@@ -1785,7 +2278,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
@@ -1802,12 +2295,32 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r, outline, edge) in tops {
|
||||
for (t, r, outline, edge, drawn) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
}
|
||||
// In a layer or isolated container whose own geometry effects reshape its art: by what
|
||||
// that art touches.
|
||||
if let Some(drawn) = drawn {
|
||||
if !leaves {
|
||||
let mut touched = false;
|
||||
t.walk(&mut |n| touched |= drawn.contains(&n.id));
|
||||
if touched {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else {
|
||||
// A leaf, or a group whose own fills and strokes the art paints, and its members.
|
||||
if drawn.contains(&t.id) && !t.is_layer() {
|
||||
out.push(t.id);
|
||||
}
|
||||
if !is_leaf(t) {
|
||||
collect_drawn(t, &drawn, scope, &mut out);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A layer's clipping mask counts by its own geometry ([`plain`]).
|
||||
let _mask = edge.is_some().then(DrawnOff::set);
|
||||
if leaves {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
@@ -1827,8 +2340,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
|
||||
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
|
||||
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`), and in a layer or an
|
||||
/// isolated container whose own geometry effects reshape its art, the ids of the objects of that art
|
||||
/// the marquee touches (`touched_in_art`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>, Option<Rc<HashSet<NodeId>>>);
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
|
||||
|
||||
@@ -307,6 +307,423 @@ fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
|
||||
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
|
||||
}
|
||||
|
||||
/// A stand-in for the engine's [`DrawnArt`]: an object with a visible effect named `test.shift`
|
||||
/// draws 100 pt to the right of its own place, and one with a visible effect named `test.copy`
|
||||
/// draws at its own place and 100 pt to the right. The effects are applied innermost first, and
|
||||
/// the art keeps the ids of the objects it is drawn from. An instance of a symbol whose art has a
|
||||
/// visible effect draws as a 50 pt square from (100, 0), white with a black 1 pt stroke. A clip
|
||||
/// group with a visible effect named `test.mask_only` draws as a group of its clipping path alone,
|
||||
/// as the engine's art for a clip group whose clipping path's strokes have geometry effects is.
|
||||
/// Without any of these, no geometry effect changes what an object draws.
|
||||
fn shifted_art(s: &SymbolBoxes<'_>, n: &Node) -> Option<Node> {
|
||||
if n.clips()
|
||||
&& n.appearance.effects.iter().any(|e| e.visible && e.id == "test.mask_only")
|
||||
&& let Some(mask) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
return Some(Node::group(n.id, vec![mask.clone()]));
|
||||
}
|
||||
fn draw(s: &SymbolBoxes<'_>, n: &Node, found: &mut bool) -> Node {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
|
||||
&& s.has_effects(symbol)
|
||||
{
|
||||
*found = true;
|
||||
return Node::path(n.id, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art());
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(draw(s, c, found));
|
||||
}
|
||||
}
|
||||
let has = |id: &str| n.appearance.effects.iter().any(|e| e.visible && e.id == id);
|
||||
let (shift, copy) = (has("test.shift"), has("test.copy"));
|
||||
m.appearance.effects.retain(|e| e.id != "test.shift" && e.id != "test.copy");
|
||||
*found |= shift || copy;
|
||||
let shifted = |m: &Node| moved(m, vectorcraft_geom::Affine::translate((100.0, 0.0)));
|
||||
if shift {
|
||||
shifted(&m)
|
||||
} else if copy {
|
||||
Node::group(n.id, vec![Arc::new(shifted(&m)), Arc::new(m)])
|
||||
} else {
|
||||
m
|
||||
}
|
||||
}
|
||||
let mut found = false;
|
||||
let art = draw(s, n, &mut found);
|
||||
found.then_some(art)
|
||||
}
|
||||
|
||||
/// A visible effect named `id`.
|
||||
fn effect(id: &str) -> crate::Effect {
|
||||
crate::Effect { id: id.into(), params: serde_json::json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// A 50 pt square at `x`, `y`, white with a black 1 pt stroke.
|
||||
fn square(d: &mut Document, x: f64, y: f64) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 50.0, y + 50.0)), Appearance::default_art())
|
||||
}
|
||||
|
||||
/// The leaf and the kind a click at (`x`, `y`) hits.
|
||||
fn hit_at(d: &Document, x: f64, y: f64, opt: HitOptions) -> Option<(NodeId, HitKind)> {
|
||||
hit_test(d, Point::new(x, y), opt).map(|h| (h.leaf, h.kind))
|
||||
}
|
||||
|
||||
/// A path that a geometry effect moves is clicked where it is drawn, and not at its own place,
|
||||
/// which it no longer paints; with Object Selection by Path Only on its drawn outline, not its
|
||||
/// fill. Outline view draws no effects: there its own outline is clicked. Hidden, the effect no
|
||||
/// longer moves what clicks hit.
|
||||
#[test]
|
||||
fn a_click_hits_a_paths_shifted_art_not_its_source() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.shift"));
|
||||
let a = p.id;
|
||||
d.insert(Some(l), 0, p).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)), "where it is drawn");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a]);
|
||||
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
|
||||
let path_only = HitOptions { path_only: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, path_only), None, "path only: the drawn fill");
|
||||
assert_eq!(hit_at(&d, 100.0, 25.0, path_only), Some((a, HitKind::Stroke)), "path only: the drawn outline");
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, outline), Some((a, HitKind::Outline)), "outline: its own outline");
|
||||
assert_eq!(hit_at(&d, 100.5, 25.0, outline), None, "outline: no drawn art");
|
||||
d.node_mut(a).unwrap().appearance.effects[0].visible = false;
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), Some((a, HitKind::Fill)), "hidden effect: its own place");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "hidden effect: nothing drawn there");
|
||||
}
|
||||
|
||||
/// A geometry effect that copies a path is clicked on the copy and on the path, the topmost of the
|
||||
/// stack first. The pointer moving over it evaluates its art once until it changes, and a path
|
||||
/// without effects is not evaluated.
|
||||
#[test]
|
||||
fn a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let below = square(&mut d, 100.0, 0.0);
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.copy"));
|
||||
let (a, b) = (p.id, below.id);
|
||||
d.insert(Some(l), 0, below).unwrap();
|
||||
d.insert(Some(l), 1, p).unwrap();
|
||||
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let opt = HitOptions::default();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt).map(|h| h.0), Some(a), "the path");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt).map(|h| h.0), Some(a), "its copy, over the square below");
|
||||
}
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a, b]);
|
||||
assert_eq!(evaluated(), before + 1, "evaluated once");
|
||||
if let Some(NodeKind::Path { path, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
|
||||
*path = shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 50.0));
|
||||
}
|
||||
assert_eq!(hit_at(&d, 140.0, 25.0, opt).map(|h| h.0), Some(b), "narrowed, the copy leaves the square below");
|
||||
assert_eq!(evaluated(), before + 2, "evaluated again after it changed");
|
||||
// The square below has no effects: it is never evaluated.
|
||||
assert_eq!(hit_at(&d, 145.0, 45.0, opt).map(|h| h.0), Some(b));
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A group without effects or fills and strokes of its own is not evaluated as a whole: a click
|
||||
/// on the art of a moved member in it evaluates that member only, and finds the group by it.
|
||||
#[test]
|
||||
fn a_click_in_a_plain_group_evaluates_only_its_member_with_effects() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut moved = square(&mut d, 0.0, 0.0);
|
||||
moved.appearance.effects.push(effect("test.shift"));
|
||||
let still = square(&mut d, 0.0, 100.0);
|
||||
let (a, g) = (moved.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(moved), Arc::new(still)])).unwrap();
|
||||
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let opt = HitOptions::default();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)));
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
|
||||
}
|
||||
assert_eq!(evaluated(), before + 1, "only the member with effects, once");
|
||||
}
|
||||
|
||||
/// A compound path that a geometry effect moves keeps its hole where it is drawn, for clicks and
|
||||
/// marquees.
|
||||
#[test]
|
||||
fn a_compound_paths_shifted_art_keeps_its_hole() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let outer = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), Appearance::default());
|
||||
let hole = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default());
|
||||
let c = d.alloc_id();
|
||||
let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd });
|
||||
compound.appearance = Appearance::default_art().into();
|
||||
compound.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 105.0, 5.0, opt), Some((c, HitKind::Fill)), "its drawn fill");
|
||||
assert_eq!(hit_at(&d, 130.0, 30.0, opt), None, "its drawn hole");
|
||||
assert_eq!(hit_at(&d, 5.0, 5.0, opt), None, "its own place");
|
||||
assert_eq!(marquee(&d, Rect::new(155.0, 25.0, 165.0, 35.0), None, false), [c], "a marquee across the drawn edge");
|
||||
assert!(marquee(&d, Rect::new(-5.0, 25.0, 5.0, 35.0), None, false).is_empty(), "a marquee across its own edge");
|
||||
}
|
||||
|
||||
/// A marquee touches a path that a geometry effect moves where it is drawn, and not at its own
|
||||
/// place; in Outline view, at its own place.
|
||||
#[test]
|
||||
fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut p = square(&mut d, 0.0, 0.0);
|
||||
p.appearance.effects.push(effect("test.shift"));
|
||||
let a = p.id;
|
||||
d.insert(Some(l), 0, p).unwrap();
|
||||
let (drawn, own) = (Rect::new(140.0, 40.0, 160.0, 60.0), Rect::new(40.0, 40.0, 60.0, 60.0));
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose own geometry effect moves its members is clicked where each member is drawn: the
|
||||
/// member, inside the group, is hit, and a locked member lets the click through to what is below
|
||||
/// and is listed for unlocking there. A marquee there touches the group, or the member for Direct
|
||||
/// Selection.
|
||||
#[test]
|
||||
fn a_groups_own_effect_moves_where_its_members_are_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let below = square(&mut d, 150.0, 0.0);
|
||||
let (a, b) = (square(&mut d, 0.0, 0.0), square(&mut d, 50.0, 0.0));
|
||||
let (below_id, a_id, b_id, g) = (below.id, a.id, b.id, d.alloc_id());
|
||||
let mut group = Node::group(g, vec![Arc::new(a), Arc::new(b)]);
|
||||
group.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, below).unwrap();
|
||||
d.insert(Some(l), 1, group).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
let h = hit_test(&d, Point::new(125.0, 25.0), opt).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None)), (a_id, g), "the first member, drawn there");
|
||||
assert_eq!(h.ancestry, [l, g, a_id]);
|
||||
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(b_id), "the second member, over the square below");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "the first member's own place");
|
||||
assert_eq!(objects_at(&d, Point::new(175.0, 25.0), opt, None), [g, below_id]);
|
||||
let drawn = Rect::new(195.0, 20.0, 205.0, 30.0);
|
||||
assert_eq!(marquee(&d, drawn, None, false), [below_id, g]);
|
||||
assert_eq!(marquee(&d, drawn, None, true), [below_id, b_id]);
|
||||
assert!(marquee(&d, Rect::new(-5.0, 20.0, 5.0, 30.0), None, true).is_empty(), "the members' own place");
|
||||
d.node_mut(b_id).unwrap().locked = true;
|
||||
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(below_id), "a locked member lets the click through");
|
||||
assert_eq!(marquee(&d, drawn, None, true), [below_id], "nor does a marquee collect it");
|
||||
assert_eq!(locked_objects_at(&d, Point::new(175.0, 25.0), opt), [b_id], "the Unlock submenu lists it where it is drawn");
|
||||
assert!(locked_objects_at(&d, Point::new(75.0, 25.0), opt).is_empty(), "and not at its own place");
|
||||
// Outline view draws no effects: the members are clicked at their own places.
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, outline).map(|h| h.0), Some(a_id));
|
||||
}
|
||||
|
||||
/// A layer whose own geometry effect moves its art is clicked and marqueed where the art is
|
||||
/// drawn. With the layer's Preview off, its art is clicked at its own place, in outline.
|
||||
#[test]
|
||||
fn a_layers_own_effect_moves_where_its_art_is_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = square(&mut d, 0.0, 0.0);
|
||||
let a_id = a.id;
|
||||
d.insert(Some(l), 0, a).unwrap();
|
||||
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "where it is drawn");
|
||||
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a_id]);
|
||||
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
|
||||
let (drawn, own) = (Rect::new(145.0, 20.0, 155.0, 30.0), Rect::new(-5.0, 20.0, 5.0, 30.0));
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a_id], "a marquee where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "a marquee at its own place");
|
||||
}
|
||||
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(l).map(|n| &mut n.kind) {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(hit_at(&d, 0.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: its own outline");
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: no drawn art");
|
||||
assert_eq!(marquee(&d, own, None, false), [a_id], "preview off: a marquee at its own place");
|
||||
}
|
||||
|
||||
/// In a layer whose own geometry effect moves its art, a sublayer with Preview off is clicked in
|
||||
/// outline: on the outline of its art where the art is drawn, not inside its fill.
|
||||
#[test]
|
||||
fn a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap();
|
||||
let a = square(&mut d, 0.0, 0.0);
|
||||
let a_id = a.id;
|
||||
d.insert(Some(sub), 0, a).unwrap();
|
||||
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "preview on: inside its fill");
|
||||
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(sub).map(|n| &mut n.kind) {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: inside its fill");
|
||||
assert_eq!(hit_at(&d, 100.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: on its outline");
|
||||
}
|
||||
|
||||
/// A group with fills and strokes of its own around an instance of a symbol whose art has an
|
||||
/// effect is clicked where its art is drawn, though no object in the group has an effect.
|
||||
#[test]
|
||||
fn a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut art = square(&mut d, 0.0, 0.0);
|
||||
art.appearance.effects.push(effect("test.raster"));
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Effected".into(), art: Arc::new(art) });
|
||||
let (g, inst) = (d.alloc_id(), d.alloc_id());
|
||||
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: "Effected".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let mut group = Node::group(g, vec![Arc::new(instance)]);
|
||||
group.appearance = Appearance::default_art().into();
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((inst, HitKind::Fill)), "where its art is drawn");
|
||||
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
|
||||
}
|
||||
|
||||
/// In a layer with fills and strokes of its own whose art is evaluated for a member's geometry
|
||||
/// effect, an Intertwine group's members are still clicked in the order they are drawn at the
|
||||
/// click: where the lower member is woven over the upper one, the click takes the lower member.
|
||||
#[test]
|
||||
fn an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
d.node_mut(l).unwrap().appearance = Appearance::default_art().into();
|
||||
let mut a = square(&mut d, 0.0, 100.0);
|
||||
a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(25.0, 100.0, 50.0, 150.0))));
|
||||
let b = square(&mut d, 25.0, 100.0);
|
||||
let (a_id, b_id, g) = (a.id, b.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap();
|
||||
let mut moved = square(&mut d, 200.0, 0.0);
|
||||
moved.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 1, moved).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 40.0, 125.0, opt), Some((a_id, HitKind::Fill)), "where the lower member is woven over");
|
||||
assert_eq!(hit_at(&d, 60.0, 125.0, opt), Some((b_id, HitKind::Fill)), "where the upper member is drawn over");
|
||||
}
|
||||
|
||||
/// The clipping path of a clip group and of a clipping layer is still marqueed by its own geometry
|
||||
/// when a geometry effect moves what it draws.
|
||||
#[test]
|
||||
fn a_clipping_path_keeps_its_own_geometry_under_a_geometry_effect() {
|
||||
set_drawn_art(shifted_art);
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
// A clip group.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(effect("test.shift"));
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clip group");
|
||||
// A clipping layer.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(effect("test.shift"));
|
||||
let (mask_id, art_id) = (mask.id, art.id);
|
||||
let layer = d.node_mut(l).unwrap();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
|
||||
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
|
||||
}
|
||||
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clipping layer");
|
||||
}
|
||||
|
||||
/// The selection tools take the clipping path of a clip group whose own geometry effect moves it
|
||||
/// on its outline where it is drawn, before the art it clips, and not at its own place.
|
||||
#[test]
|
||||
fn a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let tools = HitOptions { clip_outlines: true, ..HitOptions::default() };
|
||||
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "the drawn edge, over the art");
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "the drawn art inside the mask");
|
||||
assert_eq!(hit_at(&d, 0.5, 50.0, tools), None, "the mask's own edge");
|
||||
// The same clip group in a group whose own effect moves it.
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
outer.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, outer).unwrap();
|
||||
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "in a moved group: the drawn edge, over the art");
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "in a moved group: the drawn art");
|
||||
}
|
||||
|
||||
/// In isolation mode in a clip group whose own geometry effect moves it, the selection tools take
|
||||
/// the art outside the clipping mask by its own geometry, for a marquee as for a click.
|
||||
#[test]
|
||||
fn an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.shift"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let tools = HitOptions { clip_outlines: true, scope: Some(g), ..HitOptions::default() };
|
||||
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "a click outside the mask");
|
||||
let edge = Rect::new(190.0, 40.0, 210.0, 60.0);
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, edge, Some(g), leaves), [art_id], "a marquee across its own edge outside the mask");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip group whose drawn art holds only its clipping path still has the art it clips clicked
|
||||
/// inside the mask.
|
||||
#[test]
|
||||
fn a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path() {
|
||||
set_drawn_art(shifted_art);
|
||||
let mut d = Document::new(400.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
clip.appearance.effects.push(effect("test.mask_only"));
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(hit_at(&d, 50.0, 50.0, opt), Some((art_id, HitKind::Fill)), "inside the mask");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), opt, None), [g]);
|
||||
assert!(hit_at(&d, 150.0, 50.0, opt).is_none(), "outside the mask");
|
||||
}
|
||||
|
||||
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
|
||||
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
|
||||
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
|
||||
@@ -1452,6 +1869,76 @@ fn objects_at_edit_contents_uses_general_order() {
|
||||
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
|
||||
}
|
||||
|
||||
/// Select Behind keeps one limit of symbol art to walk when it falls back to the general
|
||||
/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback
|
||||
/// walks no more art than what the first pass left, and keeps what the first pass found.
|
||||
#[test]
|
||||
fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
// 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art
|
||||
// of and misses: each walk takes 3 objects of the 100.
|
||||
let stack = |d: &mut Document, count: usize| {
|
||||
let l = d.layers[0].id;
|
||||
for _ in 0..count {
|
||||
let inst = instance_of(d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
};
|
||||
// An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50).
|
||||
let envelope = |d: &mut Document| {
|
||||
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (a, b) = (d.alloc_id(), d.alloc_id());
|
||||
let e = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, e).unwrap();
|
||||
(a, b)
|
||||
};
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
stack(&mut d, 60);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![b, a]);
|
||||
assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked");
|
||||
// An instance that the first pass hits by its art, the limit then used up, stays in the list:
|
||||
// `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
let (a, b) = envelope(&mut d);
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(clip)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
stack(&mut d, 32);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback");
|
||||
assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked");
|
||||
// A root that is not a layer, below the layer.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
stack(&mut d, 60);
|
||||
let root = Arc::new(Node::group(d.alloc_id(), vec![]));
|
||||
d.layers.insert(0, root);
|
||||
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
|
||||
assert!(behind.is_empty());
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -2140,6 +2627,37 @@ fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit(
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
|
||||
}
|
||||
|
||||
/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects
|
||||
/// for a click, as the members of a plain group do. A click on a member's path past the instance's
|
||||
/// box is still found within the limit.
|
||||
#[test]
|
||||
fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100
|
||||
// box, over an Intertwine group of 200 squares at 140..160 × 40..60.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let squares = (0..200)
|
||||
.map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art())))
|
||||
.collect();
|
||||
let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares }));
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Woven", vec![Arc::new(clip)]);
|
||||
let inst = instance_of(&mut d, "Woven");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let opt = HitOptions { path_only: true, ..HitOptions::default() };
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
// Inside the squares and away from their paths, every member is tested and none is hit.
|
||||
let (hit, leaves, _) = with_art_limit(100, || at(150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(leaves <= 100, "{leaves} leaves tested");
|
||||
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
+107
-16
@@ -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,20 +75,29 @@ 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.
|
||||
@@ -86,16 +109,22 @@ fn ink_amount(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// 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. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
/// 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: [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(), ink_amount(tint))), 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 }
|
||||
}
|
||||
@@ -106,11 +135,18 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
|
||||
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
|
||||
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
|
||||
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
|
||||
/// 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(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
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
|
||||
}
|
||||
@@ -201,7 +237,7 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch, SwatchGroup};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
/// A document with spot swatch `Gold` and process swatch `Teal`.
|
||||
@@ -233,6 +269,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
|
||||
@@ -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,7 +55,7 @@ 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;
|
||||
@@ -94,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};
|
||||
|
||||
+47
-29
@@ -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,21 +200,16 @@ 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.
|
||||
@@ -748,4 +733,37 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -608,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;
|
||||
|
||||
@@ -805,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)]);
|
||||
}
|
||||
+119
-7
@@ -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);
|
||||
|
||||
+126
-23
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -50,10 +50,10 @@ pub struct Selection {
|
||||
#[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,
|
||||
/// the last one a Shift-click added (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.
|
||||
/// 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
|
||||
@@ -311,7 +311,7 @@ impl Selection {
|
||||
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.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))
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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()));
|
||||
|
||||
+256
-12
@@ -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;
|
||||
@@ -340,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 {
|
||||
@@ -384,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())
|
||||
}
|
||||
|
||||
@@ -400,7 +422,7 @@ 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())
|
||||
@@ -718,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()
|
||||
@@ -725,18 +755,20 @@ 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));
|
||||
}
|
||||
|
||||
@@ -811,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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
+372
-2
@@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> {
|
||||
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 {
|
||||
/// [`SymbolBoxes`] for this document's symbols, none measured yet.
|
||||
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
|
||||
@@ -131,6 +259,56 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`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 {
|
||||
@@ -148,6 +326,8 @@ impl Document {
|
||||
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> {
|
||||
@@ -218,6 +398,8 @@ impl<'a> SymbolBoxes<'a> {
|
||||
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
|
||||
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
|
||||
@@ -584,10 +766,10 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
#[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 {
|
||||
@@ -911,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);
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,8 @@ 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, GlyphForm, MAX_AKI, MAX_TSUME, 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, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
@@ -35,7 +35,7 @@ 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`.
|
||||
///
|
||||
@@ -67,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,
|
||||
|
||||
@@ -48,8 +48,10 @@ pub struct CharStyle {
|
||||
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
|
||||
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
|
||||
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
|
||||
/// after it. Horizontal type only.
|
||||
/// 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.
|
||||
@@ -180,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")]
|
||||
@@ -553,6 +567,10 @@ 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;
|
||||
|
||||
@@ -684,6 +702,8 @@ 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,
|
||||
@@ -707,7 +727,8 @@ impl CharStyle {
|
||||
/// 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 };
|
||||
@@ -723,6 +744,9 @@ impl CharStyle {
|
||||
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 =
|
||||
|
||||
@@ -94,6 +94,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(),
|
||||
@@ -511,6 +512,8 @@ impl crate::Document {
|
||||
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();
|
||||
@@ -537,6 +540,8 @@ impl crate::Document {
|
||||
("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 {
|
||||
|
||||
@@ -271,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.
|
||||
@@ -375,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,
|
||||
@@ -412,6 +417,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -439,6 +445,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -470,6 +477,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
@@ -496,6 +504,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
korean_line_break_anywhere,
|
||||
|
||||
@@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() {
|
||||
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0,
|
||||
/// each on its own; styles written before them read as 0, and a value out of range from a file is
|
||||
/// kept within one em either way.
|
||||
#[test]
|
||||
fn diacritic_positions_are_saved_only_when_set() {
|
||||
let st = CharStyle::default();
|
||||
assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0));
|
||||
let saved = serde_json::to_value(&st).unwrap();
|
||||
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
|
||||
for set in [
|
||||
CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() },
|
||||
] {
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal);
|
||||
assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical);
|
||||
assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0);
|
||||
assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0);
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
|
||||
}
|
||||
let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION));
|
||||
let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION));
|
||||
// A character style from a file is kept in range the same way.
|
||||
let mut d = crate::Document::new(100.0, 100.0);
|
||||
let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000});
|
||||
d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
|
||||
d.keep_type_values_in_range();
|
||||
let kept = |key: &str| d.char_styles[0].attrs[key].as_f64();
|
||||
assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION)));
|
||||
}
|
||||
|
||||
/// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a
|
||||
/// value out of range from a file, in a run or a character style, is kept from 0 to 100.
|
||||
#[test]
|
||||
|
||||
+68
-34
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, shapes};
|
||||
|
||||
use super::{TextKind, WrapShape};
|
||||
use super::{TextKind, TextObject, WrapShape};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
|
||||
@@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline area type wraps around for wrap object `n`, in document coordinates, as
|
||||
/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those
|
||||
/// of the shown members of a group or compound path, a clip group's clipping object's, and the
|
||||
/// bounds of other art. Empty when `n` has none.
|
||||
pub fn wrap_outline(n: &Node) -> PathData {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
pd
|
||||
}
|
||||
|
||||
enum Item<'a> {
|
||||
Wrap(&'a Node),
|
||||
Text(&'a Node),
|
||||
@@ -82,6 +92,57 @@ pub fn wrap_work(doc: &Document) -> usize {
|
||||
total
|
||||
}
|
||||
|
||||
/// Each area text object of `layer`, from the top down, with the wrap objects above it in the
|
||||
/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in
|
||||
/// document coordinates. Each wrap object's outline is made once.
|
||||
fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) {
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
let mut above: Vec<(&Node, WrapShape)> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }));
|
||||
}
|
||||
}
|
||||
Item::Text(n) => f(n, &above),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as
|
||||
/// [`each_text`] gives them: bottom first.
|
||||
fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
|
||||
let inv = t.xf.inverse();
|
||||
above
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(_, s)| {
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap
|
||||
/// objects whose outlines make them, bottom first, and those shapes (text space), as
|
||||
/// [`resolve_wrap`] works them out. The copying is [`wrap_work`].
|
||||
pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec<WrapShape>)) {
|
||||
for layer in &doc.layers {
|
||||
each_text(layer, |n, above| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& !above.is_empty()
|
||||
{
|
||||
f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
|
||||
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
|
||||
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
|
||||
@@ -95,41 +156,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut items = vec![];
|
||||
collect(layer, &mut items);
|
||||
if items.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// From the top down, each wrap object's outline is made once; each area text object takes
|
||||
// those above it, bottom first.
|
||||
let mut above: Vec<WrapShape> = vec![];
|
||||
for it in items.iter().rev() {
|
||||
match it {
|
||||
Item::Wrap(n) => {
|
||||
let mut pd = PathData::default();
|
||||
outline(n, &mut pd);
|
||||
if !pd.is_empty() {
|
||||
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
|
||||
}
|
||||
}
|
||||
Item::Text(n) => {
|
||||
let NodeKind::Text(t) = &n.kind else { continue };
|
||||
let inv = t.xf.inverse();
|
||||
let shapes: Vec<WrapShape> = above
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|s| {
|
||||
let mut path = s.path.clone();
|
||||
path.transform(inv);
|
||||
WrapShape { path, wrap: s.wrap }
|
||||
})
|
||||
.collect();
|
||||
if shapes != t.wrap {
|
||||
updates.push((n.id, shapes));
|
||||
}
|
||||
each_text(layer, |n, above| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let shapes = shapes_of(t, above);
|
||||
if shapes != t.wrap {
|
||||
updates.push((n.id, shapes));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut changed = Vec::with_capacity(updates.len());
|
||||
for (id, shapes) in updates {
|
||||
|
||||
@@ -17,10 +17,10 @@ vectorcraft-text = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-trace = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
|
||||
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
|
||||
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
|
||||
# Effect › SVG Filters draws its filters with craft-svg's resvg (`tree-render`).
|
||||
craft-svg = { workspace = true, features = ["tree-render"] }
|
||||
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
|
||||
svgtypes = "0.16"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+60
-20
@@ -117,6 +117,11 @@ thread_local! {
|
||||
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
|
||||
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
|
||||
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The objects in the baked art of the instances inside the art of other instances that
|
||||
/// [`bake_node`] baked for one export and then left as they are, counted with
|
||||
/// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never
|
||||
/// given back.
|
||||
static NESTED_DROPPED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
|
||||
/// placed art ([`placed_symbol_art`]).
|
||||
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
|
||||
@@ -162,7 +167,7 @@ struct Placing {
|
||||
layers: WrittenLayers,
|
||||
}
|
||||
|
||||
/// The layers an exporter writes besides the shown, printing ones
|
||||
/// The layers and objects an exporter writes besides the shown, printing ones
|
||||
/// ([`bake_document_placing_symbols`]). Template layers are never written.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct WrittenLayers {
|
||||
@@ -170,16 +175,19 @@ pub struct WrittenLayers {
|
||||
pub hidden: bool,
|
||||
/// Layers that do not print.
|
||||
pub non_printing: bool,
|
||||
/// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden
|
||||
/// layers).
|
||||
pub hidden_objects: bool,
|
||||
}
|
||||
|
||||
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
|
||||
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
|
||||
/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer
|
||||
/// that does not print when the export leaves those out ([`WrittenLayers`]).
|
||||
fn unwritten(n: &Node) -> bool {
|
||||
PLACING.with(|p| {
|
||||
p.borrow().as_ref().is_some_and(|p| match n.kind {
|
||||
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
|
||||
_ => !n.visible,
|
||||
_ => !(n.visible || p.layers.hidden_objects),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -369,17 +377,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
};
|
||||
// Instances baked inside the art of others stop at the depth limit, or once their art
|
||||
// passes the objects one export bakes that way: an instance of a symbol whose art holds
|
||||
// instances of itself is kept as it is there.
|
||||
// instances of itself is kept as it is there. The symbol's art is held in the count while
|
||||
// it bakes, so the instances inside it bake only within what is left; the art it bakes to,
|
||||
// with what its effects add, then takes its place in the count. When that art does not
|
||||
// fit, the instance stays as it is, and the art baked for it, with the art dropped for the
|
||||
// instances inside it, still counts against the instances after it.
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
|
||||
let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0;
|
||||
let before = NESTED_NODES.with(|c| c.get());
|
||||
if nested {
|
||||
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
|
||||
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
|
||||
let spent = before.saturating_add(count);
|
||||
let dropped = NESTED_DROPPED.with(|c| c.get());
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES {
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
let m = reshape(Some(d), n, symbol.as_ref())?;
|
||||
let Some(m) = reshape(Some(d), n, symbol.as_ref()) else {
|
||||
if nested {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
|
||||
}
|
||||
@@ -387,7 +407,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
if instance {
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
|
||||
}
|
||||
return Some(baked.unwrap_or(m));
|
||||
let baked = baked.unwrap_or(m);
|
||||
if nested {
|
||||
let spent = before.saturating_add(baked.count() as u64);
|
||||
if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES {
|
||||
NESTED_NODES.with(|c| c.set(before));
|
||||
NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64)));
|
||||
return None;
|
||||
}
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
}
|
||||
return Some(baked);
|
||||
}
|
||||
// Symbol instances whose art draws live effects, when the caller asks for them: the art
|
||||
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
|
||||
@@ -653,9 +683,11 @@ fn apart(offsets: &[Vec2], b: Rect) -> bool {
|
||||
|
||||
/// Type `n` whose own geometry effects only move it ([`transform_moves`]) as a group of the moved
|
||||
/// type ([`moved_type`]). The group keeps `n`'s id, name, visibility, transparency, opacity mask and
|
||||
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise.
|
||||
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise, and for type
|
||||
/// whose copies each carry the raster effects listed before their Transform effect
|
||||
/// ([`crate::outer_effects`]), which is baked through its outlines as the canvas draws it.
|
||||
fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::Text(_)) {
|
||||
if !matches!(n.kind, NodeKind::Text(_)) || crate::reshape::copied_raster_at(n).is_some() {
|
||||
return None;
|
||||
}
|
||||
let moves = transform_moves(&geometry_effects(n))?;
|
||||
@@ -688,7 +720,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
/// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live
|
||||
/// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is
|
||||
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
|
||||
/// them. `None` when no type stays type.
|
||||
/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster
|
||||
/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the
|
||||
/// canvas draws it ([`evaluate_container`]).
|
||||
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
if !clipping {
|
||||
@@ -724,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) {
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
|| has_pathfinder(n)
|
||||
|| has_own_paint(n)
|
||||
|| crate::reshape::copied_container_raster_at(n).is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
@@ -1014,13 +1052,14 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
|
||||
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
|
||||
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
|
||||
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
|
||||
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
|
||||
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
|
||||
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
|
||||
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
|
||||
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
|
||||
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
|
||||
/// symbols' own art is left as it is.
|
||||
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and
|
||||
/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`:
|
||||
/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
|
||||
/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`:
|
||||
/// the hidden layers, layers that do not print and hidden objects that the exporter writes.
|
||||
/// Instances the export does not write (template layers, and the hidden objects and layers
|
||||
/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as
|
||||
/// it is.
|
||||
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
|
||||
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
|
||||
}
|
||||
@@ -1068,6 +1107,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<D
|
||||
}
|
||||
let mut d = placed.into_owned();
|
||||
NESTED_NODES.with(|c| c.set(0));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let layers = d.layers.clone();
|
||||
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
|
||||
Some(d)
|
||||
|
||||
@@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() {
|
||||
}
|
||||
|
||||
/// Every layer written, as DXF writes them (template layers are never written).
|
||||
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
|
||||
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
|
||||
fn is_instance(d: &Document, id: u64) -> bool {
|
||||
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
@@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() {
|
||||
}
|
||||
// An export that writes the layers that do not print, or the hidden layers, places that
|
||||
// layer's instance first; the template layer's instance is never placed.
|
||||
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
|
||||
for (layers, first) in
|
||||
[(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)]
|
||||
{
|
||||
let out = bake(&d, Some((true, each, layers))).unwrap();
|
||||
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
|
||||
}
|
||||
// An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance
|
||||
// first, and the instance in the hidden group would come next; the hidden layer's instance
|
||||
// stays, since that layer is still left out.
|
||||
let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap();
|
||||
assert!(!is_instance(&out, 901), "the hidden instance is placed");
|
||||
for id in [900, 903, 911, 921, 931] {
|
||||
assert!(is_instance(&out, id), "{id} stays as it is");
|
||||
}
|
||||
}
|
||||
|
||||
/// `leaf` in `levels` groups, with ids from `id` up.
|
||||
@@ -1525,3 +1535,125 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
|
||||
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
|
||||
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
|
||||
}
|
||||
|
||||
/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art.
|
||||
fn offset_instance(id: u64, symbol: &str) -> Node {
|
||||
let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY);
|
||||
n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0})));
|
||||
n
|
||||
}
|
||||
|
||||
/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol
|
||||
/// art already baked: the baked object, and the objects counted after it, art baked and dropped
|
||||
/// included.
|
||||
fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option<Node>, u64) {
|
||||
INSTANCE_DEPTH.with(|c| c.set(1));
|
||||
NESTED_NODES.with(|c| c.set(spent));
|
||||
NESTED_DROPPED.with(|c| c.set(0));
|
||||
let out = bake_node(d, n);
|
||||
INSTANCE_DEPTH.with(|c| c.set(0));
|
||||
(out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0))))
|
||||
}
|
||||
|
||||
/// The object with id `id` in `n`'s subtree.
|
||||
fn find(n: &Node, id: u64) -> Option<&Node> {
|
||||
if n.id == NodeId(id) {
|
||||
return Some(n);
|
||||
}
|
||||
n.children().into_iter().flatten().find_map(|c| find(c, id))
|
||||
}
|
||||
|
||||
/// Is `n` an object other than a symbol instance?
|
||||
fn baked(n: Option<&Node>) -> bool {
|
||||
n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
}
|
||||
|
||||
/// An instance baked inside another instance's art counts the art it bakes to, the copies its
|
||||
/// symbol's effects make included: art that fits exactly takes the last of the budget, and art
|
||||
/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_baked_art() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let n = offset_instance(900, "Inner");
|
||||
let source = d.symbols[0].art.count() as u64;
|
||||
let (all, spent) = bake_nested(&mut d, &n, 0);
|
||||
let baked = all.map_or(0, |m| m.count() as u64);
|
||||
assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1");
|
||||
assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art");
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &n, max - baked);
|
||||
assert!(exact.is_some(), "{baked} objects fit in {baked}");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &n, max - baked + 1);
|
||||
assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not");
|
||||
assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts");
|
||||
}
|
||||
|
||||
/// An instance left as it is because its baked art does not fit still counts the art baked for
|
||||
/// it: an instance after it is left as it is too, before its art bakes.
|
||||
#[test]
|
||||
fn nested_reshape_refusal_keeps_its_work_counted() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
add_symbol(&mut d, "Small", moved_square(810));
|
||||
let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small"));
|
||||
let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let (b, s) = (count(&mut d, &big), count(&mut d, &small));
|
||||
assert!(s < b, "{s} < {b}");
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &big, first);
|
||||
assert!(refused.is_none(), "the big art passes the budget");
|
||||
assert_eq!(spent, first + b, "the big art baked and dropped counts");
|
||||
let (later, after) = bake_nested(&mut d, &small, spent);
|
||||
assert!(later.is_none(), "the small art does not fit after the dropped art");
|
||||
assert_eq!(after, spent, "the small instance is refused before it bakes");
|
||||
}
|
||||
|
||||
/// Sibling instances inside other instances' art whose baked art each passes what is left: the
|
||||
/// first is baked and dropped, and its art counts, so the others are left as they are before
|
||||
/// their art bakes. With room for all of them, every one is baked.
|
||||
#[test]
|
||||
fn nested_reshape_refused_siblings_bake_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
let one = offset_instance(900, "Big");
|
||||
let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64);
|
||||
let siblings: Vec<Arc<Node>> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect();
|
||||
let group = Node::group(NodeId(999), siblings);
|
||||
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
|
||||
let (refused, spent) = bake_nested(&mut d, &group, first);
|
||||
let refused = refused.unwrap_or_else(|| group.clone());
|
||||
assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}");
|
||||
assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}");
|
||||
let (room, spent) = bake_nested(&mut d, &group, 0);
|
||||
let room = room.unwrap_or_else(|| panic!("the siblings are baked"));
|
||||
assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked");
|
||||
assert_eq!(spent, 16 * b);
|
||||
}
|
||||
|
||||
/// An instance inside another instance's art whose own art holds a reshaped instance counts that
|
||||
/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and
|
||||
/// with one object less the art baked and dropped still counts.
|
||||
#[test]
|
||||
fn nested_reshape_counts_successful_descendants_once() {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)]));
|
||||
let outer = offset_instance(900, "Outer");
|
||||
let (all, spent) = bake_nested(&mut d, &outer, 0);
|
||||
let all = all.unwrap_or_else(|| panic!("the outer instance is baked"));
|
||||
assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}");
|
||||
let total = all.count() as u64;
|
||||
assert_eq!(spent, total);
|
||||
let max = crate::SYMBOL_ART_MAX_NODES;
|
||||
let (exact, spent) = bake_nested(&mut d, &outer, max - total);
|
||||
let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}"));
|
||||
assert!(baked(find(&exact, 802)), "the inner instance is baked too");
|
||||
assert_eq!(spent, max);
|
||||
let (short, spent) = bake_nested(&mut d, &outer, max - total + 1);
|
||||
assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked");
|
||||
assert!(spent > max, "the art baked and dropped counts: {spent}");
|
||||
assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}");
|
||||
}
|
||||
@@ -182,49 +182,49 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
EXTRUDE,
|
||||
"Extrude & Bevel…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
|
||||
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
ROTATE,
|
||||
"Rotate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
"Rotate (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
@@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineH
|
||||
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
|
||||
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
|
||||
if outline {
|
||||
let fill = src.appearance.fill_paint();
|
||||
let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill };
|
||||
appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() };
|
||||
// The edges take the paint, opacity, blend mode and overprint of the top fill that paints,
|
||||
// or of the top stroke that paints when no fill does.
|
||||
let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i)));
|
||||
let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0);
|
||||
if let Some(i) = layer {
|
||||
(stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint());
|
||||
}
|
||||
appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
|
||||
}
|
||||
let mut n = Node::path(src.id, path, appearance);
|
||||
n.opacity = src.opacity;
|
||||
@@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
|
||||
.iter()
|
||||
.filter_map(|l| {
|
||||
let (path, rule) = geometry(l)?;
|
||||
Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() }))
|
||||
let fill = top_painting_fill(&l.appearance).map_or(Paint::None, |i| i.paint().clone());
|
||||
Some((l.id, crate::trap::TrapSource { path, rule, fill }))
|
||||
})
|
||||
.unzip();
|
||||
let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params));
|
||||
@@ -580,7 +586,8 @@ fn mixing_rate(params: &Value) -> f64 {
|
||||
}
|
||||
|
||||
fn fill_cmyk(src: &Node) -> Option<[f32; 4]> {
|
||||
let paint = src.appearance.fill_paint();
|
||||
// The top fill that paints: a hidden fill adds no color.
|
||||
let paint = top_painting_fill(&src.appearance)?.paint().clone();
|
||||
let color = paint.color()?;
|
||||
let tinted = match paint {
|
||||
Paint::Solid { tint, .. } => color.tinted(tint),
|
||||
@@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped.
|
||||
fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> {
|
||||
a.items.iter().rev().find(|i| i.is_fill() && paints(i))
|
||||
}
|
||||
|
||||
/// Does `item` paint anything?
|
||||
pub fn paints(item: &AppearanceItem) -> bool {
|
||||
item.visible()
|
||||
@@ -820,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
|
||||
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
|
||||
/// symbols' art from `doc`.
|
||||
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
|
||||
/// it gives each copy those raster effects ([`copied_container`]).
|
||||
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !is_container(n) {
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
|
||||
return Some(copied_container(doc, n, t));
|
||||
}
|
||||
let pathfinder = has_pathfinder(n);
|
||||
let fx = crate::reshape::geometry_effects(n);
|
||||
let paint = has_own_paint(n);
|
||||
@@ -853,7 +869,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
{
|
||||
// The members' raster effects then follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
@@ -885,6 +905,63 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
|
||||
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
|
||||
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
|
||||
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
|
||||
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
|
||||
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
|
||||
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
|
||||
/// and locked as their containers were.
|
||||
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
|
||||
let mut m = n.clone();
|
||||
let mut guides = vec![];
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
let mut source = m.clone();
|
||||
source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec();
|
||||
// With no geometry effect before the Transform effect, `evaluate_container` leaves the members'
|
||||
// own effects live (it only paints the group's own fills and strokes): the members are drawn
|
||||
// first, so their effects apply before the copies are made.
|
||||
if crate::reshape::geometry_effects(&source).is_empty() {
|
||||
source = crate::reshape::outlined_members(doc, &source);
|
||||
// The members' raster effects follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut source);
|
||||
}
|
||||
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
|
||||
let mut p = source.clone();
|
||||
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
|
||||
p
|
||||
});
|
||||
// The piece is one copy: the transparency, opacity mask and guides stay on the art.
|
||||
piece.name = None;
|
||||
piece.visible = true;
|
||||
piece.locked = false;
|
||||
(piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false);
|
||||
piece.extras_mut().mask = None;
|
||||
// The copies are made about the piece's bounds, measured first: a layer leaves its hidden
|
||||
// members out of them, and a group does not.
|
||||
let bounds = piece.geometric_bounds();
|
||||
// A layer's copies are groups in it.
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut piece.kind {
|
||||
piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip };
|
||||
}
|
||||
let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds);
|
||||
let copies = art.children().cloned().unwrap_or_default();
|
||||
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind {
|
||||
*children = copies;
|
||||
*clip = false;
|
||||
}
|
||||
m.appearance.items.clear();
|
||||
m.appearance.contents_index = None;
|
||||
m.appearance.effects = effects;
|
||||
if let Some(ch) = m.children_mut() {
|
||||
ch.extend(guides);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
|
||||
use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect, shapes};
|
||||
|
||||
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
|
||||
@@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
|
||||
assert_eq!(fill.paint.color(), Some(yellow));
|
||||
}
|
||||
|
||||
/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member
|
||||
/// whose only fill is hidden does not take part.
|
||||
#[test]
|
||||
fn trap_skips_a_hidden_fill() {
|
||||
let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0);
|
||||
let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0);
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
hidden.visible = false;
|
||||
let trap = |members: Vec<Arc<Node>>| {
|
||||
let mut g = Node::group(NodeId(10), members);
|
||||
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
|
||||
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
|
||||
pathfinder_children(None, &g, None).unwrap()
|
||||
};
|
||||
let mut covered = (*sq(1, 0.0, yellow)).clone();
|
||||
covered.appearance.items.push(AppearanceItem::Fill(hidden.clone()));
|
||||
let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]);
|
||||
assert_eq!(out.len(), 3, "both squares and one trap");
|
||||
assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow));
|
||||
let only_hidden = Node::path(
|
||||
NodeId(1),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)),
|
||||
Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() },
|
||||
);
|
||||
assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() {
|
||||
let mut g = two_overlapping_cmyk_squares();
|
||||
@@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
|
||||
assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}");
|
||||
}
|
||||
|
||||
/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color.
|
||||
#[test]
|
||||
fn mixes_skip_a_hidden_fill() {
|
||||
for effect in ["pathfinder.softMix", "pathfinder.hardMix"] {
|
||||
let mut plain = two_overlapping_cmyk_squares();
|
||||
plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true });
|
||||
let mut covered = plain.clone();
|
||||
let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") };
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
hidden.visible = false;
|
||||
for c in children.iter_mut() {
|
||||
Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone()));
|
||||
}
|
||||
assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend
|
||||
/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill
|
||||
/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes.
|
||||
#[test]
|
||||
fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() {
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let mut fill = FillLayer::new(red.clone());
|
||||
(fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true);
|
||||
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
hidden.visible = false;
|
||||
let mut stroke = StrokeLayer::new(blue.clone(), 2.0);
|
||||
(stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true);
|
||||
let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0);
|
||||
hidden_stroke.visible = false;
|
||||
let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0);
|
||||
let look = |items: Vec<AppearanceItem>| Appearance { items, ..Default::default() };
|
||||
let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke);
|
||||
let cases = [
|
||||
(look(vec![f(fill.clone())]), Some(red.clone())),
|
||||
(look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())),
|
||||
(look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())),
|
||||
(look(vec![f(hidden.clone())]), None),
|
||||
(look(vec![s(stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())),
|
||||
(look(vec![s(zero_stroke)]), None),
|
||||
];
|
||||
for (appearance, want) in cases {
|
||||
let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance));
|
||||
let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]);
|
||||
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true });
|
||||
let out = pathfinder_children(None, &g, None).unwrap();
|
||||
let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect();
|
||||
assert!(!edges.is_empty(), "{out:#?}");
|
||||
for n in edges {
|
||||
let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") };
|
||||
match &want {
|
||||
Some(paint) => {
|
||||
assert_eq!(&s.paint, paint);
|
||||
assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}");
|
||||
}
|
||||
None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_modes_follow_the_pathfinder_panel() {
|
||||
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
|
||||
|
||||
@@ -82,13 +82,13 @@ pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_objec
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
|
||||
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
|
||||
outline_text, paint_type_piece, reshape,
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
|
||||
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
|
||||
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
@@ -103,8 +103,8 @@ pub use solids::{
|
||||
with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
|
||||
rename_appearance_graphic_symbol,
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
|
||||
graphics_reshaped_after, rename_appearance_graphic_symbol,
|
||||
};
|
||||
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
|
||||
pub use svg_filter::SVG_FILTER;
|
||||
|
||||
@@ -168,6 +168,62 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
|
||||
if sign < 0.0 { footprint.reverse_subpaths() } else { footprint }
|
||||
}
|
||||
|
||||
/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges.
|
||||
const SEAMED_FILL_EDGES: usize = 256;
|
||||
|
||||
/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an
|
||||
/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a
|
||||
/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`]
|
||||
/// finite edges, with an area, and with no two edges that are not neighbors touching: only there
|
||||
/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for
|
||||
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
|
||||
/// than the facet.
|
||||
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
|
||||
use kurbo::{PathEl, Point, Shape};
|
||||
if !(seam.is_finite() && seam > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let bez = path.to_bezpath();
|
||||
let mut elements = bez.elements().iter();
|
||||
let Some(PathEl::MoveTo(first)) = elements.next() else { return None };
|
||||
let mut points = vec![*first];
|
||||
let mut closed = false;
|
||||
for el in elements {
|
||||
match el {
|
||||
PathEl::LineTo(p) if !closed => points.push(*p),
|
||||
PathEl::ClosePath if !closed => closed = true,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
if points.len() > 1 && points.first() == points.last() {
|
||||
points.pop();
|
||||
}
|
||||
let area = bez.area().abs();
|
||||
if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a);
|
||||
let touch = |a: Point, b: Point, c: Point, d: Point| {
|
||||
let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y);
|
||||
boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0
|
||||
};
|
||||
let n = points.len();
|
||||
let edge = |i: usize| (points[i], points[(i + 1) % n]);
|
||||
for i in 0..n {
|
||||
for j in i + 2..n {
|
||||
if i == 0 && j == n - 1 {
|
||||
continue;
|
||||
}
|
||||
let ((a, b), (c, d)) = (edge(i), edge(j));
|
||||
if touch(a, b, c, d) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let fill = footprint(&bez, seam);
|
||||
(fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
|
||||
}
|
||||
|
||||
/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same
|
||||
/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets'
|
||||
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
|
||||
@@ -175,6 +231,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
|
||||
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
|
||||
/// in a clip of its footprint, neither with an opacity mask.
|
||||
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
let (clip, mut underlay) = underlay(id, faces)?;
|
||||
underlay.extend(faces.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
}
|
||||
|
||||
/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to,
|
||||
/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same
|
||||
/// conditions as [`sealed`].
|
||||
pub(crate) fn underlay(
|
||||
id: vectorcraft_doc::NodeId,
|
||||
faces: &[std::sync::Arc<vectorcraft_doc::Node>],
|
||||
) -> Option<(vectorcraft_doc::Node, Vec<std::sync::Arc<vectorcraft_doc::Node>>)> {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
let mut outline = vectorcraft_geom::BezPath::new();
|
||||
@@ -207,15 +277,15 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vector
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default());
|
||||
underlay.extend(faces.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay))
|
||||
}
|
||||
|
||||
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
|
||||
/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a
|
||||
/// shared edge is opaque in that channel's own light before the channels are screened together;
|
||||
/// the black backdrop shows only outside the surface, which the clip removes.
|
||||
/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the
|
||||
/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam
|
||||
/// stroke where that is `None`.
|
||||
pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node {
|
||||
use kurbo::Shape;
|
||||
use std::sync::Arc;
|
||||
@@ -239,6 +309,8 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
|
||||
let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default());
|
||||
let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
|
||||
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
|
||||
let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let exact: Vec<Option<PathData>> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect();
|
||||
let channels = (0..3)
|
||||
.map(|channel| {
|
||||
let mut color = [0.0; 3];
|
||||
@@ -274,7 +346,17 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
|
||||
};
|
||||
let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))];
|
||||
children.extend(draw(|_| UNDERLAY_SEAM));
|
||||
children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75)));
|
||||
children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| {
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))];
|
||||
let path = match fill {
|
||||
Some(fill) => fill.clone(),
|
||||
None => {
|
||||
items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face))));
|
||||
face.path()
|
||||
}
|
||||
};
|
||||
Arc::new(Node::path(id, path, Appearance { items, ..Default::default() }))
|
||||
}));
|
||||
let mut group = Node::group(id, children);
|
||||
group.isolate = true;
|
||||
group.blend = BlendMode::Screen;
|
||||
@@ -321,6 +403,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
|
||||
(base, transparent.then_some(mask))
|
||||
}
|
||||
|
||||
/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient
|
||||
/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the
|
||||
/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement.
|
||||
/// An opaque gradient is returned as [`opaque_paint`] returns it.
|
||||
pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option<Paint>) {
|
||||
let (base, mask) = opaque_paint(paint);
|
||||
if mask.is_none() || !matches!(paint, Paint::Gradient(_)) {
|
||||
return (base, mask);
|
||||
}
|
||||
let mut pinned = paint.clone();
|
||||
if let Paint::Gradient(g) = &mut pinned {
|
||||
g.pin(bounds().inflate(1.0, 1.0));
|
||||
}
|
||||
opaque_paint(&pinned)
|
||||
}
|
||||
|
||||
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
@@ -501,4 +599,65 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
|
||||
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
|
||||
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
|
||||
/// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none.
|
||||
#[test]
|
||||
fn seamed_fill_covers_a_polygon_and_its_seam_once() {
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_geom::BezPath;
|
||||
let polygon = |points: &[(f64, f64)]| {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(points[0]);
|
||||
for p in &points[1..] {
|
||||
bp.line_to(*p);
|
||||
}
|
||||
bp.close_path();
|
||||
bp
|
||||
};
|
||||
let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0;
|
||||
let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)];
|
||||
let mut reversed = notched;
|
||||
reversed.reverse();
|
||||
for points in [¬ched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] {
|
||||
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon");
|
||||
let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count();
|
||||
assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours");
|
||||
for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] {
|
||||
assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})");
|
||||
}
|
||||
for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] {
|
||||
assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})");
|
||||
}
|
||||
}
|
||||
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(¬ched)), 0.75).unwrap();
|
||||
assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam");
|
||||
assert!(!covers(&fill, 5.0, 8.0), "the notch stays open");
|
||||
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
|
||||
let mut holed = square.clone();
|
||||
holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter());
|
||||
let mut curved = BezPath::new();
|
||||
curved.move_to((0.0, 0.0));
|
||||
curved.quad_to((5.0, -5.0), (10.0, 0.0));
|
||||
curved.line_to((5.0, 10.0));
|
||||
curved.close_path();
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((0.0, 0.0));
|
||||
open.line_to((10.0, 0.0));
|
||||
open.line_to((10.0, 10.0));
|
||||
for (name, path, seam) in [
|
||||
("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75),
|
||||
("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75),
|
||||
("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75),
|
||||
("hole", holed, 0.75),
|
||||
("curve", curved, 0.75),
|
||||
("open", open, 0.75),
|
||||
("no seam", square.clone(), 0.0),
|
||||
("endless seam", square, f64::INFINITY),
|
||||
] {
|
||||
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
-2
@@ -29,6 +29,8 @@ mod sketch_ink;
|
||||
mod texture;
|
||||
mod video;
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
@@ -332,6 +334,9 @@ pub struct PixelSpace {
|
||||
pub extent: f64,
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angle parameters with their defaults (degrees).
|
||||
const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)];
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
let quality = |levels: [(&str, u32); 3], default: u32| {
|
||||
@@ -565,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
},
|
||||
"pixelate.colorHalftone" => PixelFx::ColorHalftone {
|
||||
max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0),
|
||||
angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]
|
||||
.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
},
|
||||
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
|
||||
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
|
||||
@@ -855,6 +859,113 @@ fn pick<T: Clone>(table: &[(&str, &str)], all: &[T], value: &str, default: T) ->
|
||||
table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone())
|
||||
}
|
||||
|
||||
/// The shortest that a direction's unit vector may become under a Transform effect and still give
|
||||
/// a direction ([`turned_directions`]).
|
||||
const MIN_TURNED: f64 = 1e-9;
|
||||
|
||||
/// How close (radians) two directions' angles to a turned direction must be to count as equally
|
||||
/// near ([`nearest`]).
|
||||
const TIE: f64 = 1e-9;
|
||||
|
||||
/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction
|
||||
/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the
|
||||
/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke
|
||||
/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are
|
||||
/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn,
|
||||
/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal)
|
||||
/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays
|
||||
/// as it is. Empty for filters with no such parameter.
|
||||
pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> {
|
||||
enum Kind {
|
||||
Light(&'static str),
|
||||
Stroke,
|
||||
Screens,
|
||||
}
|
||||
let kind = match id {
|
||||
"sketch.basRelief" => Kind::Light("bottom"),
|
||||
"artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"),
|
||||
"brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke,
|
||||
"pixelate.colorHalftone" => Kind::Screens,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let p = crate::merged_params(id, p);
|
||||
match kind {
|
||||
Kind::Light(default) => {
|
||||
let light = Light::parse(text(&p, "lightDirection", default));
|
||||
snapped(&Light::ALL, Light::toward, light, a, later, false)
|
||||
.and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t))
|
||||
.map(|name| vec![("lightDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
Kind::Stroke => {
|
||||
let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal"));
|
||||
snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true)
|
||||
.and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t))
|
||||
.map(|name| vec![("strokeDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
// A screen at θ° runs along (cos θ, −sin θ) on the page (y down).
|
||||
Kind::Screens => SCREEN_ANGLES
|
||||
.iter()
|
||||
.filter_map(|&(key, default)| {
|
||||
let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians();
|
||||
let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?;
|
||||
let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6;
|
||||
Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0)))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction.
|
||||
fn mapped(a: Affine, v: Vec2) -> Option<Vec2> {
|
||||
let w = (a * v.to_point()) - (a * Point::ORIGIN);
|
||||
(w.is_finite() && w.hypot() > MIN_TURNED).then_some(w)
|
||||
}
|
||||
|
||||
/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to
|
||||
/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and
|
||||
/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to
|
||||
/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is
|
||||
/// rounded once. `None` when `a` takes `from` to no direction.
|
||||
fn snapped<T: Copy + PartialEq>(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option<T> {
|
||||
let v = mapped(a, dir(from))?;
|
||||
let turned = nearest(all, dir, v, axis)?;
|
||||
if later == Affine::IDENTITY {
|
||||
return Some(turned);
|
||||
}
|
||||
let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) };
|
||||
let fits: Vec<T> = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect();
|
||||
nearest(&fits, dir, v, axis).or(Some(turned))
|
||||
}
|
||||
|
||||
/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle,
|
||||
/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one
|
||||
/// clockwise of `v` on the page.
|
||||
fn nearest<T: Copy>(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option<T> {
|
||||
let period = if axis { PI } else { TAU };
|
||||
let at = v.atan2();
|
||||
let mut best: Option<(T, f64)> = None;
|
||||
for &t in all {
|
||||
// How far clockwise of `v` the entry lies, within half a period either way.
|
||||
let d = (dir(t).atan2() - at).rem_euclid(period);
|
||||
let d = if d > period / 2.0 { d - period } else { d };
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b),
|
||||
};
|
||||
if better {
|
||||
best = Some((t, d));
|
||||
}
|
||||
}
|
||||
best.map(|(t, _)| t)
|
||||
}
|
||||
|
||||
/// The value in `table` of entry `t` of `all` (the same order).
|
||||
fn name_of<T: PartialEq>(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> {
|
||||
table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v)
|
||||
}
|
||||
|
||||
/// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty).
|
||||
fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> {
|
||||
let (px, rest) = data.as_chunks_mut::<4>();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub enum StrokeDirection {
|
||||
}
|
||||
|
||||
impl StrokeDirection {
|
||||
const ALL: [StrokeDirection; 4] =
|
||||
pub(super) const ALL: [StrokeDirection; 4] =
|
||||
[StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical];
|
||||
|
||||
/// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal
|
||||
@@ -53,7 +53,7 @@ impl StrokeDirection {
|
||||
}
|
||||
|
||||
/// The unit vector along the strokes (document axes, y down).
|
||||
fn along(self) -> Vec2 {
|
||||
pub(super) fn along(self) -> Vec2 {
|
||||
match self {
|
||||
StrokeDirection::RightDiagonal => RIGHT,
|
||||
StrokeDirection::Horizontal => Vec2::new(1.0, 0.0),
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
//! lies one pixel per point at 100 %, centered on the object's center and repeated in both
|
||||
//! directions.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
@@ -85,9 +84,15 @@ impl LoadedTexture {
|
||||
/// Its [`TEXTURE_IMAGE`] value: the gray levels as a grayscale PNG, base64; `None` when the
|
||||
/// PNG can't be written.
|
||||
pub fn to_stored(&self) -> Option<String> {
|
||||
let img = image::GrayImage::from_raw(self.width, self.height, self.gray.clone())?;
|
||||
let mut png = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
self.width,
|
||||
self.height,
|
||||
craft_image_codecs::ChannelLayout::Gray,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
self.gray.clone(),
|
||||
)
|
||||
.ok()?;
|
||||
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
|
||||
Some(base64_encode(&png))
|
||||
}
|
||||
|
||||
@@ -95,21 +100,38 @@ impl LoadedTexture {
|
||||
/// `None` when `png` isn't a PNG or holds no pixels.
|
||||
/// `None` too when its gray levels would take the live textures past [`MAX_LIVE`].
|
||||
fn from_png(png: &[u8]) -> Option<Self> {
|
||||
let reader = || {
|
||||
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
reader
|
||||
};
|
||||
let (w, h) = reader().into_dimensions().ok()?;
|
||||
let (w, h) = Self::png_ihdr_size(png)?;
|
||||
let gray = (w as usize).checked_mul(h as usize)?;
|
||||
if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE {
|
||||
return None;
|
||||
}
|
||||
let img = reader().decode().ok()?.to_luma8();
|
||||
let mut opts = craft_image_codecs::DecodeOptions::default();
|
||||
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
|
||||
// The codec default caps each side at 2^18; a stored texture can be longer than that and
|
||||
// still fit the live and allocation budgets.
|
||||
opts.limits.max_width = u32::MAX;
|
||||
opts.limits.max_height = u32::MAX;
|
||||
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).ok()?;
|
||||
let (width, height) = img.dimensions();
|
||||
(width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw()))
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
|
||||
let luma = match (img.layout(), img.sample_type()) {
|
||||
(L::Gray, S::U8) => img.into_data(),
|
||||
_ => image::RgbaImage::from_raw(width, height, img.to_rgba8()).map(image::DynamicImage::ImageRgba8)?.into_luma8().into_raw(),
|
||||
};
|
||||
Some(Self::new(width, height, luma))
|
||||
}
|
||||
|
||||
/// Read `(width, height)` from a PNG's IHDR chunk without decoding pixels.
|
||||
fn png_ihdr_size(png: &[u8]) -> Option<(u32, u32)> {
|
||||
if png.len() < 24 || &png[..8] != b"\x89PNG\r\n\x1a\n" || &png[12..16] != b"IHDR" {
|
||||
return None;
|
||||
}
|
||||
let w = u32::from_be_bytes(png[16..20].try_into().ok()?);
|
||||
let h = u32::from_be_bytes(png[20..24].try_into().ok()?);
|
||||
Some((w, h))
|
||||
}
|
||||
|
||||
/// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray
|
||||
|
||||
@@ -1704,6 +1704,14 @@ fn a_loaded_texture_is_its_gray_over_middle_gray() {
|
||||
assert!(texture("not base64!").is_none() && texture("aGVsbG8=").is_none(), "base64 of a PNG only");
|
||||
}
|
||||
|
||||
/// A stored texture longer than the codec's default 2^18-pixel side still reads back.
|
||||
#[test]
|
||||
fn a_stored_texture_longer_than_the_codec_default_side_reads_back() {
|
||||
let t = LoadedTexture::from_rgba(262_145, 1, &vec![128; 262_145 * 4]).and_then(|t| t.to_stored()).unwrap();
|
||||
let loaded = texture(&t).unwrap();
|
||||
assert_eq!(loaded.size(), (262_145, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glass_bends_the_image_by_a_loaded_texture() {
|
||||
let (w, h) = (48, 40);
|
||||
|
||||
@@ -137,7 +137,7 @@ pub enum Light {
|
||||
}
|
||||
|
||||
impl Light {
|
||||
const ALL: [Light; 8] =
|
||||
pub(super) const ALL: [Light; 8] =
|
||||
[Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight];
|
||||
|
||||
/// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects.
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects.
|
||||
//!
|
||||
//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path
|
||||
//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects
|
||||
@@ -11,12 +11,15 @@
|
||||
//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or
|
||||
//! layer whose clipping path has strokes with geometry effects is given as that path's geometry
|
||||
//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`],
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve,
|
||||
//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with
|
||||
//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and
|
||||
//! marquees use, leaves 3D effects unprojected. [`bounds_of`],
|
||||
//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes
|
||||
//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and
|
||||
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
|
||||
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
|
||||
//! with its geometry effects, and the other instances in it are measured without them.
|
||||
//! with its geometry and 3D effects, and the other instances in it are measured without them.
|
||||
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
|
||||
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
|
||||
|
||||
@@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
|
||||
use crate::group::has_own_paint;
|
||||
use crate::reshape::{geometry_effects, leaf_geometry};
|
||||
use crate::{
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
|
||||
needs_outline, outline_art, paints, reshape,
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve,
|
||||
has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in,
|
||||
};
|
||||
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
|
||||
/// past it, the other instances in the object are measured without geometry effects.
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects:
|
||||
/// past it, the other instances in the object are measured without those effects.
|
||||
const MAX_INSTANCES: usize = 4096;
|
||||
|
||||
/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else
|
||||
@@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::
|
||||
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
|
||||
}
|
||||
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
|
||||
/// [`Node::visual_bounds_with`].
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected,
|
||||
/// else [`Node::visual_bounds_with`].
|
||||
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
Drawn::new(symbols).visual_bounds(n)
|
||||
}
|
||||
@@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances
|
||||
/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a
|
||||
/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a
|
||||
/// group of its clipping path without strokes and the drawn art of the path's strokes, when they
|
||||
/// have one. `None` when no geometry effect in `n` changes what it draws.
|
||||
/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or
|
||||
/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group
|
||||
/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's
|
||||
/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps
|
||||
/// its own id. `None` when no geometry effect in `n` changes what it draws.
|
||||
pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
|
||||
Drawn::new(symbols).drawn_art(n)
|
||||
Drawn::without_3d(symbols).drawn_art(n)
|
||||
}
|
||||
|
||||
/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol
|
||||
/// instance in `n` counts when its symbol's art has a geometry effect.
|
||||
/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a
|
||||
/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its
|
||||
/// symbol's art has geometry or 3D effects.
|
||||
pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
Drawn::new(symbols).draws_geometry(n)
|
||||
}
|
||||
|
||||
/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name,
|
||||
/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name,
|
||||
/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]).
|
||||
struct Drawn<'s, 'd> {
|
||||
symbols: &'s SymbolBoxes<'d>,
|
||||
draws: RefCell<HashMap<String, bool>>,
|
||||
left: Cell<usize>,
|
||||
three_d: bool,
|
||||
}
|
||||
|
||||
impl<'s, 'd> Drawn<'s, 'd> {
|
||||
fn new(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) }
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true }
|
||||
}
|
||||
|
||||
/// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]).
|
||||
fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { three_d: false, ..Self::new(symbols) }
|
||||
}
|
||||
|
||||
/// Whether `n` has a 3D effect of its own that this measurement projects.
|
||||
fn projects(&self, n: &Node) -> bool {
|
||||
self.three_d && (has_revolve(n) || has_solid(n))
|
||||
}
|
||||
|
||||
/// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object.
|
||||
@@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found
|
||||
|| self.projects(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol),
|
||||
_ => reshapes(c),
|
||||
@@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
d
|
||||
}
|
||||
|
||||
/// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the
|
||||
/// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that
|
||||
/// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from
|
||||
/// those effects in its symbol's art, with the instance's appearance overrides applied.
|
||||
/// A group or layer with fills or strokes of its own that
|
||||
/// paint, around members with geometry effects, is evaluated too: its fills and strokes paint
|
||||
/// the members' geometry before their effects. A blend, envelope or repeat whose objects have
|
||||
/// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and
|
||||
/// the objects in its evaluated art keep their geometry effects. `None` when it has none, and
|
||||
/// for a symbol instance past [`MAX_INSTANCES`].
|
||||
fn own_art(&self, n: &Node) -> Option<Node> {
|
||||
let doc = Some(self.symbols.document());
|
||||
// A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built.
|
||||
let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n);
|
||||
if counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
if self.three_d
|
||||
&& let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n))
|
||||
{
|
||||
// The builders retain later geometry on the projected group. Measure it after that
|
||||
// geometry too; item-level effects are handled by the ordinary member traversal.
|
||||
return Some(self.own_art(&art).unwrap_or(art));
|
||||
}
|
||||
let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c)));
|
||||
let painted = || has_own_paint(n) && inner();
|
||||
match &n.kind {
|
||||
@@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
|
||||
return None;
|
||||
}
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
if !counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
let art = self.symbols.measure_art(symbol, Arc::clone)?;
|
||||
// Paint overrides can remove a projected surface or change its stroke outline.
|
||||
let art =
|
||||
if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) };
|
||||
// An instance in perspective is projected by `reshape`.
|
||||
let doc = Some(self.symbols.document());
|
||||
reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art)))
|
||||
|
||||
@@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
|
||||
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
|
||||
let list = out.get_or_insert_with(|| effects.to_vec());
|
||||
if let Some(e) = list.get_mut(i) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
out.map_or(Cow::Borrowed(effects), Cow::Owned)
|
||||
@@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
|
||||
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
|
||||
let mut changed = false;
|
||||
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
@@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine)
|
||||
let det = b.determinant();
|
||||
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
|
||||
if c.is_finite() {
|
||||
follow_transform(e, c);
|
||||
follow_transform(e, c, b);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -608,21 +608,36 @@ fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
|
||||
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
|
||||
/// instead of the art it is made from: the indices of the visible Transform effects listed after
|
||||
/// it that move the art, when from the first visible Transform effect after it on every visible
|
||||
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
|
||||
/// in the order they are listed, so the image is made of the art before those Transform effects
|
||||
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
|
||||
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
|
||||
/// on.
|
||||
/// it that move or copy the art, when from the first visible Transform effect after it on every
|
||||
/// visible effect is a Transform effect that does not move at random, and at most one of them makes
|
||||
/// copies. Effects apply in the order they are listed, so the image is made of the art before those
|
||||
/// Transform effects and moves with them, its pixel grid and room around the art included; each copy
|
||||
/// carries the same image ([`stage_maps`]). `None` when there is no such Transform effect, or the
|
||||
/// effects after the Rasterize effect hold anything else from there on.
|
||||
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
|
||||
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
|
||||
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
|
||||
let mut at = vec![];
|
||||
let mut copying = false;
|
||||
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
|
||||
if e.id != "distort.transform" || transform_step(e).is_none() {
|
||||
if e.id != "distort.transform" {
|
||||
return None;
|
||||
}
|
||||
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
if !flag(&p, "objects", true) {
|
||||
continue;
|
||||
}
|
||||
if flag(&p, "random", false) {
|
||||
return None;
|
||||
}
|
||||
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
|
||||
if copies > 0 {
|
||||
if copying {
|
||||
return None;
|
||||
}
|
||||
copying = true;
|
||||
}
|
||||
if copies > 0 || map != Affine::IDENTITY {
|
||||
at.push(i);
|
||||
}
|
||||
}
|
||||
@@ -641,22 +656,41 @@ pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
|
||||
/// The maps the Transform effects at `at` of `effects` ([`rasterize_stage`]) place the Rasterize
|
||||
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
|
||||
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
|
||||
/// last one outermost. `None` when `staged` is empty or the map is not a number.
|
||||
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
|
||||
/// last one outermost. A Transform effect with copies places the image once more for each copy
|
||||
/// the geometry pass makes, copy `k` through its map `k` times. The maps come in the order the
|
||||
/// images paint, the lowest first: the last copy lowest and the original on top, as copied objects
|
||||
/// stack. `None` when `staged` is empty or a map is not a number.
|
||||
pub fn stage_maps(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Vec<Affine>> {
|
||||
let mut cur = staged.clone();
|
||||
let mut b = staged.bounds()?;
|
||||
let mut map = Affine::IDENTITY;
|
||||
// The original's map first, then each copy's.
|
||||
let mut maps = vec![Affine::IDENTITY];
|
||||
for &i in at {
|
||||
let e = effects.get(i)?;
|
||||
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
|
||||
map = m * map;
|
||||
cur = cur.transformed(m);
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(b, &p, 0);
|
||||
if copies == 0 {
|
||||
maps.iter_mut().for_each(|x| *x = m * *x);
|
||||
cur = cur.transformed(m);
|
||||
} else {
|
||||
// As many copies as the geometry pass makes: it stops early past its limits.
|
||||
let next = crate::distort::transform(&cur, b, &p, 0);
|
||||
let made = (next.anchor_count() / cur.anchor_count().max(1)).saturating_sub(1);
|
||||
let placed = maps.clone();
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..made {
|
||||
xf = m * xf;
|
||||
maps.extend(placed.iter().map(|x| xf * *x));
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
map.is_finite().then_some(map)
|
||||
maps.reverse();
|
||||
maps.iter().all(|m| m.is_finite()).then_some(maps)
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
@@ -666,11 +700,44 @@ pub(crate) fn follows(id: &str) -> bool {
|
||||
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The linear part of the Transform effects of the groups and layers whose members are being
|
||||
/// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once
|
||||
/// the members are evaluated: the members' light and stroke directions are rounded for them as
|
||||
/// well ([`follow_transform`]).
|
||||
static LATER_GROUPS: std::cell::Cell<Affine> = const { std::cell::Cell::new(Affine::IDENTITY) };
|
||||
}
|
||||
|
||||
/// The Transform effects of a group or layer whose members are being evaluated before the group's
|
||||
/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped.
|
||||
pub(crate) struct LaterGroups(Affine);
|
||||
|
||||
impl LaterGroups {
|
||||
/// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]),
|
||||
/// to those the members will still go through.
|
||||
pub(crate) fn enter(owner: &[Effect]) -> Self {
|
||||
let was = LATER_GROUPS.with(|l| l.get());
|
||||
if let Some(step) = contents_step(owner) {
|
||||
LATER_GROUPS.with(|l| l.set(was * step));
|
||||
}
|
||||
LaterGroups(was)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LaterGroups {
|
||||
fn drop(&mut self) {
|
||||
LATER_GROUPS.with(|l| l.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
|
||||
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
|
||||
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
|
||||
/// `a`. Effects that [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`,
|
||||
/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with
|
||||
/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn,
|
||||
/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that
|
||||
/// [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine, later: Affine) {
|
||||
if !follows(&e.id) {
|
||||
return;
|
||||
}
|
||||
@@ -678,15 +745,22 @@ fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
|
||||
});
|
||||
let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later);
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
|
||||
crate::scale_effect(e, k);
|
||||
}
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
let mut set = |key: &str, value: Value| {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
}
|
||||
e.params["x"] = json!(o.x);
|
||||
e.params["y"] = json!(o.y);
|
||||
e.params[key] = value;
|
||||
};
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
set("x", json!(o.x));
|
||||
set("y", json!(o.y));
|
||||
}
|
||||
for (key, value) in turned {
|
||||
set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+445
-62
@@ -107,24 +107,84 @@ fn reaches_appearance(e: &Effect) -> bool {
|
||||
}
|
||||
|
||||
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
|
||||
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
|
||||
/// baked and expanded through that art ([`reshape`]).
|
||||
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`],
|
||||
/// [`has_copied_row_raster`]), or whose live-effect plug-ins paint what they return
|
||||
/// ([`has_painted_effects`])? It is drawn, baked and expanded through that art ([`reshape`]).
|
||||
pub fn has_transform_art(n: &Node) -> bool {
|
||||
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some()
|
||||
has_gradient_copies(n)
|
||||
|| has_layered_copies(n)
|
||||
|| has_transform_options(n)
|
||||
|| has_painted_effects(n)
|
||||
|| (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some())
|
||||
|| has_copied_row_raster(n)
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform
|
||||
/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index
|
||||
/// of the last visible Transform effect that makes copies, when a visible raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other
|
||||
/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for
|
||||
/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect
|
||||
/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of
|
||||
/// its own.
|
||||
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are
|
||||
/// carried by copies: one whose own effects list a Transform effect that makes copies after a
|
||||
/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes
|
||||
/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or
|
||||
/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`],
|
||||
/// [`follow_copies`]).
|
||||
pub fn has_copied_row_raster(n: &Node) -> bool {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
// Checked first: this runs for every object drawn.
|
||||
if !n.appearance.items.iter().any(follows_row_raster) {
|
||||
return false;
|
||||
}
|
||||
n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n)
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry a visible raster effect that follows a Transform effect
|
||||
/// ([`crate::raster::follows`])?
|
||||
fn follows_row_raster(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
}
|
||||
|
||||
/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries
|
||||
/// the raster effects listed before it: the index of the first visible Transform effect that makes
|
||||
/// copies (an earlier one that makes copies included) for which a visible raster effect that
|
||||
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible
|
||||
/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it
|
||||
/// that makes copies or moves at random holds those raster effects back
|
||||
/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it
|
||||
/// and before a later Transform effect that makes copies or moves at random, which would apply to
|
||||
/// the art that raster effect paints.
|
||||
fn copied_row_raster_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copying =
|
||||
|e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0;
|
||||
// Is a visible raster effect in `rest` listed before its last Transform effect that holds back?
|
||||
let raster_held = |rest: &[Effect]| {
|
||||
rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id)))
|
||||
};
|
||||
(0..fx.len()).find(|&t| {
|
||||
let before = &fx[..t];
|
||||
copying(&fx[t])
|
||||
&& !raster_held(&fx[t + 1..])
|
||||
&& crate::raster::held_back(before) == 0
|
||||
&& before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so
|
||||
/// that each copy of a Transform effect carries the raster effects listed before that effect
|
||||
/// ([`copied_raster_art`]): the index of the last visible Transform effect that makes copies, when
|
||||
/// a visible raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed
|
||||
/// before it and every other visible effect before it is a geometry effect or such a raster effect.
|
||||
/// `None` otherwise, and for an object with a linked opacity mask, a 3D effect, Crop Marks, Vector
|
||||
/// Halftone, a live-effect plug-in that paints what it returns, a fill or stroke that paints with
|
||||
/// geometry effects of its own, or (type, images and symbol instances) a perspective.
|
||||
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
match n.kind {
|
||||
NodeKind::Path { guide: false, clipping: false, .. }
|
||||
| NodeKind::Compound { .. }
|
||||
| NodeKind::Text(_)
|
||||
| NodeKind::Image(_)
|
||||
| NodeKind::SymbolInstance { .. } => {}
|
||||
_ => return None,
|
||||
}
|
||||
let effects = &n.appearance.effects;
|
||||
// Checked first: this runs for every object drawn.
|
||||
@@ -143,10 +203,115 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
|
||||
|| crate::has_crop_marks(n)
|
||||
|| crate::addons::halftone::has_halftone(n)
|
||||
|| has_painted_effects(n)
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()));
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
|
||||
|| n.projection().is_some();
|
||||
(carried && !excluded).then_some(t)
|
||||
}
|
||||
|
||||
/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect
|
||||
/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of
|
||||
/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes
|
||||
/// copies, when a visible raster effect that follows a Transform effect is listed before it and
|
||||
/// every other visible effect before it is a geometry effect or such a raster effect. `None`
|
||||
/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a
|
||||
/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints
|
||||
/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own.
|
||||
pub(crate) fn copied_container_raster_at(n: &Node) -> Option<usize> {
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) {
|
||||
return None;
|
||||
}
|
||||
let effects = &n.appearance.effects;
|
||||
// Checked first: this runs for every group and layer drawn.
|
||||
if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
|
||||
return None;
|
||||
}
|
||||
let t = effects.iter().rposition(|e| {
|
||||
e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0
|
||||
})?;
|
||||
let before = effects.get(..t)?;
|
||||
let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
|
||||
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id));
|
||||
let excluded = n.is_compound_shape()
|
||||
|| n.extras().shaper.is_some()
|
||||
|| crate::has_pathfinder(n)
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
|| crate::has_solid(n)
|
||||
|| crate::has_revolve(n)
|
||||
|| crate::has_crop_marks(n)
|
||||
|| crate::addons::halftone::has_halftone(n)
|
||||
|| effects.iter().any(|e| painted_plugin(e).is_some())
|
||||
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
|
||||
|| n.projection().is_some();
|
||||
(carried && !excluded).then_some(t)
|
||||
}
|
||||
|
||||
/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`,
|
||||
/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster
|
||||
/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding
|
||||
/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved,
|
||||
/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale
|
||||
/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect
|
||||
/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as
|
||||
/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies
|
||||
/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have
|
||||
/// their raster effects moved, turned, reflected and scaled with each copy in the same way
|
||||
/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art
|
||||
/// and the raster effects from `t` on, as they ran.
|
||||
pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option<Rect>) -> (Node, Vec<Effect>) {
|
||||
let rest = n.appearance.effects.get(t..).unwrap_or_default();
|
||||
let own = piece.appearance.effects.clone();
|
||||
let original = piece.clone();
|
||||
let mut art = Node::group(n.id, vec![Arc::new(piece)]);
|
||||
if let (Some(e), Some(bounds)) = (rest.first(), bounds) {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0);
|
||||
let max = Budget::EFFECTS.at_least(art_cost(&art));
|
||||
copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max);
|
||||
if let Some(children) = art.children_mut() {
|
||||
// The original is last, and each copy above it is mapped once more by `m`.
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
let mut a = Affine::IDENTITY;
|
||||
for (k, c) in children.iter_mut().rev().enumerate() {
|
||||
// Each copy is the piece in a group of its own: the piece takes its place.
|
||||
if let Some([one]) = c.children().map(Vec::as_slice) {
|
||||
*c = one.clone();
|
||||
}
|
||||
if k > 0 {
|
||||
a *= step;
|
||||
// Scale Strokes & Effects scaled the copy's own effects with it: they follow
|
||||
// its map from their values on the original instead.
|
||||
let copy = Arc::make_mut(c);
|
||||
copy.appearance.effects = own.clone();
|
||||
crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY);
|
||||
follow_carried(copy, &original, n.id, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc);
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
}
|
||||
let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
|
||||
(art, effects)
|
||||
}
|
||||
|
||||
/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a
|
||||
/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster
|
||||
/// effects of the matching members of `original`, the piece `copy` was made from, made to follow
|
||||
/// `a` ([`crate::raster::follow_contents`]).
|
||||
fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) {
|
||||
let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return };
|
||||
for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) {
|
||||
let c = Arc::make_mut(c);
|
||||
c.appearance.effects = w.appearance.effects.clone();
|
||||
crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY);
|
||||
follow_carried(c, w, id, a);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
|
||||
/// else `None`.
|
||||
fn painted_plugin(e: &Effect) -> Option<&str> {
|
||||
@@ -515,18 +680,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
|
||||
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
|
||||
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
|
||||
/// move with the type.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
|
||||
///
|
||||
/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give
|
||||
/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill,
|
||||
/// and the returned path is the area the run's stroke paints around `piece` in text space
|
||||
/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and
|
||||
/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run
|
||||
/// without a stroke.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option<Node> {
|
||||
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
|
||||
let mut ap = style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) };
|
||||
piece.appearance = ap.into();
|
||||
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
|
||||
piece.transform(xf, scaling);
|
||||
stroke.map(|mut s| {
|
||||
s.transform(xf, scaling);
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a
|
||||
/// reflection), without flattening?
|
||||
fn is_similarity(xf: Affine) -> bool {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let (x, y) = (a.hypot(b), c.hypot(d));
|
||||
let tol = 1e-9 * x.max(y);
|
||||
x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y)
|
||||
}
|
||||
|
||||
/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space),
|
||||
/// and returns the area it paints there as a path filled with its paint, opacity, blend mode,
|
||||
/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing.
|
||||
fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option<Node> {
|
||||
let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?;
|
||||
let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None };
|
||||
let path = PathData::from_bezpath(&piece.stroke_path()?);
|
||||
let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st);
|
||||
if region.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fill = vectorcraft_doc::FillLayer {
|
||||
opacity: st.opacity,
|
||||
blend: st.blend,
|
||||
effects: st.effects.clone(),
|
||||
overprint: st.overprint,
|
||||
..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill())
|
||||
};
|
||||
Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
|
||||
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
|
||||
/// outline with the object's items below the characters under them and the others over them, as
|
||||
/// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke
|
||||
/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to
|
||||
/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts
|
||||
/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to
|
||||
/// the layout's bounds in text space. The object's own unplaced gradients are fixed to the
|
||||
/// bounding box of those bounds in the document. The group is marked as type's outlines
|
||||
/// ([`vectorcraft_doc::NodeExtras::type_outlines`]).
|
||||
@@ -542,8 +751,9 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
continue;
|
||||
}
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
|
||||
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
children.push(Arc::new(piece));
|
||||
children.extend(stroke.map(Arc::new));
|
||||
}
|
||||
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
|
||||
let (below, above) = n.appearance.split_contents();
|
||||
@@ -845,6 +1055,16 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// Symbol instance `n` as plain art for Expand Appearance, with or without geometry effects: the
|
||||
/// art it places, reshaped by those effects when it has some, in the form [`expand_outlined`]
|
||||
/// gives. `None` for other kinds of objects and for an instance without `symbol_art`.
|
||||
pub fn instance_as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
return None;
|
||||
}
|
||||
as_art(doc, n, symbol_art)
|
||||
}
|
||||
|
||||
/// [`reshape`] without its checks (no geometry effects: just the art).
|
||||
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
|
||||
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
|
||||
@@ -876,7 +1096,8 @@ fn as_art_opts(
|
||||
apart: bool,
|
||||
) -> Option<Node> {
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n));
|
||||
let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart);
|
||||
return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
@@ -933,7 +1154,7 @@ fn as_art_opts(
|
||||
}
|
||||
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
|
||||
};
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
|
||||
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -971,23 +1192,39 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
|
||||
art
|
||||
}
|
||||
|
||||
/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the
|
||||
/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then
|
||||
/// copied by that Transform effect, each copy an object of its own carrying those raster effects
|
||||
/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry
|
||||
/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without
|
||||
/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do,
|
||||
/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an
|
||||
/// object of its own ([`copy_leaf`]).
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node {
|
||||
/// The art of `n` whose own effects split at `t` ([`copied_raster_at`]): the art the effects before
|
||||
/// the Transform effect at `t` make of `n`, with their raster effects, then copied by that
|
||||
/// Transform effect, each copy an object of its own carrying those raster effects moved, turned,
|
||||
/// reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry effects after
|
||||
/// it. The art keeps `n`'s id and carries the raster effects from `t` on, without `n`'s name,
|
||||
/// visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do, each with
|
||||
/// its raster effects. With `apart`, the Transform effects before `t` make each copy of a path an
|
||||
/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through
|
||||
/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame
|
||||
/// and an instance as its symbol's art, whose members take their own geometry effects first
|
||||
/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option<Node>) -> Option<Node> {
|
||||
let (before, rest) = n.appearance.effects.split_at(t);
|
||||
let mut source = n.clone();
|
||||
source.appearance.effects = before.to_vec();
|
||||
let piece = match copied_raster_at(&source) {
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart),
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?,
|
||||
None if needs_outline(&source) => {
|
||||
let mut art = outlined(&source)?;
|
||||
if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() {
|
||||
// The copying Transform effect reshapes what the symbol's members draw.
|
||||
crate::group::members_as_drawn(doc, &mut art);
|
||||
}
|
||||
art.name = None;
|
||||
art.visible = true;
|
||||
(art.opacity, art.blend, art.isolate, art.knockout_shape) = (1.0, Default::default(), false, false);
|
||||
art.extras_mut().mask = None;
|
||||
art
|
||||
}
|
||||
None => {
|
||||
let mut art = one_piece(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
let rows = has_copied_row_raster(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
@@ -1028,19 +1265,21 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) ->
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
}
|
||||
art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
|
||||
art
|
||||
Some(art)
|
||||
}
|
||||
|
||||
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
|
||||
/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]).
|
||||
/// on for a path, compound path, type, image or symbol instance whose copies each carry the raster
|
||||
/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do
|
||||
/// ([`copied_container_raster_at`]).
|
||||
pub fn outer_effects(n: &Node) -> &[Effect] {
|
||||
match copied_raster_at(n) {
|
||||
match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) {
|
||||
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
|
||||
None => &n.appearance.effects,
|
||||
}
|
||||
@@ -1074,7 +1313,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n));
|
||||
return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
@@ -1158,19 +1397,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
|
||||
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
|
||||
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
|
||||
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc);
|
||||
}
|
||||
|
||||
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
|
||||
/// strokes) follow the effects ([`crate::Carry`]).
|
||||
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
|
||||
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
|
||||
reshape_leaves_apart(art, fx, &[], budget, false, doc)
|
||||
reshape_leaves_apart(art, fx, &[], budget, (false, false), doc)
|
||||
}
|
||||
|
||||
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
|
||||
@@ -1191,7 +1430,10 @@ fn hoist_copies(art: &mut Node) {
|
||||
|
||||
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
|
||||
/// `apart`, a Transform effect's copies of each path are objects
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
|
||||
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`,
|
||||
/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect
|
||||
/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved,
|
||||
/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect
|
||||
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
|
||||
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
|
||||
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
|
||||
@@ -1202,7 +1444,14 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
|
||||
fn reshape_leaves_apart(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
(apart, rows): (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
return whole;
|
||||
@@ -1239,7 +1488,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held };
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
@@ -1283,6 +1532,7 @@ struct Step<'a> {
|
||||
seed: u64,
|
||||
effect: Option<usize>,
|
||||
apart: bool,
|
||||
rows: bool,
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
held: bool,
|
||||
@@ -1447,8 +1697,12 @@ impl Step<'_> {
|
||||
// make together; and Expand Appearance (`apart`) makes each copy an object.
|
||||
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
|
||||
// Each copy of a path with a linked mask carries the mask, moved with it.
|
||||
// With `rows`, each copy carries the raster effects of its fills and strokes,
|
||||
// following that copy's map.
|
||||
let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster);
|
||||
let separate = copies > 0
|
||||
&& (self.apart
|
||||
|| rows
|
||||
|| leaf.appearance.has_unplaced_gradient()
|
||||
|| leaf.appearance.has_placed_gradient()
|
||||
|| paints_copies_apart(&leaf.appearance, rule)
|
||||
@@ -1456,9 +1710,12 @@ impl Step<'_> {
|
||||
// The copies of a path replace it by a group of them, the path included.
|
||||
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
|
||||
if options.reach_appearance() {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None);
|
||||
*used = used.minus(before).plus(made);
|
||||
took |= moved;
|
||||
if moved && rows {
|
||||
follow_copies(leaf, map, None);
|
||||
}
|
||||
if moved {
|
||||
// With Transform Objects off the path stays, and its mask takes the
|
||||
// effect's stroke and pattern changes as its own art.
|
||||
@@ -1474,6 +1731,9 @@ impl Step<'_> {
|
||||
if separate {
|
||||
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
|
||||
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
|
||||
if rows {
|
||||
follow_copies(leaf, m, None);
|
||||
}
|
||||
*used = used.minus(before).plus(made);
|
||||
took = true;
|
||||
moved_ids.insert(leaf.id);
|
||||
@@ -1865,7 +2125,7 @@ fn transform_leaf(
|
||||
kept: Kept,
|
||||
) -> (Budget, bool) {
|
||||
let mut scaling = copy_scaling(options);
|
||||
if follows && copies == 0 {
|
||||
if follows {
|
||||
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
|
||||
}
|
||||
if !options.objects {
|
||||
@@ -2181,7 +2441,8 @@ fn paint_piece(
|
||||
|
||||
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
|
||||
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
|
||||
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`item_transform_options`]) or makes copies that carry the raster effects before it
|
||||
/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns
|
||||
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
|
||||
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
|
||||
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
|
||||
@@ -2198,9 +2459,20 @@ fn makes_piece(e: &Effect) -> bool {
|
||||
reaches_appearance(e) || painted_plugin(e).is_some()
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that [`makes_piece`]?
|
||||
/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the
|
||||
/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the
|
||||
/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first.
|
||||
fn piece_at(fx: &[Effect]) -> Option<usize> {
|
||||
let copied = copied_row_raster_at(fx);
|
||||
match fx.iter().position(makes_piece) {
|
||||
Some(at) => Some(copied.map_or(at, |t| t.min(at))),
|
||||
None => copied,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])?
|
||||
fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
crate::paints(item) && item.effects().iter().any(makes_piece)
|
||||
crate::paints(item) && piece_at(item.effects()).is_some()
|
||||
}
|
||||
|
||||
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
|
||||
@@ -2210,12 +2482,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
|
||||
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
|
||||
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
|
||||
/// pattern follow the map, and the raster effects before it that follow it take their followed
|
||||
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
|
||||
/// values ([`follow_piece`]), on each copy the values that copy's map gives them
|
||||
/// ([`follow_copies`]). The effects after it keep their values and apply to what it made
|
||||
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
|
||||
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
|
||||
/// stroke's own effects. The geometry effects after the Transform effect then
|
||||
/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry
|
||||
/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way,
|
||||
/// with neither option. The geometry effects after the Transform effect then
|
||||
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
|
||||
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
|
||||
/// effects stay on each of them, except that without either option the raster effects after a
|
||||
/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The
|
||||
/// other fills and strokes stay together on paths of the leaf's
|
||||
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
|
||||
/// what it has spent.
|
||||
///
|
||||
@@ -2261,7 +2538,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
|
||||
for (i, item) in original.appearance.items.iter().enumerate() {
|
||||
let fx = item.effects();
|
||||
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
|
||||
let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else {
|
||||
plain.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
@@ -2339,13 +2616,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
let after = kept_before.len();
|
||||
let keep = |k: usize| k >= after || !options.objects;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
let from = crate::raster::held_back(before);
|
||||
if moved && !held_later {
|
||||
// Each copy carries the raster effects before the Transform effect, following that copy's
|
||||
// map, unless a Transform effect before or after it holds them back.
|
||||
let copied = copies > 0 && !held_later && from == 0;
|
||||
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep)));
|
||||
*used = used.plus(made);
|
||||
if moved && copied {
|
||||
follow_copies(&mut p, map, Some(0..after));
|
||||
} else if moved && !held_later {
|
||||
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
|
||||
}
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
|
||||
// Without Transform Patterns and Scale Strokes & Effects, the raster effects after the
|
||||
// Transform effect paint once around all the copies, as they paint around the one path of
|
||||
// every copy.
|
||||
if copies > 0 && !options.reach_appearance() {
|
||||
lift_later_raster(&mut p, after);
|
||||
}
|
||||
pieces.push(Arc::new(p));
|
||||
}
|
||||
if !plain.is_empty() {
|
||||
@@ -2396,6 +2684,7 @@ fn transform_piece(
|
||||
count = count.max(item.effects().len());
|
||||
}
|
||||
});
|
||||
let outer = held;
|
||||
// The effects before a Transform effect among the piece's effects that makes copies or moves at
|
||||
// random are held back from the Transform effects before it too.
|
||||
let mut held = held;
|
||||
@@ -2416,7 +2705,7 @@ fn transform_piece(
|
||||
let from = held.min(j);
|
||||
let mut holds = false;
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
|
||||
let at = PieceStage { j, from, seed, bounds, doc, stage };
|
||||
let at = PieceStage { j, from, outer, seed, bounds, doc, stage };
|
||||
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
|
||||
// counts each path it became so, or `None` when it stays as it was.
|
||||
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
|
||||
@@ -2637,12 +2926,14 @@ thread_local! {
|
||||
|
||||
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
|
||||
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
|
||||
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
|
||||
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
|
||||
/// plug-in is listed by.
|
||||
/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the
|
||||
/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted
|
||||
/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is
|
||||
/// listed by.
|
||||
struct PieceStage<'a> {
|
||||
j: usize,
|
||||
from: usize,
|
||||
outer: usize,
|
||||
seed: u64,
|
||||
bounds: Rect,
|
||||
doc: Option<&'a Document>,
|
||||
@@ -2685,15 +2976,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
return paint_piece(leaf, &item, (appearance, index), (plugin, ¶ms), at.bounds, room, at.doc, Some(at.stage));
|
||||
}
|
||||
if reaches_appearance(e) {
|
||||
let copied = copies_carry(item.effects(), e, at);
|
||||
if reaches_appearance(e) || copied {
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
let (_, copies) = crate::distort::transform_map(at.bounds, ¶ms, at.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(at.bounds, ¶ms, at.seed);
|
||||
let j = at.j;
|
||||
let keep = |k: usize| k > j || (k < j && !options.objects);
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
|
||||
if moved {
|
||||
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep)));
|
||||
if moved && copied {
|
||||
// Each copy's raster effects before the Transform effect follow that copy's map. The
|
||||
// Transform effects before it have already moved them, so each run between two of
|
||||
// them follows on its own.
|
||||
let fx = item.effects();
|
||||
let mut start = 0;
|
||||
for k in 0..=j {
|
||||
if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") {
|
||||
if start < k {
|
||||
follow_copies(leaf, map, Some(start..k));
|
||||
}
|
||||
start = k + 1;
|
||||
}
|
||||
}
|
||||
} else if moved {
|
||||
follow_piece(leaf, was, at.from, e);
|
||||
}
|
||||
return Some(made);
|
||||
@@ -2718,6 +3024,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects
|
||||
/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's
|
||||
/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do
|
||||
/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible
|
||||
/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it,
|
||||
/// and no Transform effect that makes copies or moves at random holds those raster effects back:
|
||||
/// none before the piece's effects, none listed before it after such a raster effect, and none
|
||||
/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect
|
||||
/// before it must also be a geometry effect or such a raster effect, and no visible raster effect
|
||||
/// may be listed after it, as for [`copied_row_raster_at`].
|
||||
fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool {
|
||||
if !e.visible || e.id != "distort.transform" || at.outer > 0 {
|
||||
return false;
|
||||
}
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
if !crate::distort::TransformOptions::of(¶ms).objects || crate::distort::transform_map(Rect::ZERO, ¶ms, 0).1 == 0 {
|
||||
return false;
|
||||
}
|
||||
let before = fx.get(..at.j).unwrap_or_default();
|
||||
let after = fx.get(at.j + 1..).unwrap_or_default();
|
||||
if crate::raster::held_back(before) > 0
|
||||
|| !before.iter().any(|f| f.visible && crate::raster::follows(&f.id))
|
||||
|| after.iter().any(crate::raster::holds_back)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
reaches_appearance(e)
|
||||
|| (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id))
|
||||
&& !after.iter().any(|f| f.visible && crate::is_raster(&f.id)))
|
||||
}
|
||||
|
||||
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
|
||||
fn same_path(a: &Node, b: &Node) -> bool {
|
||||
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
@@ -2790,6 +3127,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills
|
||||
/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the
|
||||
/// copy `k` places below the original takes the linear part of `m` `k` times
|
||||
/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when
|
||||
/// given, is which of each fill's or stroke's effects follow; the others keep their values.
|
||||
fn follow_copies(leaf: &mut Node, m: Affine, range: Option<std::ops::Range<usize>>) {
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
let Some(children) = leaf.children_mut() else { return };
|
||||
let mut a = Affine::IDENTITY;
|
||||
for c in children.iter_mut().rev().skip(1) {
|
||||
a *= step;
|
||||
for item in &mut Arc::make_mut(c).appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
let fx = match &range {
|
||||
Some(r) => fx.get_mut(r.clone()).unwrap_or_default(),
|
||||
None => fx.as_mut_slice(),
|
||||
};
|
||||
crate::raster::follow_contents(fx, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`,
|
||||
/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint
|
||||
/// once around all of the copies. The other effects stay where they are.
|
||||
fn lift_later_raster(p: &mut Node, after: usize) {
|
||||
if p.children().is_none() {
|
||||
return;
|
||||
}
|
||||
let mut lifted: Option<Vec<Effect>> = None;
|
||||
for_each_leaf(p, &mut |l| {
|
||||
for item in &mut l.appearance.items {
|
||||
let fx = item.effects_mut();
|
||||
if fx.len() <= after {
|
||||
continue;
|
||||
}
|
||||
let (raster, other): (Vec<Effect>, Vec<Effect>) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id));
|
||||
fx.extend(other);
|
||||
lifted.get_or_insert(raster);
|
||||
}
|
||||
});
|
||||
if let Some(raster) = lifted {
|
||||
p.appearance.effects.extend(raster);
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
|
||||
/// order. A group inside one of them is part of it.
|
||||
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
|
||||
|
||||
+330
-51
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_geom::{FillRule, PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
@@ -105,6 +105,7 @@ pub fn revolve_options(p: &Value) -> Revolve {
|
||||
shade: flag(p, "shade", true),
|
||||
smooth_shading: true,
|
||||
cap_ends: flag(p, "cap", true),
|
||||
fill_rule: FillRule::NonZero,
|
||||
curve_samples: None,
|
||||
map_surface: false,
|
||||
}
|
||||
@@ -231,7 +232,7 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
|
||||
return Ok(());
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options).map(|_| ()))
|
||||
paths.into_iter().try_for_each(|path| caster.revolve(path, options.fill_rule, b, options).map(|_| ()))
|
||||
}
|
||||
|
||||
/// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of
|
||||
@@ -296,11 +297,35 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize {
|
||||
faces.saturating_mul(4).saturating_mul(paint_bytes(paint))
|
||||
}
|
||||
|
||||
/// Do Revolve's `options` light its surface with colored lights?
|
||||
fn colored(options: &Revolve) -> bool {
|
||||
options.light_color != [1.0; 3] || options.lights.is_some()
|
||||
}
|
||||
|
||||
/// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under
|
||||
/// colored lights (`colored`), in a solid color or a gradient, when a face takes a smooth light
|
||||
/// ramp ([`crate::lighting::rgb_gradient_art`], [`crate::lighting::gradient_art`],
|
||||
/// [`crate::lighting::smooth_paint`]). Not in a gradient with transparent stops: its composed faces
|
||||
/// carry its opacity mask, which the underlay does not take ([`crate::lighting::underlay`]).
|
||||
fn seals(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> bool {
|
||||
colored
|
||||
&& (matches!(paint, Paint::Gradient(_)) || paint.color().is_some())
|
||||
&& faces.iter().any(|f| f.rgb_gradient.is_some() || f.light_gradient.is_some())
|
||||
&& crate::lighting::opaque_paint(paint).1.is_none()
|
||||
}
|
||||
|
||||
/// The bytes the copies of `paint` take on Revolve's `faces` ([`paint_copies`]), twice that when the
|
||||
/// faces lie over an underlay of themselves ([`seals`]).
|
||||
fn surface_copies(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> usize {
|
||||
let copies = paint_copies(faces.len(), paint);
|
||||
if seals(faces, paint, colored) { copies.saturating_mul(2) } else { copies }
|
||||
}
|
||||
|
||||
/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the
|
||||
/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`].
|
||||
fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> {
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options)?;
|
||||
*copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0)));
|
||||
*copies = copies.saturating_add(item.map_or(0, |i| surface_copies(&faces, &paint_of(i).0, colored(&options))));
|
||||
if *copies > MAX_PAINT_COPIES {
|
||||
return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into());
|
||||
}
|
||||
@@ -394,7 +419,7 @@ fn cast_surface(
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
|
||||
caster.revolve(path, options.fill_rule, b, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -425,7 +450,7 @@ fn group_shadow(
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
let faces = cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, kept)?;
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
|
||||
@@ -438,7 +463,9 @@ fn group_shadow(
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last
|
||||
/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them
|
||||
/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
@@ -453,7 +480,7 @@ fn surface(
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
@@ -473,15 +500,16 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false));
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let colored = colored(&options);
|
||||
let (faces, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
|
||||
let seal = seals(&faces, &paint, colored);
|
||||
copies.surfaces = copies.surfaces.saturating_add(surface_copies(&faces, &paint, colored));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
}
|
||||
@@ -604,7 +632,62 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group, kept))
|
||||
Some((keys, group, kept, seal))
|
||||
}
|
||||
|
||||
/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal`
|
||||
/// ([`sealed_run`]), keeping the surface's opacity and blending mode.
|
||||
fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node {
|
||||
let NodeKind::Group { children, clip: false } = &surface.kind else { return surface };
|
||||
let Some(mut out) = seal.then(|| sealed_run(id, children)).flatten() else { return surface };
|
||||
out.opacity = surface.opacity;
|
||||
out.blend = surface.blend;
|
||||
out
|
||||
}
|
||||
|
||||
/// The faces `run` of one surface, in drawing order, over an underlay of themselves, all clipped
|
||||
/// once to the faces' outline, as [`crate::lighting::sealed`] draws them. A face drawn with a part
|
||||
/// of a graphic, a group of the face and that part, takes its face's underlay and stays in the
|
||||
/// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]),
|
||||
/// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces.
|
||||
fn sealed_run(id: NodeId, run: &[Arc<Node>]) -> Option<Node> {
|
||||
let faces: Vec<Arc<Node>> = run
|
||||
.iter()
|
||||
.map(|face| match &face.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().cloned(),
|
||||
_ => Some(face.clone()),
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
if faces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (clip, mut underlay) = crate::lighting::underlay(id, &faces)?;
|
||||
underlay.extend(run.iter().cloned());
|
||||
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
|
||||
}
|
||||
|
||||
/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive
|
||||
/// faces of one surface that `seal` takes lies over an underlay of its own faces ([`sealed_run`]),
|
||||
/// so no underlay reaches under another surface's faces, as Inflate's surfaces do
|
||||
/// (`crate::solids::underlaid_runs`). A run the underlay does not take keeps its faces.
|
||||
fn sealed_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, seal: impl Fn(usize) -> bool) -> Vec<Arc<Node>> {
|
||||
let mut out = Vec::with_capacity(faces.len());
|
||||
let mut run: Vec<Arc<Node>> = vec![];
|
||||
let mut faces = faces.into_iter().peekable();
|
||||
while let Some((surface, face)) = faces.next() {
|
||||
run.push(face);
|
||||
if faces.peek().is_some_and(|(next, _)| *next == surface) {
|
||||
continue;
|
||||
}
|
||||
match seal(surface).then(|| sealed_run(id, &run)).flatten() {
|
||||
Some(sealed) => {
|
||||
out.push(Arc::new(sealed));
|
||||
run.clear();
|
||||
}
|
||||
None => out.append(&mut run),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
|
||||
@@ -621,13 +704,16 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
|
||||
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
|
||||
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
|
||||
/// [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
/// A surface of one object about the bounds of `path`, filled with `rule`, built with options
|
||||
/// derived from `fx` ([`rule_options`]), and when `fx` casts a shadow from it, the faces it is cast
|
||||
/// from ([`surface`]). `copies` is the count [`surface`] adds to; its graphics take the symbols of
|
||||
/// `doc`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
fx: &Effect,
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
@@ -636,7 +722,14 @@ fn object_surface(
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
|
||||
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
|
||||
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
|
||||
}
|
||||
|
||||
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
|
||||
/// leave open the holes `rule` leaves in the profile.
|
||||
fn rule_options(fx: &Effect, rule: FillRule) -> Revolve {
|
||||
Revolve { fill_rule: rule, ..fx_options(fx) }
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
@@ -757,13 +850,13 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let options = shared_options(&shapes, fx_options(fx))?;
|
||||
let mut out = vec![];
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
out.extend(faces(&s.path, b, fx, Revolve { fill_rule: s.rule, ..options })?);
|
||||
}
|
||||
// In wireframe mode the canvas draws no shadow.
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
|
||||
return Ok((out, shadow));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let (path, rule) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
|
||||
let Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], vec![])) };
|
||||
@@ -771,8 +864,8 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
|
||||
let surface = faces(&path, b, fx, rule_options(fx, rule))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None)? };
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -783,7 +876,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
{
|
||||
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
|
||||
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&p, b, fx, fx_options(fx))?;
|
||||
let surface = faces(&p, b, fx, rule_options(fx, rule))?;
|
||||
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
|
||||
}
|
||||
}
|
||||
@@ -801,13 +894,14 @@ fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
}
|
||||
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
|
||||
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
|
||||
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, each with
|
||||
/// its fill rule, all swept about the bounds `b` with `options`: the edges of their faces
|
||||
/// ([`crate::solids::wireframe::wire_art`]). `None` when a profile can't be swept or past the edge
|
||||
/// limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = (&'a PathData, FillRule)>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
let mut faces = vec![];
|
||||
for path in paths {
|
||||
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
|
||||
for (path, rule) in paths {
|
||||
faces.extend(wire_faces(path, b, fx, Revolve { fill_rule: rule, ..options }).ok()?.into_iter().map(|f| f.path));
|
||||
}
|
||||
crate::solids::wireframe::wire_art(id, &faces)
|
||||
}
|
||||
@@ -857,11 +951,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
|
||||
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
let (surface, kept) = object_surface(doc, n, &path, rule, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
@@ -887,18 +981,19 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
|
||||
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
continue;
|
||||
}
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
let (mut art, kept) = object_surface(doc, n, &p, rule, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
// The shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadow.appearance.effects.extend(art.appearance.effects.iter().cloned());
|
||||
shadows.push(Arc::new(shadow));
|
||||
}
|
||||
children.push(Arc::new(art));
|
||||
@@ -1044,7 +1139,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
@@ -1055,6 +1150,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let mut surfaces = vec![];
|
||||
// The faces each member's surface kept for the shadow, member by member.
|
||||
let mut kept = vec![];
|
||||
// Whether each member's faces lie over an underlay of themselves ([`surface`]).
|
||||
let mut seals = vec![];
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
@@ -1072,10 +1169,15 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
let options = Revolve { fill_rule: s.rule, ..options };
|
||||
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
seals.push(seal);
|
||||
}
|
||||
// The faces of a member whose surface takes an underlay lie over one, run by run in the one
|
||||
// order of every member's faces ([`sealed_runs`]).
|
||||
let seal = |member: usize| seals.get(member) == Some(&true);
|
||||
if surfaces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -1101,7 +1203,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let order = crate::solids::surface_order(faces.iter().map(|(d, ..)| (d.points.as_slice(), d.plane, d.depth)));
|
||||
let faces = in_order(faces, &order);
|
||||
if opaque {
|
||||
vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))]
|
||||
vec![Arc::new(Node::group(n.id, sealed_runs(n.id, faces.into_iter().map(|(_, member, .., face)| (member, face)).collect(), seal)))]
|
||||
} else {
|
||||
// An opaque member's face goes in the order on its own. The faces of a member with
|
||||
// transparency share a run, one group with the opacity and blending mode of its fill or
|
||||
@@ -1110,6 +1212,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
// where one group can't be both behind and in front of another face.
|
||||
struct Run<'a> {
|
||||
member: Option<usize>,
|
||||
// The member the faces are of.
|
||||
of: usize,
|
||||
scopes: &'a [Scope],
|
||||
bounds: Rect,
|
||||
faces: Vec<Arc<Node>>,
|
||||
@@ -1125,12 +1229,12 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0);
|
||||
let Some(cover) = Coverage::of(&face).filter(|_| paints) else {
|
||||
// A face that paints nothing goes in the order on its own and overlaps nothing.
|
||||
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
runs.push(Run { member: None, of: member, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
|
||||
continue;
|
||||
};
|
||||
let masked = masks.get(member).is_some_and(Option::is_some);
|
||||
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked {
|
||||
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
runs.push(Run { member: None, of: member, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
continue;
|
||||
}
|
||||
let mut clear = |r: &Run| {
|
||||
@@ -1153,24 +1257,49 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
if let Some(last) = last_run.get_mut(member) {
|
||||
*last = Some(runs.len());
|
||||
}
|
||||
runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
|
||||
runs.push(Run {
|
||||
member: Some(member),
|
||||
of: member,
|
||||
scopes,
|
||||
bounds: cover.bounds,
|
||||
faces: vec![face],
|
||||
cover: vec![cover],
|
||||
opacity,
|
||||
blend,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = runs.into_iter().filter_map(|mut r| {
|
||||
// Consecutive faces of opaque members on their own wait in `solo` and go over an
|
||||
// underlay of their member's faces, run by run ([`sealed_runs`]).
|
||||
let mut out: Vec<(&[Scope], Arc<Node>)> = Vec::with_capacity(runs.len());
|
||||
let mut solo: Vec<(usize, Arc<Node>)> = vec![];
|
||||
for mut r in runs {
|
||||
// A face on its own needs a group only for the opacity or blending mode of its fill or stroke.
|
||||
if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() {
|
||||
return r.faces.pop().map(|face| (r.scopes, face));
|
||||
let Some(face) = r.faces.pop() else { continue };
|
||||
if r.scopes.is_empty() && !r.cover.is_empty() {
|
||||
solo.push((r.of, face));
|
||||
} else {
|
||||
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
|
||||
out.push((r.scopes, face));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut group = Node::group(n.id, r.faces);
|
||||
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
|
||||
let mut group = match r.member.filter(|m| seal(*m)).and_then(|_| sealed_run(n.id, &r.faces)) {
|
||||
Some(sealed) => sealed,
|
||||
None => Node::group(n.id, r.faces),
|
||||
};
|
||||
group.opacity = r.opacity;
|
||||
group.blend = r.blend;
|
||||
if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() {
|
||||
group.extras_mut().mask = Some(mask);
|
||||
}
|
||||
Some((r.scopes, Arc::new(group)))
|
||||
});
|
||||
scoped(n.id, runs.collect(), 0)
|
||||
out.push((r.scopes, Arc::new(group)));
|
||||
}
|
||||
out.extend(sealed_runs(n.id, solo, seal).into_iter().map(|face| (&[][..], face)));
|
||||
scoped(n.id, out, 0)
|
||||
}
|
||||
};
|
||||
// One shadow for every member's surface, behind them all.
|
||||
@@ -1693,6 +1822,156 @@ mod tests {
|
||||
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
|
||||
let object = painted(3, 0.0, stops * 2);
|
||||
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
|
||||
// Under a colored light the faces lie over an underlay of themselves, which copies their
|
||||
// paints again: the gradient that fits in white light is past the budget.
|
||||
let lit = json!({"lightColor": "#ff0000"});
|
||||
let object = painted(4, 0.0, stops);
|
||||
assert_eq!(validate_revolve(&object, &json!({})), Ok(()));
|
||||
let refused = validate_revolve(&object, &lit).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
let mut drawn = (*object).clone();
|
||||
drawn.appearance.effects.push(crate::new_effect(REVOLVE, &lit).unwrap());
|
||||
assert_eq!(revolve_art(&drawn), None, "past the budget the source draws");
|
||||
}
|
||||
|
||||
/// Is `u` the underlay [`crate::lighting::underlay`] draws for `face`, a face [`surface`] draws?
|
||||
fn underlies(u: &Node, face: &Node) -> bool {
|
||||
match (&u.kind, &face.kind) {
|
||||
(NodeKind::Path { .. }, NodeKind::Path { .. }) => {
|
||||
u.path_data() == face.path_data()
|
||||
&& u.appearance.items.iter().all(|i| !matches!(i, AppearanceItem::Stroke(s) if s.width != crate::lighting::UNDERLAY_SEAM))
|
||||
}
|
||||
(NodeKind::Group { children: under, clip: true }, NodeKind::Group { children, clip: true }) => {
|
||||
matches!((under.get(1), children.get(1)), (Some(a), Some(b)) if Arc::ptr_eq(a, b))
|
||||
}
|
||||
(_, NodeKind::Group { children, clip: false }) => children.first().is_some_and(|f| underlies(u, f)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The runs of faces in `art` that lie over an underlay of themselves ([`sealed_run`]), each
|
||||
/// run's faces in drawing order.
|
||||
pub(super) fn sealed_faces(art: &Node) -> Vec<Vec<Arc<Node>>> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
let NodeKind::Group { children, clip: true } = &n.kind else { return };
|
||||
let [clip, inner] = &children[..] else { return };
|
||||
let NodeKind::Group { children: drawn, clip: false } = &inner.kind else { return };
|
||||
let (under, faces) = drawn.split_at(drawn.len() / 2);
|
||||
if clip.path_data().is_some() && !inner.isolate && drawn.len() % 2 == 0 && under.iter().zip(faces).all(|(u, f)| underlies(u, f)) {
|
||||
out.push(faces.to_vec());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `n`'s surface as [`surface`] draws it before its faces are sealed, and whether they are.
|
||||
fn unsealed(n: &Node) -> (Node, bool) {
|
||||
let path = n.path_data().unwrap();
|
||||
let fx = n.appearance.effects.first().unwrap();
|
||||
let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap());
|
||||
let (_, art, _, seal) =
|
||||
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap();
|
||||
(art, seal)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colored_light_faces_lie_over_an_underlay_of_themselves_once_per_surface() {
|
||||
use vectorcraft_doc::color::{BlendMode, Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let lit = |params: Value, paint: Paint| {
|
||||
let mut n = profile_node();
|
||||
n.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
|
||||
n.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap());
|
||||
n
|
||||
};
|
||||
let red = Paint::solid(Color::rgb(0.8, 0.2, 0.1));
|
||||
let ramp = |opacity: f32| {
|
||||
let stops = [Color::WHITE, Color::rgb(0.5, 0.5, 0.5)].into_iter().enumerate();
|
||||
let stops = stops.map(|(i, c)| GradientStop { opacity, ..GradientStop::new(i as f32, c) }).collect();
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))
|
||||
};
|
||||
let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]);
|
||||
// In white light nothing is sealed.
|
||||
let white = lit(json!({}), red.clone());
|
||||
assert!(!unsealed(&white).1);
|
||||
assert!(sealed_faces(&revolve_art(&white).unwrap()).is_empty());
|
||||
for (name, n) in [
|
||||
("solid", lit(json!({"lightColor": "#ff0000"}), red.clone())),
|
||||
("gradient", lit(json!({"lightColor": "#ff0000"}), ramp(1.0))),
|
||||
("two lights", lit(json!({"lights": lights}), ramp(1.0))),
|
||||
("edge-on", lit(json!({"lightColor": "#ff0000", "rotationX": -80}), red.clone())),
|
||||
] {
|
||||
// Every face of the surface, in its order, lies over its underlay, once.
|
||||
let (plain, seal) = unsealed(&n);
|
||||
assert!(seal, "{name}");
|
||||
let faces = plain.children().unwrap().to_vec();
|
||||
assert_eq!(sealed_faces(&revolve_art(&n).unwrap()), vec![faces], "{name}");
|
||||
}
|
||||
// The surface's opacity and blending mode apply once, to the sealed surface.
|
||||
let mut n = lit(json!({"lightColor": "#ff0000"}), ramp(1.0));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = 0.5;
|
||||
f.blend = BlendMode::Multiply;
|
||||
}
|
||||
let art = revolve_art(&n).unwrap();
|
||||
assert_eq!(sealed_faces(&art).len(), 1);
|
||||
// Inside the surface only a face's own lit art blends (its light multiplied over its paint).
|
||||
let once = |chain: &Chain| chain.first() == Some(&(0.5, BlendMode::Multiply)) && chain.iter().skip(1).all(|(o, _)| *o == 1.0);
|
||||
let faces = faces_in_order(&art);
|
||||
assert!(faces.iter().all(|(_, chain)| once(chain)), "{:?}", faces.iter().map(|f| &f.1).find(|c| !once(c)));
|
||||
// Faces in a gradient with transparent stops carry its opacity mask, which the underlay
|
||||
// does not take: the surface keeps its faces as they are, and their paints are not
|
||||
// counted twice.
|
||||
let n = lit(json!({"lightColor": "#ff0000"}), ramp(0.6));
|
||||
let (plain, seal) = unsealed(&n);
|
||||
assert!(!seal);
|
||||
assert_eq!(sealed_surface(n.id, plain.clone(), true), plain);
|
||||
assert!(sealed_faces(&revolve_art(&n).unwrap()).is_empty());
|
||||
let path = n.path_data().unwrap();
|
||||
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), fx_options(&n.appearance.effects[0])).unwrap();
|
||||
assert_eq!(surface_copies(&faces, &ramp(0.6), true), paint_copies(faces.len(), &ramp(0.6)));
|
||||
assert_eq!(surface_copies(&faces, &ramp(1.0), true), 2 * paint_copies(faces.len(), &ramp(1.0)));
|
||||
// Revolve (Classic) takes no colored light, so none of its faces are sealed.
|
||||
assert!(!colored(&classic::options(&json!({"lightColor": "#ff0000"}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_members_run_of_faces_lies_over_an_underlay_of_its_own() {
|
||||
// Rings one above the other: their faces alternate in the one order, so each ring's
|
||||
// faces go over underlays run by run, and no run holds faces of both.
|
||||
let ring = |id, y: f64, opacity: f32| {
|
||||
let mut n = (*member(id, 40.0)).clone();
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
if let NodeKind::Path { path, .. } = &mut n.kind {
|
||||
*path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath()));
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let lit = json!({"segments": 16, "lightColor": "#ff0000"});
|
||||
for opacity in [1.0, 0.5] {
|
||||
let members = vec![ring(1, 0.0, 1.0), ring(2, 200.0, opacity)];
|
||||
let art = revolve_art(&group_with(lit.clone(), members.clone())).unwrap();
|
||||
let runs = sealed_faces(&art);
|
||||
assert!(runs.len() >= 2, "{opacity}: {} runs", runs.len());
|
||||
for run in &runs {
|
||||
let ys: Vec<f64> = run.iter().filter_map(|f| f.visual_bounds()).map(|b| b.center().y).collect();
|
||||
assert!(ys.iter().all(|y| *y < 100.0) || ys.iter().all(|y| *y > 100.0), "{opacity}: a run holds one ring's faces: {ys:?}");
|
||||
}
|
||||
// Each ring's opacity applies once, to its faces and their underlays; inside, only a
|
||||
// face's own lit art blends.
|
||||
let faded = |chain: &Chain| chain.iter().filter(|(o, _)| *o != 1.0).count();
|
||||
let chains: Vec<Chain> = faces_in_order(&art).into_iter().map(|(_, c)| c).collect();
|
||||
assert!(chains.iter().all(|c| faded(c) <= 1 && c.iter().all(|(o, _)| *o == 1.0 || *o == opacity)), "{opacity}");
|
||||
assert_eq!(chains.iter().any(|c| faded(c) == 1), opacity < 1.0, "{opacity}");
|
||||
if opacity == 1.0 {
|
||||
// Opaque rings share one order, and every face in it lies over an underlay.
|
||||
let white = revolve_art(&group_with(json!({"segments": 16}), members)).unwrap();
|
||||
let count = white.children().unwrap()[0].children().unwrap().len();
|
||||
assert_eq!(runs.iter().map(Vec::len).sum::<usize>(), count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1822,7 +2101,7 @@ mod tests {
|
||||
let mut fx = crate::new_effect(id, &json!({})).unwrap();
|
||||
fx.params = params.clone();
|
||||
let n = profile_node();
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let mut half = n.clone();
|
||||
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
|
||||
@@ -1830,9 +2109,9 @@ mod tests {
|
||||
}
|
||||
for n in [n, half] {
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, rule_options(&fx, rule), None).unwrap();
|
||||
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
@@ -1898,11 +2177,11 @@ mod tests {
|
||||
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
|
||||
f.opacity = bad;
|
||||
}
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, rule, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
|
||||
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
|
||||
let shadows = group_shadows(&group(bad));
|
||||
|
||||
@@ -164,6 +164,41 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Black Overprint every face keeps the blue, and the faces that darken get black over it,
|
||||
/// overprinting, as strong as the darkening of the shading color Black.
|
||||
#[test]
|
||||
fn black_overprint_keeps_the_blue_under_overprinting_black() {
|
||||
let darkened = revolved(json!({"surface": "diffuse"}));
|
||||
let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"}));
|
||||
let (darkened, drawn) = (faces(&darkened), faces(&art));
|
||||
assert_eq!(darkened.len(), drawn.len());
|
||||
let mut shaded = 0;
|
||||
for (face, black) in drawn.iter().zip(&darkened) {
|
||||
let fills: Vec<&vectorcraft_doc::FillLayer> = face
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false));
|
||||
let k = match fills.get(1) {
|
||||
Some(shadow) => {
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
|
||||
shaded += 1;
|
||||
k
|
||||
}
|
||||
None => 0.0,
|
||||
};
|
||||
let b = fill(black).unwrap().to_rgb()[2];
|
||||
assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}");
|
||||
}
|
||||
assert!(shaded > 0, "faces turned from the light get black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_offset_edge_and_cap_shape_the_surface() {
|
||||
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
|
||||
|
||||
@@ -279,6 +279,23 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() {
|
||||
assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_a_colored_light_each_part_of_a_graphic_stays_right_after_its_face_over_the_underlay() {
|
||||
let d = document();
|
||||
let n = revolved(&CYLINDER, json!({"shade": true, "lightColor": "#ff8040", "graphics": [{"symbol": "Red"}]}));
|
||||
let art = revolve_art_in(Some(&d), &n).unwrap();
|
||||
// One run holds every face; a face with a part of the bar is a group of the face and that part.
|
||||
let runs = super::tests::sealed_faces(&art);
|
||||
assert_eq!(runs.len(), 1);
|
||||
let carrying: Vec<&Arc<Node>> = runs[0].iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).collect();
|
||||
assert!(!carrying.is_empty());
|
||||
assert!(carrying.iter().all(|f| f.children().is_some_and(|c| c.len() > 1 && parts(&c[0], false).is_empty())));
|
||||
// Every part of the bar is drawn in the run, after its face, and none in the underlay.
|
||||
let in_run: usize = carrying.iter().map(|f| parts(f, false).len()).sum();
|
||||
assert!(in_run > 0);
|
||||
assert_eq!(in_run, parts(&art, false).len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_past_the_point_limit_are_refused() {
|
||||
let mut d = document();
|
||||
|
||||
+100
-59
@@ -102,6 +102,21 @@ pub fn has_solid(n: &Node) -> bool {
|
||||
solid(&n.appearance.effects).is_some() || n.appearance.items.iter().any(|i| i.visible() && solid(i.effects()).is_some())
|
||||
}
|
||||
|
||||
/// Does `n` carry a 3D effect that [`three_d_meshes`] builds solids from: a visible Revolve, or
|
||||
/// else a visible Extrude & Bevel, Inflate or Rotate effect, which on a group or layer must be on
|
||||
/// the object itself (one on a group's fill or stroke draws nothing to export)? It does not build
|
||||
/// the solids, so [`three_d_meshes`] can still refuse an object it passes.
|
||||
pub fn exports_three_d(n: &Node) -> bool {
|
||||
let container = is_container(n);
|
||||
if crate::has_revolve(n) {
|
||||
!container || n.appearance.effects.iter().any(|e| e.visible && crate::is_revolve(&e.id))
|
||||
} else if container {
|
||||
solid(&n.appearance.effects).is_some()
|
||||
} else {
|
||||
has_solid(n)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Position presets: (id, [rotation X, Y, Z]). Front, Back, Left, Right, Top and Bottom face
|
||||
/// the art that way; Off-Axis tilts each 20° down and 25° aside (showing the top and right);
|
||||
/// Isometric lays the art on the left, right, top or bottom plane of an isometric view (the
|
||||
@@ -324,8 +339,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
return check_cast(id, p, &shapes);
|
||||
return check_solids(id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -342,38 +356,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = path.bounds().ok_or_else(anchors)?;
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
check_cast(id, p, &shapes)
|
||||
check_solids(id, p, &shapes)
|
||||
}
|
||||
|
||||
/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes`
|
||||
/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
if wireframe::wireframe_params(id, p) {
|
||||
return Ok(());
|
||||
}
|
||||
cast_shadow(id, p, shapes).map(|_| ())
|
||||
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
|
||||
/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn casts_shadow(id: &str, p: &Value) -> bool {
|
||||
!is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p)
|
||||
}
|
||||
|
||||
/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow?
|
||||
fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
paint_of(item, member).1 > 0.0
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every
|
||||
/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill,
|
||||
/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid,
|
||||
/// which [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
|
||||
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
|
||||
/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids
|
||||
/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which
|
||||
/// [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))))
|
||||
.try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
let cast = casts_shadow(id, p);
|
||||
let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity)));
|
||||
shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes`
|
||||
/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not
|
||||
/// counted.
|
||||
/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does
|
||||
/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as
|
||||
/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the
|
||||
/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its
|
||||
/// shadow Rotate builds no plane here.
|
||||
fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let cast = casts_shadow(id, p);
|
||||
if is_plane(id) {
|
||||
if !cast {
|
||||
return Ok(());
|
||||
}
|
||||
let mut built = vec![];
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
if !visible(item, s.opacity) {
|
||||
built.push(None);
|
||||
continue;
|
||||
}
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1);
|
||||
}
|
||||
}
|
||||
return cast_built(id, p, shapes, built).map(|_| ());
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()))
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
|
||||
@@ -596,7 +640,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
|
||||
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
|
||||
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
|
||||
/// with the faces of other solids.
|
||||
/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn
|
||||
/// opaque under one mask of its transparency, placed once on all the facets when it has no
|
||||
/// placement of its own ([`crate::lighting::opaque_surface_paint`]).
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
|
||||
if !faces && composites_facets(&facets, paint, colored) {
|
||||
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
|
||||
@@ -605,7 +651,7 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
return group;
|
||||
}
|
||||
// Preserve existing white-light paints and alpha composition exactly.
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) };
|
||||
let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) };
|
||||
let paint = &opaque;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
@@ -642,6 +688,11 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
group
|
||||
}
|
||||
|
||||
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
|
||||
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
|
||||
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
|
||||
}
|
||||
|
||||
/// The width of the stroke of a facet's own paint that closes the seams between `face` and its
|
||||
/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than
|
||||
/// the stroke, and its stroke would then paint over its neighbors.
|
||||
@@ -733,7 +784,8 @@ thread_local! {
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
|
||||
/// ([`cast_shadow`]) count too.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -1435,7 +1487,7 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let cast = casts_shadow(&fx.id, &p);
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
@@ -1500,12 +1552,16 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
@@ -1529,16 +1585,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
/// each shape, otherwise each part ([`solid_parts`]). No solid is built here: an entry with no faces
|
||||
/// (a stroke's solid left out of the art, past its own limits) casts nothing, as it draws nothing.
|
||||
/// Only `built` of another length than the solids is cast as [`cast_shadow`] casts it.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
@@ -1555,39 +1609,22 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
let Some(kept) = kept else { continue };
|
||||
cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.casts() && kept.is_none())) {
|
||||
let (parts, _) = solid_parts(shapes, b);
|
||||
if parts.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) {
|
||||
let ink = ink(item, *member);
|
||||
// A fully transparent solid, or a stroke's solid left out of the art, casts nothing.
|
||||
let Some(kept) = kept.filter(|_| ink.casts()) else { continue };
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
let faces = match caster.add_solid(kept) {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
@@ -2140,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Arc::make_mut(&mut art).appearance.effects = later.clone();
|
||||
art
|
||||
};
|
||||
shadows.extend(shadow.into_iter().map(with_later));
|
||||
// A shadow keeps its own blur (the light's Softness) below the later effects.
|
||||
shadows.extend(shadow.into_iter().map(|mut art| {
|
||||
Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned());
|
||||
art
|
||||
}));
|
||||
children.extend(surfaces.into_iter().map(with_later));
|
||||
} else {
|
||||
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
|
||||
@@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"];
|
||||
/// The width of a Wireframe edge, in points.
|
||||
const WIRE: f64 = 0.5;
|
||||
|
||||
/// The Shading Color choices: black, a custom color, or none.
|
||||
pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"];
|
||||
/// The Shading Color choices: black, a custom color, none, or black overprinting the paint.
|
||||
pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"];
|
||||
|
||||
/// The surface settings of Extrude & Bevel (Classic)'s parameters.
|
||||
pub fn classic_shading(p: &Value) -> ClassicShading {
|
||||
@@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only
|
||||
/// the highlight lightens them).
|
||||
/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces
|
||||
/// keep their paint and only the highlight lightens them).
|
||||
fn shading_color(p: &Value) -> Option<Color> {
|
||||
match text(p, "shadingColor", "black") {
|
||||
"none" => None,
|
||||
@@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool {
|
||||
|
||||
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
|
||||
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
|
||||
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it as
|
||||
/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// stroke each layer draws around the face.
|
||||
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
|
||||
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
|
||||
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
|
||||
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
|
||||
if shade.is_some() && tone < 1.0 {
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Multiply;
|
||||
edge.overprint = true;
|
||||
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
|
||||
if shade.is_some() {
|
||||
items.extend(overprinting_black(tone, seam));
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The black that shades a face at tone `tone` on the black plate, when the tone is below full
|
||||
/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam`
|
||||
/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a
|
||||
/// neighbor's, the face is not darkened twice.
|
||||
fn overprinting_black(tone: f64, seam: f64) -> Vec<AppearanceItem> {
|
||||
if tone >= 1.0 {
|
||||
return vec![];
|
||||
}
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Darken;
|
||||
edge.overprint = true;
|
||||
vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]
|
||||
}
|
||||
|
||||
/// Whether the shading color of parameters `p` is Black Overprint.
|
||||
fn black_overprint(p: &Value) -> bool {
|
||||
text(p, "shadingColor", "black") == "blackOverprint"
|
||||
}
|
||||
|
||||
/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full
|
||||
/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they
|
||||
/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of
|
||||
/// the seam stroke each layer draws around the face.
|
||||
fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec<AppearanceItem> {
|
||||
let mut items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))];
|
||||
items.extend(overprinting_black(tone, seam));
|
||||
items
|
||||
}
|
||||
|
||||
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
|
||||
/// Wireframe, else the seam between faces.
|
||||
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
@@ -229,16 +256,19 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
|
||||
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot
|
||||
/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops
|
||||
/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's
|
||||
/// coverage; without a placement of its own, it is placed once on all the faces
|
||||
/// ([`crate::lighting::opaque_surface_paint`]).
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let overprint = black_overprint(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
|
||||
let paint = &paint;
|
||||
let children = facets
|
||||
.into_iter()
|
||||
@@ -251,6 +281,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
let (tone, spec) = shading.tone(face.normal, &lights);
|
||||
// A narrow stroke of the face's own paint closes the hairline seams between faces.
|
||||
let seam = super::seam_width(&face);
|
||||
if overprint {
|
||||
let items = overprinted_face(paint, tone, seam);
|
||||
return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }));
|
||||
}
|
||||
let items = match paint.color() {
|
||||
// Unshaded (No Shading, no shading color, or a face in full light) with no
|
||||
// highlight: the paint itself, its color space and swatch kept.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the
|
||||
//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it
|
||||
//! draws behind the solids.
|
||||
//! draws behind the solids, blurred by the first light's Softness.
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
|
||||
use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition};
|
||||
|
||||
use super::Scope;
|
||||
@@ -15,15 +15,21 @@ use crate::util::{flag, num, text};
|
||||
/// The shadow's paint: black at this opacity. VectorCraft's own values.
|
||||
const SHADOW_OPACITY: f32 = 0.5;
|
||||
|
||||
/// Blur radii below this, in points, leave the shadow hard-edged.
|
||||
const MIN_BLUR: f64 = 0.01;
|
||||
|
||||
/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built.
|
||||
/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first
|
||||
/// light's.
|
||||
pub(crate) fn options(p: &Value) -> Option<Shadow> {
|
||||
let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0));
|
||||
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
|
||||
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
|
||||
let lit = flag(p, "shade", true) && intensity > 0.0;
|
||||
(lit && flag(p, "shadow", false)).then(|| Shadow {
|
||||
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
|
||||
distance: num(p, "shadowDistance", 0.0) / 100.0,
|
||||
bounds: num(p, "shadowBounds", 100.0) / 100.0,
|
||||
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool {
|
||||
}
|
||||
|
||||
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
|
||||
/// `None` when it casts nothing.
|
||||
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and
|
||||
/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which
|
||||
/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing.
|
||||
pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> {
|
||||
let all = 0..caster.len();
|
||||
let all = std::slice::from_ref(&all);
|
||||
@@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::BLACK));
|
||||
fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0);
|
||||
fill.blend = ink.blend;
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
let blur = plane.blur();
|
||||
let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] };
|
||||
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies).
|
||||
|
||||
@@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result
|
||||
|
||||
/// The check builds each solid the effect draws once, about the bounds it draws it about: one for
|
||||
/// a fill and one for each stroke, on an object, on a group's members and on an appearance item,
|
||||
/// with the shadow on or off.
|
||||
/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds
|
||||
/// kept, so no solid is built again for it.
|
||||
#[test]
|
||||
fn the_check_builds_each_drawn_solid_once() {
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
@@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() {
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill");
|
||||
let shadow = json!({"shadow": true});
|
||||
assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on");
|
||||
let mut other = square_node();
|
||||
other.id = NodeId(2);
|
||||
let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]);
|
||||
assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on");
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1760,11 +1766,24 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
|
||||
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
|
||||
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
|
||||
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect();
|
||||
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
|
||||
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
|
||||
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
|
||||
assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}");
|
||||
let reaches = |b: Rect| (b.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (b.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1;
|
||||
assert!(reaches(clip), "{clip:?} {facet:?}");
|
||||
// In the composite, the facet over the underlay is one fill of the facet and its seam in each
|
||||
// channel: no seam stroke of its own, and a path that reaches past the facet by half the seam.
|
||||
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect();
|
||||
assert!(widths.is_empty(), "{widths:?}");
|
||||
let mut seamed = vec![];
|
||||
batch.walk(&mut |n| {
|
||||
if let [AppearanceItem::Fill(f)] = n.appearance.items.as_slice()
|
||||
&& f.paint != Paint::solid(Color::BLACK)
|
||||
&& f.paint != paint
|
||||
{
|
||||
seamed.extend(n.path_data().and_then(PathData::bounds));
|
||||
}
|
||||
});
|
||||
assert!(seamed.len() == 3 && seamed.iter().all(|b| reaches(*b)), "{seamed:?} {facet:?}");
|
||||
}
|
||||
|
||||
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
|
||||
@@ -1902,6 +1921,89 @@ fn classic_shading_color_blend_steps_and_lights() {
|
||||
assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6);
|
||||
}
|
||||
|
||||
/// The fills, then the strokes, of face `face`.
|
||||
fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) {
|
||||
let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect();
|
||||
let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect();
|
||||
(fills, strokes)
|
||||
}
|
||||
|
||||
/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in
|
||||
/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice);
|
||||
/// `None` when the face has none.
|
||||
fn overprinted_black(face: &Node) -> Option<f32> {
|
||||
let (fills, strokes) = layers_of(face);
|
||||
assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke");
|
||||
let shadow = fills.get(1)?;
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
|
||||
assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true));
|
||||
assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out");
|
||||
Some(k)
|
||||
}
|
||||
|
||||
/// Black Overprint keeps the paint on every face and draws the shading over it as black,
|
||||
/// overprinting, as strong as the darkening of the shading color Black; the
|
||||
/// highlight is not drawn, and No Shading adds no black.
|
||||
#[test]
|
||||
fn classic_black_overprint_keeps_the_paint_under_overprinting_black() {
|
||||
let diffuse = json!({"surface": "diffuse", "ambient": 20});
|
||||
let mut over = diffuse.clone();
|
||||
over["shadingColor"] = json!("blackOverprint");
|
||||
let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect();
|
||||
let faces = classic_faces(over);
|
||||
assert_eq!(faces.len(), darkened.len());
|
||||
let mut shaded = 0;
|
||||
for (face, rgb) in faces.iter().zip(&darkened) {
|
||||
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept");
|
||||
let k = overprinted_black(face).unwrap_or(0.0);
|
||||
assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}");
|
||||
shaded += usize::from(k > 0.0);
|
||||
}
|
||||
assert!(shaded > 0, "faces turned from the light get black");
|
||||
// Plastic: no white layer for the highlight.
|
||||
let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
|
||||
for face in classic_faces(shiny) {
|
||||
let (fills, _) = layers_of(&face);
|
||||
assert_eq!(fills[0].paint, Paint::solid(RED));
|
||||
assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}");
|
||||
}
|
||||
// No Shading: the paint alone.
|
||||
for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) {
|
||||
assert_eq!(overprinted_black(&face), None);
|
||||
assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED));
|
||||
}
|
||||
}
|
||||
|
||||
/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate
|
||||
/// (Classic) draws its plane the same way.
|
||||
#[test]
|
||||
fn classic_black_overprint_keeps_gradients_and_shades_rotate() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint};
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)],
|
||||
))));
|
||||
let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
|
||||
f.paint = gradient.clone();
|
||||
}
|
||||
let art = solid_art(&n).unwrap();
|
||||
let mut shaded = 0;
|
||||
for face in faces(&art) {
|
||||
assert_eq!(layers_of(face).0[0].paint, gradient);
|
||||
shaded += usize::from(overprinted_black(face).is_some());
|
||||
}
|
||||
assert!(shaded > 0);
|
||||
// Rotate (Classic), turned from the light: red with black over it; facing it: red alone.
|
||||
let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
|
||||
let face = &turned[0].children().unwrap()[0];
|
||||
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED));
|
||||
assert!(overprinted_black(face).is_some_and(|k| k > 0.05));
|
||||
let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
|
||||
assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_bevel_height_extent_and_cap_shape_the_solid() {
|
||||
let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap();
|
||||
@@ -1954,6 +2056,57 @@ fn classic_shading_keeps_a_gradients_transparency() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient without a placement and with a transparent stop, under colored lights or classic
|
||||
/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask
|
||||
/// share one placement, so the color and transparency ramps line up across the faces. A gradient
|
||||
/// placed in the document keeps its placement.
|
||||
#[test]
|
||||
fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
|
||||
// The source's stops carry an unusual midpoint, so its color and mask copies can be told from
|
||||
// the light ramps.
|
||||
const MARK: f32 = 0.37;
|
||||
let mut first = GradientStop::new(0.0, RED);
|
||||
first.midpoint = MARK;
|
||||
let mut end = GradientStop::new(1.0, Color::BLACK);
|
||||
end.opacity = 0.25;
|
||||
let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end]));
|
||||
let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None };
|
||||
// The placement of each copy of the source gradient: its own, else its fit on the path it fills.
|
||||
fn placements(n: &Node, out: &mut Vec<GradientGeom>) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(mask) = &c.extras().mask {
|
||||
placements(&mask.art, out);
|
||||
}
|
||||
let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO);
|
||||
for item in &c.appearance.items {
|
||||
if let Paint::Gradient(g) = paint_ref(item)
|
||||
&& g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK)
|
||||
{
|
||||
out.push(g.resolve(bounds));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let lit = json!({"lights": [{"color": "#ff8080"}]});
|
||||
for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] {
|
||||
for geom in [None, Some(placed)] {
|
||||
let mut n = square_node();
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))];
|
||||
n.appearance.effects.push(fx(id, params.clone()));
|
||||
let art = solid_art(&n).unwrap_or_else(|| panic!("{id}"));
|
||||
let mut masks = 0;
|
||||
art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some()));
|
||||
assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask");
|
||||
let mut found = vec![];
|
||||
placements(&art, &mut found);
|
||||
assert!(found.len() > 2, "{id}: the faces' colors and the mask");
|
||||
let expected = geom.unwrap_or(found[0]);
|
||||
assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
|
||||
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
|
||||
/// faces are drawn between them where they are in front of some and behind others. Here a square
|
||||
@@ -2077,9 +2230,12 @@ fn classic_parameters_are_checked() {
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok());
|
||||
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
|
||||
(json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingColor": true}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"),
|
||||
@@ -2156,11 +2312,12 @@ fn classic_rotate_parameters_are_checked() {
|
||||
let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p));
|
||||
assert!(check(json!({})).is_ok());
|
||||
assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok());
|
||||
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
|
||||
for (p, says) in [
|
||||
(json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"),
|
||||
(json!({"surface": 2}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
|
||||
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
|
||||
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
(json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"),
|
||||
(json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"),
|
||||
|
||||
@@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius of the Gaussian Blur on shadow `n`; `None` without one.
|
||||
fn shadow_blur(n: &Node) -> Option<f64> {
|
||||
match n.appearance.effects.as_slice() {
|
||||
[] => None,
|
||||
[e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(),
|
||||
other => panic!("unexpected effects on the shadow: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object;
|
||||
/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness.
|
||||
#[test]
|
||||
fn the_first_lights_softness_blurs_the_shadow() {
|
||||
for id in CASTING {
|
||||
let blur = |params: Value| {
|
||||
let mut n = square_node(1, 0.0);
|
||||
n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap());
|
||||
let lit = art(&n, id).unwrap();
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id} {params}");
|
||||
shadow_blur(shadow)
|
||||
};
|
||||
assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %");
|
||||
let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}"));
|
||||
let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap();
|
||||
let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap();
|
||||
assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}");
|
||||
let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]});
|
||||
assert_eq!(blur(first), Some(softer), "{id}: the first light's");
|
||||
let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]});
|
||||
assert_eq!(blur(second), None, "{id}: only the first light casts");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() {
|
||||
for id in CASTING {
|
||||
@@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it
|
||||
/// in the fill's list follow the blur.
|
||||
#[test]
|
||||
fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() {
|
||||
for id in CASTING {
|
||||
for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] {
|
||||
let mut n = square_node(1, 0.0);
|
||||
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap());
|
||||
fill.effects_mut().extend(later.clone());
|
||||
let lit = art(&n, id).unwrap_or_else(|| panic!("{id}"));
|
||||
let shadow = &lit.children().unwrap()[0];
|
||||
assert!(is_shadow(shadow), "{id}");
|
||||
let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect();
|
||||
assert_eq!(ids, want, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_keeps_the_shadow_as_a_path() {
|
||||
for id in CASTING {
|
||||
@@ -313,6 +367,68 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast
|
||||
/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws
|
||||
/// nothing, and the fill's solid still casts.
|
||||
#[test]
|
||||
fn a_stroke_left_out_of_the_art_casts_no_shadow() {
|
||||
for id in [EXTRUDE, INFLATE] {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, &json!({"shadow": true}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut built: Vec<Option<SolidFaces>> =
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
|
||||
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
|
||||
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
|
||||
assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast");
|
||||
built[stroke] = None;
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap();
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow");
|
||||
assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing");
|
||||
assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the
|
||||
/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing.
|
||||
#[test]
|
||||
fn the_check_accepts_the_shadowed_objects_that_draw() {
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for params in shadow_settings(id) {
|
||||
for n in shadowed(id, ¶ms) {
|
||||
let mut drawn = 0;
|
||||
art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some()));
|
||||
assert!(drawn > 0, "{id} {params}");
|
||||
assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow = json!({"shadow": true});
|
||||
for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] {
|
||||
let n = stroked_square(1, 0.0, stroke);
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no
|
||||
/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off.
|
||||
#[test]
|
||||
fn the_check_casts_no_shadow_in_wireframe_mode() {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let wire = json!({"shadow": true, "render": {"mode": "wireframe"}});
|
||||
for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] {
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
|
||||
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
|
||||
/// it from the faces the solids drawn kept.
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use resvg::{tiny_skia, usvg};
|
||||
use craft_svg::tree::draw::{resvg, tiny_skia};
|
||||
use craft_svg::tree::usvg;
|
||||
use serde_json::Value;
|
||||
use usvg::roxmltree;
|
||||
use vectorcraft_doc::SvgFilter;
|
||||
@@ -624,17 +625,27 @@ fn write_drop_shadow(n: roxmltree::Node, input: &str, result: Option<&str>, name
|
||||
/// first bytes whatever its `data:` URL says, of at most [`MAX_IMAGE_PIXELS`] pixels by its header.
|
||||
/// `None` for anything else, SVG and compressed SVG included.
|
||||
fn raster_image_sized(data: Arc<Vec<u8>>) -> Option<(usvg::ImageKind, u64)> {
|
||||
let format = image::guess_format(&data).ok()?;
|
||||
let (w, h) = image::ImageReader::with_format(std::io::Cursor::new(data.as_slice()), format).into_dimensions().ok()?;
|
||||
let format = craft_image_codecs::detect(&data)?;
|
||||
let (w, h) = match format {
|
||||
craft_image_codecs::Format::Png => {
|
||||
if data.len() < 24 || &data[..8] != b"\x89PNG\r\n\x1a\n" || &data[12..16] != b"IHDR" {
|
||||
return None;
|
||||
}
|
||||
(u32::from_be_bytes(data[16..20].try_into().ok()?), u32::from_be_bytes(data[20..24].try_into().ok()?))
|
||||
}
|
||||
craft_image_codecs::Format::Jpeg => craft_image_codecs::jpeg_info(&data).map(|j| (j.width, j.height))?,
|
||||
craft_image_codecs::Format::Gif | craft_image_codecs::Format::WebP => craft_image_codecs::probe_size(&data).ok()?,
|
||||
_ => return None,
|
||||
};
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
if pixels == 0 || pixels > MAX_IMAGE_PIXELS {
|
||||
return None;
|
||||
}
|
||||
let kind = match format {
|
||||
image::ImageFormat::Png => usvg::ImageKind::PNG(data),
|
||||
image::ImageFormat::Jpeg => usvg::ImageKind::JPEG(data),
|
||||
image::ImageFormat::Gif => usvg::ImageKind::GIF(data),
|
||||
image::ImageFormat::WebP => usvg::ImageKind::WEBP(data),
|
||||
craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data),
|
||||
craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data),
|
||||
craft_image_codecs::Format::Gif => usvg::ImageKind::GIF(data),
|
||||
craft_image_codecs::Format::WebP => usvg::ImageKind::WEBP(data),
|
||||
_ => return None,
|
||||
};
|
||||
Some((kind, pixels))
|
||||
@@ -1636,7 +1647,6 @@ fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affin
|
||||
|
||||
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
|
||||
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
|
||||
use image::ImageEncoder;
|
||||
let px = data.as_chunks::<4>().0;
|
||||
let mut straight = Vec::with_capacity((x1 - x0) * (y1 - y0) * 4);
|
||||
for y in y0..y1 {
|
||||
@@ -1646,14 +1656,16 @@ fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) ->
|
||||
straight.extend_from_slice(&[un(p[0]), un(p[1]), un(p[2]), p[3]]);
|
||||
}
|
||||
}
|
||||
let mut png = vec![];
|
||||
let encoder = image::codecs::png::PngEncoder::new_with_quality(
|
||||
&mut png,
|
||||
image::codecs::png::CompressionType::Fast,
|
||||
image::codecs::png::FilterType::NoFilter,
|
||||
);
|
||||
encoder.write_image(&straight, (x1 - x0) as u32, (y1 - y0) as u32, image::ExtendedColorType::Rgba8).ok()?;
|
||||
Some(png)
|
||||
let raw = craft_image_codecs::Image::from_raw(
|
||||
(x1 - x0) as u32,
|
||||
(y1 - y0) as u32,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
straight,
|
||||
)
|
||||
.ok()?;
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts).ok()
|
||||
}
|
||||
|
||||
/// `a` as an SVG `matrix(…)`.
|
||||
|
||||
@@ -520,16 +520,15 @@ fn the_filter_is_drawn_and_written_from_its_filter_parts_alone() {
|
||||
#[test]
|
||||
fn filter_images_are_small_raster_images() {
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(
|
||||
image::codecs::png::PngEncoder::new(&mut out),
|
||||
&vec![0; (w * h * 4) as usize],
|
||||
let img = craft_image_codecs::Image::from_raw(
|
||||
w,
|
||||
h,
|
||||
image::ExtendedColorType::Rgba8,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
vec![0; (w * h * 4) as usize],
|
||||
)
|
||||
.unwrap();
|
||||
out
|
||||
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
let raster_image = |data| raster_image_sized(data).map(|(kind, _)| kind);
|
||||
assert!(matches!(raster_image(Arc::new(png(2, 2))), Some(usvg::ImageKind::PNG(_))));
|
||||
@@ -547,8 +546,12 @@ fn filter_images_are_small_raster_images() {
|
||||
|
||||
/// A 2 × 2 PNG whose header claims `w` × `h` pixels (its IHDR rewritten, with the CRC fixed).
|
||||
fn png_claiming(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
image::ImageEncoder::write_image(image::codecs::png::PngEncoder::new(&mut out), &[0; 16], 2, 2, image::ExtendedColorType::Rgba8).unwrap();
|
||||
let mut out = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, vec![0; 16]).unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
out[16..20].copy_from_slice(&w.to_be_bytes());
|
||||
out[20..24].copy_from_slice(&h.to_be_bytes());
|
||||
let crc = crc32(&out[12..29]);
|
||||
|
||||
@@ -11,6 +11,7 @@ mod rasterfollow;
|
||||
mod scale;
|
||||
mod solidcontext;
|
||||
mod transformfx;
|
||||
mod typestroke;
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
|
||||
@@ -15,10 +15,13 @@ fn fx(id: &str) -> Effect {
|
||||
}
|
||||
|
||||
/// `img` encoded as `format`.
|
||||
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
|
||||
out
|
||||
fn encoded(img: image::DynamicImage, format: craft_image_codecs::Format) -> Vec<u8> {
|
||||
let (layout, data) = match format {
|
||||
craft_image_codecs::Format::Jpeg => (craft_image_codecs::ChannelLayout::Rgb, img.to_rgb8().into_raw()),
|
||||
_ => (craft_image_codecs::ChannelLayout::Rgba, img.to_rgba8().into_raw()),
|
||||
};
|
||||
let raw = craft_image_codecs::Image::from_raw(img.width(), img.height(), layout, craft_image_codecs::SampleType::U8, data).unwrap();
|
||||
craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
|
||||
@@ -130,7 +133,7 @@ fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
|
||||
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
|
||||
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
|
||||
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
|
||||
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (d, n) = image_doc(encoded(img, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert_eq!(rows.len(), 1, "{name}");
|
||||
// The disc runs from 70 to 130; the frame from 50 to 150.
|
||||
@@ -143,9 +146,9 @@ fn outline_object_follows_the_frame_of_an_image_without_transparency() {
|
||||
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
|
||||
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
|
||||
let formats = [
|
||||
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
|
||||
("rgb png", encoded(opaque, image::ImageFormat::Png)),
|
||||
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
|
||||
("jpeg", encoded(opaque.clone(), craft_image_codecs::Format::Jpeg)),
|
||||
("rgb png", encoded(opaque, craft_image_codecs::Format::Png)),
|
||||
("rgba png, every pixel more than half opaque", encoded(solid, craft_image_codecs::Format::Png)),
|
||||
];
|
||||
for (name, bytes) in formats {
|
||||
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
@@ -165,7 +168,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
fill.effects = vec![rect.clone()];
|
||||
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
|
||||
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), items, 2);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert_eq!(rows.len(), 3, "{rows:?}");
|
||||
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
|
||||
@@ -179,7 +182,7 @@ fn convert_to_shape_keeps_the_frame_beside_outline_object() {
|
||||
#[test]
|
||||
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
|
||||
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
|
||||
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (d, n) = image_doc(encoded(clear, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
assert!(row_bounds(&d, &n).is_empty());
|
||||
let art = reshape::reshape(Some(&d), &n, None).unwrap();
|
||||
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
|
||||
@@ -190,7 +193,7 @@ fn the_outline_follows_the_images_own_pixels_and_placement() {
|
||||
// Pixels kept on the image itself (art made outside a document), placed at half size.
|
||||
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
|
||||
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), craft_image_codecs::Format::Png))));
|
||||
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
|
||||
}
|
||||
let art = reshape::reshape(None, &n, None).unwrap();
|
||||
@@ -206,7 +209,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
|
||||
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
|
||||
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
|
||||
}));
|
||||
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (d, mut n) = image_doc(encoded(half, craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
(im.width, im.height, im.xf) = (120, 60, xf);
|
||||
@@ -221,7 +224,7 @@ fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels()
|
||||
|
||||
#[test]
|
||||
fn an_image_in_a_group_exports_with_its_outline() {
|
||||
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let l = d.layers[0].id;
|
||||
d.remove(n.id).unwrap();
|
||||
let g = d.alloc_id();
|
||||
@@ -256,7 +259,7 @@ fn baked_strokes(d: &Document) -> Vec<Rect> {
|
||||
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
|
||||
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
|
||||
// Under a clipping mask that covers the whole image.
|
||||
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (mut d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let l = d.layers[0].id;
|
||||
d.remove(n.id).unwrap();
|
||||
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
|
||||
@@ -265,7 +268,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
|
||||
let paths = baked_strokes(&d);
|
||||
assert!(disc_outline(&paths), "{paths:?}");
|
||||
// With an opacity mask.
|
||||
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (mut d, mut n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
|
||||
white.appearance.set_fill(Paint::solid(Color::WHITE));
|
||||
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
|
||||
@@ -279,7 +282,7 @@ fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outli
|
||||
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
|
||||
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
fill.effects = vec![fx("path.outlineObject")];
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
|
||||
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![AppearanceItem::Fill(fill)], 1);
|
||||
let rows = row_bounds(&d, &n);
|
||||
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
|
||||
// A palette image whose first color is transparent (a tRNS chunk).
|
||||
@@ -308,15 +311,18 @@ fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
|
||||
}
|
||||
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
|
||||
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
|
||||
let (d, n) =
|
||||
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (d, n) = image_doc(
|
||||
encoded(image::DynamicImage::ImageRgba8(checker), craft_image_codecs::Format::Png),
|
||||
vec![stroke(vec![fx("path.outlineObject")])],
|
||||
1,
|
||||
);
|
||||
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
|
||||
let traces = || reshape::TRACES.with(std::cell::Cell::get);
|
||||
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let (d, n) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
|
||||
let before = traces();
|
||||
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
|
||||
@@ -331,7 +337,7 @@ fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
|
||||
// Once the document and its pixels are gone, the next trace drops their entry.
|
||||
drop(d);
|
||||
assert!(pixels.upgrade().is_none());
|
||||
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
|
||||
let (other, _) = image_doc(encoded(disc(), craft_image_codecs::Format::Png), vec![], 1);
|
||||
reshape::opaque_area(&[Some(&other)], im).unwrap();
|
||||
assert_eq!(traces(), before + 2);
|
||||
assert!(!reshape::keeps_outline(&pixels));
|
||||
|
||||
@@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
|
||||
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
use crate::pixel::{Light, StrokeDirection};
|
||||
use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -128,9 +129,10 @@ fn rasterize_before_a_transform_keeps_its_options() {
|
||||
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
|
||||
}
|
||||
|
||||
/// The Transform effects after the last Rasterize effect move its image when, from the first of
|
||||
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
|
||||
/// ones with Transform Objects off, leave the image where it is.
|
||||
/// The Transform effects after the last Rasterize effect move or copy its image when, from the
|
||||
/// first of them on, every visible effect is a Transform effect that does not move at random and at
|
||||
/// most one of them makes copies. Hidden ones, and ones with Transform Objects off, leave the image
|
||||
/// where it is.
|
||||
#[test]
|
||||
fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
let rasterize = || fx(crate::RASTERIZE, json!({}));
|
||||
@@ -149,9 +151,16 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
// the image back.
|
||||
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
|
||||
(vec![rasterize(), scale(), roughen], None),
|
||||
(vec![rasterize(), scale(), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
|
||||
(vec![rasterize(), scale(), shadow.clone()], None),
|
||||
// Each copy carries the image, even of a Transform effect that only copies in place.
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), scale()], Some(vec![1, 2])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2, "objects": false}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), transform(json!({"moveV": 10, "copies": 3}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2, "random": true}))], None),
|
||||
// The Transform effect before the Rasterize effect moves the art.
|
||||
(vec![scale(), rasterize()], None),
|
||||
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
|
||||
@@ -172,16 +181,62 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 1);
|
||||
// Twice the size about the center (20, 20), then 5 pt to the right.
|
||||
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
|
||||
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
|
||||
assert!(same_map(maps[0], want), "{maps:?}");
|
||||
// The second Transform effect turns about the center of what the first one made.
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = map * Point::new(20.0, 20.0);
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = maps[0] * Point::new(20.0, 20.0);
|
||||
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
|
||||
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
|
||||
assert_eq!(crate::stage_maps(&effects, &[1, 2], &PathData::default()), None);
|
||||
}
|
||||
|
||||
/// Is `a` `b`, each coefficient within 1e-9?
|
||||
fn same_map(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// Are `maps` `want`, in order?
|
||||
fn same_maps(maps: &[Affine], want: &[Affine]) -> bool {
|
||||
maps.len() == want.len() && maps.iter().zip(want).all(|(m, w)| same_map(*m, *w))
|
||||
}
|
||||
|
||||
/// A Transform effect with copies places the image once for the original and once for each copy,
|
||||
/// copy `k` through its map `k` times about the art before it, the last copy lowest and the
|
||||
/// original on top. A Transform effect after it moves every placement, about the bounds of all the
|
||||
/// copies.
|
||||
#[test]
|
||||
fn each_copy_carries_the_image() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let rasterize = fx(crate::RASTERIZE, json!({}));
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let want = [Affine::translate((200.0, 0.0)), Affine::translate((100.0, 0.0)), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Turned 90° about the center (20, 20) each time: copy 2 turns 180°.
|
||||
let effects = [rasterize.clone(), transform(json!({"rotate": 90, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let turn = |deg: f64| Affine::translate((20.0, 20.0)) * Affine::rotate(-deg.to_radians()) * Affine::translate((-20.0, -20.0));
|
||||
let want = [turn(180.0), turn(90.0), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A scale after the copies doubles every placement about the center of all three, (120, 20).
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2})), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let scale = Affine::translate((120.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-120.0, -20.0));
|
||||
let want = [scale * Affine::translate((200.0, 0.0)), scale * Affine::translate((100.0, 0.0)), scale];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A move before the copies moves the art they copy.
|
||||
let effects = [rasterize.clone(), transform(json!({"moveV": 5})), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let want = [Affine::translate((100.0, 5.0)), Affine::translate((0.0, 5.0))];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Copies stop where the geometry pass stops them: none past its reach of 1e9 pt.
|
||||
let effects = [rasterize, transform(json!({"moveH": 1.0e7, "copies": 1000}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 100, "{}", maps.len());
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
@@ -436,6 +491,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() {
|
||||
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// The light direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_light(effects: &[Effect]) -> Option<Light> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(
|
||||
PixelFx::Underpainting { light, .. }
|
||||
| PixelFx::RoughPastels { light, .. }
|
||||
| PixelFx::ConteCrayon { light, .. }
|
||||
| PixelFx::BasRelief { light, .. }
|
||||
| PixelFx::Plaster { light, .. }
|
||||
| PixelFx::Texturizer { light, .. },
|
||||
) => Some(light),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The stroke direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_strokes(effects: &[Effect]) -> Option<StrokeDirection> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The screen angles of the first Color Halftone `effects` draw.
|
||||
fn drawn_screens(effects: &[Effect]) -> [f64; 4] {
|
||||
match raster_effects(effects).into_iter().next() {
|
||||
Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles,
|
||||
other => panic!("expected a Color Halftone, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with.
|
||||
fn relief_then(light: &str, params: Value) -> Option<Light> {
|
||||
drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)])
|
||||
}
|
||||
|
||||
/// A light direction before a Transform effect turns and reflects with the art (y down on the
|
||||
/// page), to the nearest of the eight directions, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn bas_relief_light_follows_rotation_and_reflection() {
|
||||
assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left));
|
||||
assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom));
|
||||
assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top));
|
||||
assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right));
|
||||
// 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway
|
||||
// between Top and Top Left.
|
||||
assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft));
|
||||
// A turn of 90° counterclockwise, from each direction.
|
||||
for (from, to) in [
|
||||
("bottom", Light::Right),
|
||||
("bottomLeft", Light::BottomRight),
|
||||
("left", Light::Bottom),
|
||||
("topLeft", Light::BottomLeft),
|
||||
("top", Light::Left),
|
||||
("topRight", Light::TopLeft),
|
||||
("right", Light::Top),
|
||||
("bottomRight", Light::TopRight),
|
||||
] {
|
||||
assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}");
|
||||
}
|
||||
// Every filter with a light direction, and Bas Relief's default light (Bottom).
|
||||
for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] {
|
||||
let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))];
|
||||
assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}");
|
||||
}
|
||||
assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right));
|
||||
// The Transform effects after the filter turn it together, with one rounding at the end.
|
||||
let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))];
|
||||
assert_eq!(drawn_light(&twice), Some(Light::TopRight));
|
||||
}
|
||||
|
||||
/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest
|
||||
/// of the four, a stroke and its reverse being the same, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn stroke_axis_follows_transform() {
|
||||
let strokes = |id: &str, way: Option<&str>, params: Value| {
|
||||
let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w }));
|
||||
drawn_strokes(&[fx(id, p), transform(params)])
|
||||
};
|
||||
let sprayed = "brushStrokes.sprayedStrokes";
|
||||
let pen = "sketch.graphicPen";
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical));
|
||||
assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal));
|
||||
assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal));
|
||||
}
|
||||
|
||||
fn near4(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angles before a Transform effect turn and reflect with the art.
|
||||
#[test]
|
||||
fn halftone_channels_follow_rotation_and_reflection() {
|
||||
let screens = |p: Value, transforms: &[Value]| {
|
||||
let mut effects = vec![fx("pixelate.colorHalftone", p)];
|
||||
effects.extend(transforms.iter().cloned().map(transform));
|
||||
drawn_screens(&effects)
|
||||
};
|
||||
let defaults = screens(json!({}), &[json!({"rotate": 90})]);
|
||||
assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}");
|
||||
let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]);
|
||||
assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}");
|
||||
let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]);
|
||||
assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}");
|
||||
// One Transform effect reflects, then turns; two apply in the order they are listed.
|
||||
let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25});
|
||||
let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]);
|
||||
assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}");
|
||||
let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]);
|
||||
assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}");
|
||||
}
|
||||
|
||||
/// Only the visible Transform effects listed after a filter that move the art once turn its
|
||||
/// direction; a hidden filter turns too, and a zero scale leaves it as it is.
|
||||
#[test]
|
||||
fn only_earlier_visible_single_map_effects_follow() {
|
||||
let relief = fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top));
|
||||
for params in [
|
||||
json!({"rotate": 90, "objects": false}),
|
||||
json!({"rotate": 90, "copies": 1}),
|
||||
json!({"rotate": 90, "random": true}),
|
||||
json!({"scaleH": 0, "scaleV": 0}),
|
||||
] {
|
||||
assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}");
|
||||
}
|
||||
let mut hidden = transform(json!({"rotate": 90}));
|
||||
hidden.visible = false;
|
||||
assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top));
|
||||
let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))];
|
||||
assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero));
|
||||
// A hidden filter kept when the Transform effect is applied draws turned once it is shown.
|
||||
let mut off = relief;
|
||||
off.visible = false;
|
||||
let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]);
|
||||
assert_eq!(kept.len(), 1);
|
||||
let mut shown = kept[0].clone();
|
||||
shown.visible = true;
|
||||
assert_eq!(drawn_light(&[shown]), Some(Light::Left));
|
||||
}
|
||||
|
||||
/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's
|
||||
/// effects and from each fill's and stroke's.
|
||||
fn lights_in(n: &Node) -> Vec<Light> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
for list in lists {
|
||||
out.extend(drawn_light(list));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The canvas, a fill's own effects, a group's members and export turn the light the same way.
|
||||
#[test]
|
||||
fn nested_and_baked_directions_match_canvas() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let turn = || transform(json!({"rotate": 90}));
|
||||
// A fill's own Transform effect, and the object's Transform effect over its fill.
|
||||
let fill = fill_square(31, vec![relief(), turn()]);
|
||||
let item = fill.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(item.effects()), Some(Light::Left));
|
||||
let mut over = fill_square(32, vec![relief()]);
|
||||
over.appearance.effects = vec![turn()];
|
||||
let item = over.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left));
|
||||
// A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not
|
||||
// Left (Top Left after the first turn, then Left after the second).
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let mut both = fill_square(37, vec![relief(), thirty()]);
|
||||
both.appearance.effects = vec![thirty()];
|
||||
let item = both.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft));
|
||||
// A group's Transform effect over a member's own filter and its fill's.
|
||||
let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left; 2]);
|
||||
// Baked for export: the Transform effect is applied and the filter keeps the turned light.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap();
|
||||
d.insert(Some(layer), 1, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = baked.node(NodeId(36)).unwrap();
|
||||
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects);
|
||||
assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left));
|
||||
for id in [34, 35] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once:
|
||||
/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's).
|
||||
#[test]
|
||||
fn nested_group_turns_round_the_light_once() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]);
|
||||
let outer = group(40, vec![inner], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &outer).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [42, 43] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}");
|
||||
}
|
||||
// Three groups make 90°: Left, not Bottom Left.
|
||||
let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &three).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left]);
|
||||
}
|
||||
|
||||
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
|
||||
/// before the 3D effect, as it does without the 3D effect.
|
||||
#[test]
|
||||
@@ -556,7 +835,7 @@ fn a_groups_transform_moves_its_members_shadows() {
|
||||
}
|
||||
|
||||
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
|
||||
/// they are, as it leaves the shadows listed before it in its own effects.
|
||||
/// they are.
|
||||
#[test]
|
||||
fn a_groups_copying_transform_leaves_its_members_shadows() {
|
||||
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
|
||||
@@ -567,6 +846,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer of `members` with `effects` of its own.
|
||||
fn layer(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
|
||||
let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = members.into_iter().map(std::sync::Arc::new).collect();
|
||||
}
|
||||
l.appearance.effects = effects;
|
||||
l
|
||||
}
|
||||
|
||||
/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order.
|
||||
fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> {
|
||||
art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect()
|
||||
}
|
||||
|
||||
fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y))
|
||||
}
|
||||
|
||||
/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed
|
||||
/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and
|
||||
/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and
|
||||
/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not
|
||||
/// scaled a second time. A layer's art stays a layer.
|
||||
#[test]
|
||||
fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() {
|
||||
let cases = [
|
||||
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]),
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect();
|
||||
for container in ["group", "layer"] {
|
||||
let members = vec![square(101, vec![]), square(102, vec![])];
|
||||
let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())];
|
||||
let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) };
|
||||
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}");
|
||||
let art = crate::evaluate_container(None, &n).unwrap();
|
||||
assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}");
|
||||
assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects);
|
||||
let drawn = copy_shadows(&art);
|
||||
assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}");
|
||||
assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none");
|
||||
for c in art.children().into_iter().flatten() {
|
||||
assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}");
|
||||
}
|
||||
let b = baked(n);
|
||||
assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's copying Transform effect leaves its members' own shadows on each copy as they are,
|
||||
/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip
|
||||
/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has
|
||||
/// Transform Objects off, leaves the group's shadows on the group.
|
||||
#[test]
|
||||
fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() {
|
||||
let g = group(
|
||||
110,
|
||||
vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])],
|
||||
vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)],
|
||||
);
|
||||
assert_eq!(crate::outer_effects(&g).len(), 2);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art));
|
||||
|
||||
let mut clip = square(121, vec![]);
|
||||
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]);
|
||||
if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind {
|
||||
*clip = true;
|
||||
}
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert!(!art.clips());
|
||||
assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}");
|
||||
assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art));
|
||||
|
||||
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
|
||||
let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
assert_eq!(crate::outer_effects(&g).len(), 2, "{params}");
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow");
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without
|
||||
/// one, and no shadow is left without its copy.
|
||||
#[test]
|
||||
fn a_groups_copies_past_the_budget_each_keep_their_shadow() {
|
||||
let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
let paths = paths_in(&art);
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow.
|
||||
#[test]
|
||||
fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() {
|
||||
let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None });
|
||||
let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]);
|
||||
let art = crate::evaluate_container(None, &l).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert_eq!(ch.len(), 4, "three copies, then the guide");
|
||||
assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1);
|
||||
assert_eq!(shadows_in(&art).len(), 3);
|
||||
}
|
||||
|
||||
/// The bounds of every node with `id` under `art`, in order.
|
||||
fn bounds_of(art: &Node, id: u64) -> Vec<Rect> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.id == NodeId(id)
|
||||
&& let Some(b) = m.geometric_bounds()
|
||||
{
|
||||
out.push(b);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn rects_near(a: &[Rect], b: &[Rect]) -> bool {
|
||||
let near = |p: f64, q: f64| (p - q).abs() < 1e-6;
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1))
|
||||
}
|
||||
|
||||
/// A group with a fill of its own and only a shadow before its copying Transform effect applies
|
||||
/// its members' own effects before it copies them, as a group without a fill does: a member's own
|
||||
/// move is turned with each copy.
|
||||
#[test]
|
||||
fn a_painted_groups_copies_take_their_members_own_effects_first() {
|
||||
let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])];
|
||||
let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))];
|
||||
let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap();
|
||||
let mut painted = group(170, members(), effects());
|
||||
*painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
painted.appearance.effects = effects();
|
||||
let art = crate::evaluate_container(None, &painted).unwrap();
|
||||
let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171));
|
||||
assert!(!want.is_empty());
|
||||
assert!(rects_near(&got, &want), "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
/// A layer's copies are made about the bounds of its visible members, as the layer measures them:
|
||||
/// a hidden member does not move the center that a reflected copy turns about.
|
||||
#[test]
|
||||
fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() {
|
||||
let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]);
|
||||
hidden.visible = false;
|
||||
let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]);
|
||||
let art = crate::evaluate_container(None, &l).unwrap();
|
||||
let got = bounds_of(&art, 181);
|
||||
assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}");
|
||||
}
|
||||
|
||||
/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each
|
||||
/// copy of a later one, drawn and baked.
|
||||
#[test]
|
||||
fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() {
|
||||
let g = || {
|
||||
group(
|
||||
190,
|
||||
vec![square(191, vec![])],
|
||||
vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))],
|
||||
)
|
||||
};
|
||||
let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)];
|
||||
let art = crate::evaluate_container(None, &g()).unwrap();
|
||||
assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art));
|
||||
let b = baked(g());
|
||||
assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b));
|
||||
}
|
||||
|
||||
/// A group holding type whose Transform effect only moves its copies, baked for export, gives each
|
||||
/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type
|
||||
/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs
|
||||
/// and the test is skipped.
|
||||
#[test]
|
||||
fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
|
||||
if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
|
||||
let b = baked(g);
|
||||
assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b));
|
||||
}
|
||||
|
||||
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
|
||||
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
|
||||
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
|
||||
@@ -591,8 +1068,8 @@ fn a_groups_transform_applies_after_its_members_own() {
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
|
||||
/// makes copies leaves them.
|
||||
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that
|
||||
/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`].
|
||||
#[test]
|
||||
fn an_objects_transform_moves_its_fills_shadows() {
|
||||
let cases = [
|
||||
@@ -600,7 +1077,6 @@ fn an_objects_transform_moves_its_fills_shadows() {
|
||||
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
|
||||
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
|
||||
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
|
||||
];
|
||||
for (params, want) in cases {
|
||||
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
|
||||
@@ -991,3 +1467,300 @@ fn copies_past_the_budget_each_keep_their_shadow() {
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
|
||||
/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are
|
||||
/// `effects`.
|
||||
fn one_row(mut n: Node, stroke: bool, effects: Vec<Effect>) -> Node {
|
||||
let mut item = if stroke {
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))
|
||||
} else {
|
||||
n.appearance.items.remove(0)
|
||||
};
|
||||
*item.effects_mut() = effects;
|
||||
n.appearance.items = vec![item];
|
||||
n
|
||||
}
|
||||
|
||||
/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur.
|
||||
type CopyingCase = (Value, Vec<(f64, f64)>, Vec<f64>);
|
||||
|
||||
/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4
|
||||
/// before it: the params, each copy's offset and each copy's blur, the last copy first.
|
||||
fn copying_cases() -> Vec<CopyingCase> {
|
||||
vec![
|
||||
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
|
||||
// Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned.
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
(
|
||||
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}),
|
||||
vec![(0.0, -20.0), (10.0, 0.0)],
|
||||
vec![8.0, 4.0],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the
|
||||
/// offset and blur `want` and `blurs` give it, the last copy first.
|
||||
fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) {
|
||||
assert!(crate::has_transform_art(n), "{what}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}");
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, want), "{what}: {how} {drawn:?}");
|
||||
let b = shadow_blurs_in(&art);
|
||||
assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed
|
||||
/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy,
|
||||
/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is.
|
||||
#[test]
|
||||
fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// A Transform effect that makes copies before the shadow: its copies make one piece, which
|
||||
// the Transform effect after the shadow copies, each copy with its own shadow.
|
||||
let effects =
|
||||
vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))];
|
||||
let n = one_row(square(95, vec![]), stroke, effects);
|
||||
assert!(crate::has_transform_art(&n), "stroke {stroke}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect
|
||||
/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's
|
||||
/// copies do, with or without options of its own: drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() {
|
||||
for stroke in [false, true] {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())];
|
||||
let n = one_row(square(102, vec![]), stroke, effects);
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by
|
||||
/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and
|
||||
/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() {
|
||||
for (params, want, blurs) in copying_cases() {
|
||||
for stroke in [false, true] {
|
||||
let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]);
|
||||
n.appearance.effects = vec![transform(params.clone())];
|
||||
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
|
||||
}
|
||||
// Both a fill and a stroke: only the fill has the shadow.
|
||||
let mut n = square(97, vec![transform(params.clone())]);
|
||||
if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
|
||||
s.paint = Paint::solid(Color::BLACK);
|
||||
s.width = 2.0;
|
||||
}
|
||||
*n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)];
|
||||
assert!(crate::has_transform_art(&n), "{params}");
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
let drawn = shadows_in(&art);
|
||||
assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of
|
||||
/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has
|
||||
/// Transform Objects off, draws the fill as before, without art.
|
||||
#[test]
|
||||
fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() {
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
|
||||
let n = one_row(square(98, vec![]), false, effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
|
||||
{
|
||||
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art));
|
||||
assert_eq!(paths_in(&art), 2, "{how}");
|
||||
}
|
||||
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
|
||||
assert!(!crate::has_transform_art(&n), "{params}");
|
||||
assert!(!crate::has_copied_row_raster(&n), "{params}");
|
||||
}
|
||||
// A shadow between two Transform effects that make copies paints on what the second one
|
||||
// copies, so the fill is drawn as before, without art.
|
||||
let copies = transform(json!({"rotate": 90, "copies": 1}));
|
||||
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]);
|
||||
assert!(!crate::has_copied_row_raster(&n));
|
||||
assert!(!crate::has_transform_art(&n));
|
||||
}
|
||||
|
||||
/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow,
|
||||
/// and so do those of an object's Transform effect for its fill's shadow.
|
||||
#[test]
|
||||
fn row_copies_past_the_budget_each_keep_their_shadow() {
|
||||
let copies = transform(json!({"moveV": 50, "copies": 1000}));
|
||||
let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]);
|
||||
let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]);
|
||||
owner.appearance.effects = vec![copies];
|
||||
for n in [own, owner] {
|
||||
let art = crate::reshape(None, &n, None).unwrap();
|
||||
let paths = paths_in(&art);
|
||||
assert!(paths > 1 && paths < 1001, "{paths}");
|
||||
assert_eq!(shadows_in(&art).len(), paths);
|
||||
}
|
||||
}
|
||||
|
||||
/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`.
|
||||
fn type_node(id: u64, effects: Vec<Effect>) -> Node {
|
||||
use vectorcraft_doc::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style))));
|
||||
n.appearance.effects = effects;
|
||||
n
|
||||
}
|
||||
|
||||
/// An instance at (50, 50) with `effects` of a symbol, and the symbol's art: a black 20 pt square
|
||||
/// centered on its origin.
|
||||
fn instance(id: u64, effects: Vec<Effect>) -> (Node, Node) {
|
||||
let art = Node::path(
|
||||
NodeId(900),
|
||||
shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
let mut n = Node::new(NodeId(id), vectorcraft_doc::NodeKind::SymbolInstance { symbol: "Square".into(), xf: Affine::translate((50.0, 50.0)) });
|
||||
n.appearance.effects = effects;
|
||||
(n, art)
|
||||
}
|
||||
|
||||
/// Type, an image and a symbol instance with a Transform effect that makes copies give each copy
|
||||
/// the shadow listed before it, turned and scaled with that copy, the last copy lowest: drawn and
|
||||
/// expanded. The object paints none around all of them, and a shadow listed after the Transform
|
||||
/// effect still paints once around them. Built without fonts, type lays out no glyphs and only the
|
||||
/// image and the instance are checked.
|
||||
#[test]
|
||||
fn each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it() {
|
||||
let fonts = crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0);
|
||||
if !fonts {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
}
|
||||
let objects = |effects: Vec<Effect>| {
|
||||
let (inst, art) = instance(96, effects.clone());
|
||||
let mut out = vec![("image", image(97, effects.clone()), None), ("instance", inst, Some(art))];
|
||||
if fonts {
|
||||
out.push(("type", type_node(95, effects), None));
|
||||
}
|
||||
out
|
||||
};
|
||||
let cases = [
|
||||
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
|
||||
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
|
||||
];
|
||||
for (params, want, blurs) in cases {
|
||||
for (kind, n, symbol) in objects(vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]) {
|
||||
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{kind} {params}");
|
||||
let symbol = symbol.as_ref();
|
||||
for (how, drawn) in [("drawn", crate::reshape(None, &n, symbol)), ("expanded", expand_outlined(None, &n, symbol))] {
|
||||
let drawn = drawn.unwrap_or_else(|| panic!("{kind} {params}: {how}"));
|
||||
assert_eq!(drawn.children().map_or(0, Vec::len), want.len(), "{kind} {params}: {how} copies");
|
||||
assert!(drawn.appearance.effects.is_empty(), "{kind} {params}: {how} {:?}", drawn.appearance.effects);
|
||||
assert!(near(&shadows_in(&drawn), &want), "{kind} {params}: {how} {:?}", shadows_in(&drawn));
|
||||
let b = shadow_blurs_in(&drawn);
|
||||
assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{kind} {params}: {how} blurs {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
|
||||
for (kind, n, symbol) in objects(effects) {
|
||||
assert_eq!(crate::outer_effects(&n).len(), 2, "{kind}");
|
||||
let drawn = crate::reshape(None, &n, symbol.as_ref()).unwrap();
|
||||
assert!(near(&shadows_in(&drawn), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{kind}: {:?}", shadows_in(&drawn));
|
||||
}
|
||||
}
|
||||
|
||||
/// Type whose Transform effect only moves its copies, baked for export, gives each copy the shadow
|
||||
/// listed before that effect, as the canvas draws it, rather than staying type under one shadow.
|
||||
#[test]
|
||||
fn baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each() {
|
||||
if !crate::outline_text(&type_node(99, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let n = type_node(99, vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]);
|
||||
let drawn = baked(n);
|
||||
assert!(near(&shadows_in(&drawn), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&drawn));
|
||||
}
|
||||
|
||||
/// Type with a fill whose own geometry effects reshape it keeps one set of raster effects around
|
||||
/// all the copies.
|
||||
#[test]
|
||||
fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() {
|
||||
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let mut filled = type_node(98, effects.clone());
|
||||
filled.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
|
||||
effects: vec![fx("path.offsetPath", json!({"offset": 2}))],
|
||||
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
|
||||
}));
|
||||
assert_eq!(crate::outer_effects(&filled).len(), 2);
|
||||
}
|
||||
|
||||
/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy
|
||||
/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's
|
||||
/// first Transform effect and for one listed after a Transform effect with Transform Patterns on.
|
||||
/// Drawn, expanded and baked.
|
||||
#[test]
|
||||
fn type_carries_its_fills_shadow_on_each_copy() {
|
||||
let filled = |mut n: Node, effects: Vec<Effect>| {
|
||||
n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
|
||||
effects,
|
||||
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
|
||||
}));
|
||||
n
|
||||
};
|
||||
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
|
||||
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
|
||||
return;
|
||||
}
|
||||
let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
for (what, effects) in [("first", copying), ("later", later)] {
|
||||
let n = filled(type_node(95, vec![]), effects);
|
||||
for (how, art) in
|
||||
[("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))]
|
||||
{
|
||||
let art = art.unwrap_or_else(|| panic!("{what}: {how}"));
|
||||
assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art));
|
||||
// The two shadows are on two objects 100 pt apart: the type and its copy.
|
||||
let mut lefts = vec![];
|
||||
art.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::<usize>();
|
||||
if let Some(b) = m.geometric_bounds() {
|
||||
lefts.extend(std::iter::repeat_n(b.x0, shadows));
|
||||
}
|
||||
});
|
||||
lefts.sort_by(f64::total_cmp);
|
||||
assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live
|
||||
//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text
|
||||
//! space, placed by the transform and filled.
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign};
|
||||
use vectorcraft_geom::{Affine, FillRule, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
/// A black run with a red stroke of `width` and round joins.
|
||||
fn style(width: f64) -> CharStyle {
|
||||
CharStyle {
|
||||
fill: Paint::solid(Color::BLACK),
|
||||
stroke: Paint::solid(red()),
|
||||
stroke_width: width,
|
||||
stroke_join: LineJoin::Round,
|
||||
..CharStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 x 10 square in text space standing in for a glyph.
|
||||
fn square() -> Node {
|
||||
Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default())
|
||||
}
|
||||
|
||||
fn area(n: &Node) -> f64 {
|
||||
vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uneven_scale_fills_the_stroke_the_canvas_paints() {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill");
|
||||
assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK));
|
||||
assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0));
|
||||
assert!(stroke.appearance.stroke().is_none());
|
||||
assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red()));
|
||||
assert_eq!(stroke.id, NodeId(7));
|
||||
// 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones.
|
||||
let b = stroke.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}");
|
||||
// The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide.
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() {
|
||||
for (xf, weight) in [
|
||||
(Affine::translate((5.0, 5.0)), 4.0),
|
||||
(Affine::scale(2.0), 8.0),
|
||||
(Affine::rotate(0.5) * Affine::scale(2.0), 8.0),
|
||||
(Affine::scale_non_uniform(-2.0, 2.0), 8.0),
|
||||
] {
|
||||
let mut piece = square();
|
||||
assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}");
|
||||
let st = piece.appearance.stroke().expect("a live stroke");
|
||||
assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width);
|
||||
assert_eq!(st.join, LineJoin::Round);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shears_and_flattening_transforms_fill_the_stroke() {
|
||||
// A shear keeps the area.
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke");
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke));
|
||||
// Flattened to a line or a point: no division by the determinant, nothing non-finite.
|
||||
for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none());
|
||||
if let Some(b) = stroke.geometric_bounds() {
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_options_shape_the_filled_stroke_in_text_space() {
|
||||
let xf = Affine::scale_non_uniform(3.0, 1.0);
|
||||
let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf);
|
||||
// No stroke, or no weight: nothing is filled.
|
||||
assert!(filled(style(0.0)).is_none());
|
||||
assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none());
|
||||
// Inside and outside alignment are kept to their side of the square before it is scaled.
|
||||
let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap();
|
||||
assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)));
|
||||
assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside));
|
||||
let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap();
|
||||
assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds());
|
||||
// Dashes are laid out along the square in text space: half of each 10 pt is painted.
|
||||
let solid = area(&filled(style(1.0)).unwrap());
|
||||
let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() };
|
||||
let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap());
|
||||
assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() {
|
||||
let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)];
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap();
|
||||
let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
// Fitted across the stroke's box in text space (the square grown by half the weight), then scaled.
|
||||
let geom = g.geom.expect("placed");
|
||||
assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}");
|
||||
}
|
||||
@@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
vectorcraft-render = { workspace = true }
|
||||
vectorcraft-pathops = { workspace = true }
|
||||
# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines).
|
||||
vectorcraft-three-d = { workspace = true }
|
||||
vectorcraft-brush = { workspace = true }
|
||||
vectorcraft-trace = { workspace = true }
|
||||
vectorcraft-svg = { workspace = true }
|
||||
@@ -44,16 +46,16 @@ vectorcraft-js = { workspace = true }
|
||||
# The commands' parameter schemas (schemas.rs).
|
||||
vectorcraft-apischema = { workspace = true }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
jxl-color = { workspace = true }
|
||||
jxl-grid = { workspace = true }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
|
||||
# Pure Rust, no unsafe; pinned at the version photocraft-heif uses.
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true }
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
roxmltree = "0.21"
|
||||
craft-xml = { workspace = true }
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
kurbo = { workspace = true }
|
||||
@@ -78,6 +80,16 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "pa
|
||||
rayon = { version = "1.12", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
zune-jpegxl = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
# JPEG XL files for the import fuzz tests (tests/import_fuzz.rs).
|
||||
craft-jxl = { workspace = true }
|
||||
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
|
||||
# tests/group3_reference.rs compares it with.
|
||||
hayro-ccitt = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true, features = ["synth"] }
|
||||
crc32fast = { workspace = true }
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
@@ -89,9 +101,6 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
zune-jpegxl = { workspace = true }
|
||||
zune-core = { workspace = true }
|
||||
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
|
||||
vectorcraft-js = { workspace = true }
|
||||
# A bundled font's own glyph boxes, for the glyph bounds tests.
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time
|
||||
//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500,
|
||||
//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each
|
||||
//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same
|
||||
//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks
|
||||
//! through the paths already added), and one `Selection::set` call followed by the anchors. It
|
||||
//! checks that both give the same selection, every field, before it times them, and then times the
|
||||
//! whole command once per run on the 2,000-path document.
|
||||
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run
|
||||
//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in
|
||||
//! ms; elsewhere they are wall times.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
/// The anchors of each path, or of each subpath of the one compound path.
|
||||
const ANCHORS: usize = 10;
|
||||
|
||||
/// The builds of the selection in each timed run; a row gives the time of one build.
|
||||
const REPS: usize = 20;
|
||||
|
||||
/// What the command selects for one cut end: the path and its anchor (subpath, anchor).
|
||||
type Pick = (NodeId, (usize, usize));
|
||||
|
||||
/// A way of building the selection from the cut ends.
|
||||
type Rebuild = fn(&mut Selection, &[Pick]);
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
|
||||
fn measure(f: impl FnOnce()) -> f64 {
|
||||
match thread_cpu_ns() {
|
||||
Some(start) => {
|
||||
f();
|
||||
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
|
||||
}
|
||||
None => {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built by clearing it and adding each path in turn.
|
||||
fn one_by_one(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built with one `Selection::set` call, as the command builds it.
|
||||
fn one_call(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`.
|
||||
fn row(row: usize) -> SubPath {
|
||||
let y = row as f64 * 20.0;
|
||||
SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false)
|
||||
}
|
||||
|
||||
/// A session with the paths in `paths` and every anchor of theirs but the two ends of each
|
||||
/// subpath direct-selected (a path with all its anchors selected counts as selected whole).
|
||||
fn fixture(paths: Vec<PathData>) -> Session {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let mut items = vec![];
|
||||
for pd in paths {
|
||||
let id = doc.alloc_id();
|
||||
let refs: Vec<[usize; 2]> =
|
||||
pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect();
|
||||
doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
items.push(json!({"id": id.0, "anchors": refs}));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc, None);
|
||||
exec(&mut s, "select.anchorsMany", json!({"items": items}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The cut ends the command selects, in the order it selects them: read back from the selection it
|
||||
/// leaves, which holds each cut path once in that order.
|
||||
fn picked_after_cut(s: &Session) -> Vec<Pick> {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect()
|
||||
}
|
||||
|
||||
fn bench(name: &str, paths: impl Fn() -> Vec<PathData>) {
|
||||
let mut s = fixture(paths());
|
||||
exec(&mut s, "path.cutAtAnchors", json!({}));
|
||||
let picked = picked_after_cut(&s);
|
||||
let mut start = Selection::default();
|
||||
one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]);
|
||||
let (mut a, mut b) = (start.clone(), start.clone());
|
||||
one_by_one(&mut a, &picked);
|
||||
one_call(&mut b, &picked);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
let run = |f: Rebuild, out: &mut Vec<f64>| {
|
||||
let ms = measure(|| {
|
||||
for _ in 0..REPS {
|
||||
let mut sel = start.clone();
|
||||
f(&mut sel, black_box(&picked));
|
||||
black_box(&sel);
|
||||
}
|
||||
});
|
||||
out.push(ms / REPS as f64);
|
||||
};
|
||||
if i % 2 == 0 {
|
||||
run(one_by_one, &mut old);
|
||||
run(one_call, &mut new);
|
||||
} else {
|
||||
run(one_call, &mut new);
|
||||
run(one_by_one, &mut old);
|
||||
}
|
||||
}
|
||||
let (old, new) = (median(old), median(new));
|
||||
println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
|
||||
println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup");
|
||||
for n in [500, 2_000, 5_000] {
|
||||
bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect());
|
||||
}
|
||||
bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]);
|
||||
let whole: Vec<f64> = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect());
|
||||
measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({})))))
|
||||
})
|
||||
.collect();
|
||||
println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
|
||||
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
|
||||
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
|
||||
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
|
||||
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
|
||||
//! times the whole `select.object.directionHandles` command.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
|
||||
//! times and gives the time of one.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
|
||||
fn document(n: usize) -> Document {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let square = |b: &mut DocBuilder, i: usize| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
};
|
||||
let grouped = n / 10;
|
||||
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
|
||||
b.group(kids, false);
|
||||
for i in grouped..n {
|
||||
if i == n / 2 {
|
||||
b.layer("Layer 2");
|
||||
}
|
||||
let node = square(&mut b, i);
|
||||
b.add(node);
|
||||
}
|
||||
b.build()
|
||||
}
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
|
||||
fn with_set(sel: &mut Selection, items: Items) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<44} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths");
|
||||
let mut s = Session::new();
|
||||
s.add_document(document(n), None);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let start = s.doc().unwrap().selection.clone();
|
||||
s.execute("select.object.directionHandles", &json!({})).unwrap();
|
||||
let command = s.doc().unwrap().selection.clone();
|
||||
// The paths and anchors the command selects, in its order.
|
||||
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
|
||||
assert_eq!(items.len(), n);
|
||||
|
||||
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
|
||||
let mut last = Selection::default();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
|
||||
let t = ms(|| {
|
||||
for (sel, it) in &mut work {
|
||||
f(sel, black_box(std::mem::take(it)));
|
||||
}
|
||||
});
|
||||
last = work.pop().unwrap().0;
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(one_by_one);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let mut want = start.clone();
|
||||
with_set(&mut want, items.clone());
|
||||
assert_eq!(want.objects, command.objects);
|
||||
assert_eq!(want.anchors, command.anchors);
|
||||
row("selection, one add per path", old);
|
||||
row("selection, one set call", new);
|
||||
println!(" {:<44} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
|
||||
})
|
||||
.collect();
|
||||
row("select.object.directionHandles, whole command", median(runs));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -98,6 +98,8 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
@@ -233,11 +235,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
|
||||
/// editing and symbol editing mode isolate their own layer, which does not count here; an object
|
||||
/// isolated inside them counts.
|
||||
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> {
|
||||
st.isolation.filter(|l| {
|
||||
!st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
})
|
||||
vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation)
|
||||
}
|
||||
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
|
||||
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
|
||||
@@ -895,6 +893,10 @@ pub use buildcmds::live_paint_gaps;
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
|
||||
/// frame without running the command).
|
||||
pub use brushsym::current_symbol;
|
||||
|
||||
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
|
||||
/// Data window reads files by it too).
|
||||
pub use variablecmds::utf16_order_without_mark;
|
||||
|
||||
@@ -8,6 +8,7 @@ mod contour;
|
||||
mod cutting;
|
||||
mod document;
|
||||
mod image;
|
||||
mod packaging;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
@@ -15,6 +16,7 @@ mod shapes;
|
||||
mod typetools;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(cutting::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(image::specs());
|
||||
v.extend(packaging::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply as Filter",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed}",
|
||||
"{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step (none when nothing changes); their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}",
|
||||
has_selection,
|
||||
filter
|
||||
),
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Ink Fixes",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
|
||||
has_doc,
|
||||
print_fixes::run
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Nearest Swatch",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
"{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step (none when nothing changes): a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}",
|
||||
has_selection,
|
||||
nearest::apply
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Fill to Stroke",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
"{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}",
|
||||
has_doc,
|
||||
|s, p| copy_paint(s, p, true)
|
||||
),
|
||||
@@ -147,9 +147,8 @@ fn is_of_kind(d: &Document, n: &Node, kind: &str) -> bool {
|
||||
|
||||
/// Are the encoded image `bytes` grayscale or 1-bit? Reads only the header.
|
||||
fn is_gray(bytes: &[u8]) -> bool {
|
||||
use image::ImageDecoder as _;
|
||||
let decoder = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok());
|
||||
decoder.is_some_and(|d| matches!(d.color_type(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16))
|
||||
craft_image_codecs::decode(bytes)
|
||||
.is_ok_and(|img| matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA))
|
||||
}
|
||||
|
||||
fn filter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -259,7 +258,10 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result<Value> {
|
||||
// The graph keeps the paint its series marks and labels now have.
|
||||
let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written);
|
||||
let labels = super::super::graph::capture_label_styles(d, &ids, ©_run);
|
||||
Ok(objects + usize::from(series || labels))
|
||||
let painted: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
|
||||
// A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it.
|
||||
let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written);
|
||||
Ok(objects + usize::from(series || labels || lines))
|
||||
})?;
|
||||
}
|
||||
// The defaults for new art change the same way, as Swap Fill and Stroke changes them.
|
||||
|
||||
@@ -111,7 +111,41 @@ fn image(s: &mut Session, key: &str, blob: vectorcraft_doc::ImageBlob, x: f64) -
|
||||
|
||||
fn png(img: image::DynamicImage) -> vectorcraft_doc::ImageBlob {
|
||||
let mut bytes = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
{
|
||||
let __dyn: image::DynamicImage = img;
|
||||
let (__w, __h) = (__dyn.width(), __dyn.height());
|
||||
let (__layout, __sample, __raw) = match __dyn {
|
||||
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLuma16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Gray,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageLumaA16(b) => (
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgb16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgba16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
|
||||
};
|
||||
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
|
||||
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map(|__b| bytes.extend_from_slice(&__b))
|
||||
}
|
||||
.unwrap();
|
||||
vectorcraft_doc::ImageBlob::png(bytes)
|
||||
}
|
||||
|
||||
|
||||
@@ -228,7 +228,41 @@ fn export_all_open_documents_writes_one_file_each() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "name": "pic"})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
{
|
||||
let __dyn: image::DynamicImage = (image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]))).into();
|
||||
let (__w, __h) = (__dyn.width(), __dyn.height());
|
||||
let (__layout, __sample, __raw) = match __dyn {
|
||||
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLuma16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Gray,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageLumaA16(b) => (
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgb16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgba16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
|
||||
};
|
||||
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
|
||||
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map(|__b| png.extend_from_slice(&__b))
|
||||
}
|
||||
.unwrap();
|
||||
s.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("document.save", &json!({"path": dir.join("pic.svg"), "format": "svg", "options": {"images": "link"}})).unwrap();
|
||||
let saved: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().is_file()).collect();
|
||||
|
||||
@@ -13,10 +13,9 @@ mod tests;
|
||||
pub(crate) use mask::refresh as refresh_color_masks;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Cursor;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
|
||||
use image::{ImageBuffer, Rgba};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
|
||||
@@ -412,23 +411,36 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
|
||||
bad(cmd, "every pixel matches the background: no image would be left")
|
||||
});
|
||||
}
|
||||
let out = match (px, gray) {
|
||||
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
|
||||
(Pixels::Sixteen(img), false) => DynamicImage::ImageRgba16(img),
|
||||
(Pixels::Eight(img), true) => {
|
||||
DynamicImage::ImageLumaA8(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
|
||||
let raw = match (px, gray) {
|
||||
(Pixels::Eight(img), false) => {
|
||||
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw())
|
||||
}
|
||||
(Pixels::Sixteen(img), true) => {
|
||||
DynamicImage::ImageLumaA16(ImageBuffer::from_fn(w, h, |x, y| LumaA([img.get_pixel(x, y).0[0], img.get_pixel(x, y).0[3]])))
|
||||
}
|
||||
};
|
||||
let mut png = Vec::new();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
if let Some(icc) = icc {
|
||||
use image::ImageEncoder as _;
|
||||
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
(Pixels::Sixteen(img), false) => craft_image_codecs::Image::from_raw(
|
||||
w,
|
||||
h,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
img.into_raw().into_iter().flat_map(u16::to_ne_bytes).collect(),
|
||||
),
|
||||
(Pixels::Eight(img), true) => craft_image_codecs::Image::from_raw(
|
||||
w,
|
||||
h,
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).collect(),
|
||||
),
|
||||
(Pixels::Sixteen(img), true) => craft_image_codecs::Image::from_raw(
|
||||
w,
|
||||
h,
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
img.pixels().flat_map(|p| [p.0[0], p.0[3]]).flat_map(u16::to_ne_bytes).collect(),
|
||||
),
|
||||
}
|
||||
out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
.map_err(|e| bad(cmd, e.to_string()))?
|
||||
.with_icc(icc);
|
||||
let mut png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map_err(|e| bad(cmd, e.to_string()))?;
|
||||
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
|
||||
if let Some(r) = ppi::resolution(&blob.bytes) {
|
||||
png = ppi::with_png_resolution(&png, r);
|
||||
@@ -436,37 +448,70 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
|
||||
Ok(Some(Cleared { blob: ImageBlob::png(png), width: w, height: h, cleared }))
|
||||
}
|
||||
|
||||
/// The image's size and the bytes a pixel of it takes to change, read from its header: its
|
||||
/// samples as decoded (bitmaps as 8-bit gray, palettes as RGB, or RGBA with a transparent entry),
|
||||
/// those worked on and kept for the PNG, and the work. A header that gives only the size (one
|
||||
/// whose file can't hold its pixels) counts the fewest: one 8-bit sample. `None` when the header
|
||||
/// doesn't say.
|
||||
fn header_pixels(bytes: &[u8]) -> Option<(u32, u32, u64)> {
|
||||
use craft_image_codecs::RasterColorType as T;
|
||||
let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() else {
|
||||
return vectorcraft_doc::header_size(bytes).map(|(w, h)| (w, h, 1 + 2 * 4 + WORK_BYTES));
|
||||
};
|
||||
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
|
||||
let channels = match i.color_type {
|
||||
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
|
||||
T::Bitmap => 1,
|
||||
_ => u64::from(i.channels.max(1)),
|
||||
};
|
||||
let samples = channels * if deep { 2 } else { 1 };
|
||||
Some((i.width, i.height, samples + 2 * if deep { 8 } else { 4 } + WORK_BYTES))
|
||||
}
|
||||
|
||||
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
|
||||
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
|
||||
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
|
||||
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
|
||||
let reader = || {
|
||||
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
|
||||
};
|
||||
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
|
||||
// The ICC profile the colors are in goes with them into the PNG.
|
||||
let (w, h, kind, icc) = {
|
||||
use image::ImageDecoder as _;
|
||||
let (w, h) = decoder.dimensions();
|
||||
(w, h, decoder.color_type(), decoder.icc_profile().ok().flatten())
|
||||
};
|
||||
drop(decoder);
|
||||
// The file's pixels, those worked on (as many again for the PNG made of them) and the work,
|
||||
// checked from the header before anything is decoded.
|
||||
let deep = kind.bytes_per_pixel() > kind.channel_count();
|
||||
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
|
||||
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
|
||||
let too_large = |w: u32, h: u32, per_pixel: u64| {
|
||||
u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC)
|
||||
};
|
||||
let header = header_pixels(&blob.bytes);
|
||||
if let Some((w, h, per_pixel)) = header
|
||||
&& too_large(w, h, per_pixel)
|
||||
{
|
||||
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
|
||||
}
|
||||
let mut opts = craft_image_codecs::DecodeOptions::default();
|
||||
opts.limits.max_alloc = MAX_RASTER_ALLOC;
|
||||
let img = craft_image_codecs::decode_with(&blob.bytes, &opts).map_err(|e| match e {
|
||||
// Within the allowance from its header: a file that can't hold the pixels it declares.
|
||||
craft_image_codecs::CodecError::LimitExceeded(_) if header.is_none() => bad(cmd, "the image is too large to change"),
|
||||
_ => bad(cmd, format!("the image's pixels can't be read: {e}")),
|
||||
})?;
|
||||
let (w, h) = img.dimensions();
|
||||
let icc = img.icc.clone();
|
||||
let deep = img.sample_type() == craft_image_codecs::SampleType::U16;
|
||||
let gray = matches!(img.layout(), craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA);
|
||||
let per_pixel = u64::from(img.layout().channels() as u32 * img.sample_type().bytes() as u32) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
|
||||
if too_large(w, h, per_pixel) {
|
||||
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
|
||||
}
|
||||
let mut reader = reader()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
|
||||
#[cfg(test)]
|
||||
DECODES.with(|c| c.set(c.get() + 1));
|
||||
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
|
||||
let px = Arc::new(if deep { Pixels::Sixteen(img.into_rgba16()) } else { Pixels::Eight(img.into_rgba8()) });
|
||||
let px = Arc::new(if deep {
|
||||
let rgba16 = match (img.layout(), img.to_u16_samples()) {
|
||||
(craft_image_codecs::ChannelLayout::Rgba, Some(v)) => v,
|
||||
(craft_image_codecs::ChannelLayout::Rgb, Some(v)) => v.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], u16::MAX]).collect(),
|
||||
(craft_image_codecs::ChannelLayout::GrayA, Some(v)) => v.as_chunks::<2>().0.iter().flat_map(|c| [c[0], c[0], c[0], c[1]]).collect(),
|
||||
(craft_image_codecs::ChannelLayout::Gray, Some(v)) => v.into_iter().flat_map(|g| [g, g, g, u16::MAX]).collect(),
|
||||
_ => img.to_rgba8().into_iter().map(|b| u16::from(b) * 257).collect(),
|
||||
};
|
||||
Pixels::Sixteen(ImageBuffer::from_raw(w, h, rgba16).ok_or_else(|| bad(cmd, "invalid 16-bit pixel buffer"))?)
|
||||
} else {
|
||||
Pixels::Eight(ImageBuffer::from_raw(w, h, img.to_rgba8()).ok_or_else(|| bad(cmd, "invalid 8-bit pixel buffer"))?)
|
||||
});
|
||||
// A kept copy is worked on as a copy: one more set of the pixels worked on.
|
||||
let with_copy = per_pixel + if deep { 8 } else { 4 };
|
||||
if let Some(kept) = kept
|
||||
|
||||
@@ -287,9 +287,7 @@ fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
|
||||
/// read.
|
||||
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
|
||||
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
|
||||
.filter(|(w, h)| *w > 0 && *h > 0)
|
||||
.unwrap_or((width, height))
|
||||
blob.and_then(|b| b.pixel_size()).filter(|(w, h)| *w > 0 && *h > 0).unwrap_or((width, height))
|
||||
}
|
||||
|
||||
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use image::DynamicImage;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -15,7 +13,41 @@ const RED: [u8; 4] = [200, 0, 0, 255];
|
||||
|
||||
fn png(img: DynamicImage) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
{
|
||||
let __dyn: image::DynamicImage = img;
|
||||
let (__w, __h) = (__dyn.width(), __dyn.height());
|
||||
let (__layout, __sample, __raw) = match __dyn {
|
||||
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLuma16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Gray,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageLumaA16(b) => (
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgb16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgba16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
|
||||
};
|
||||
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
|
||||
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map(|__b| out.extend_from_slice(&__b))
|
||||
}
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -138,7 +170,24 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
|
||||
assert_eq!(s.execute(APPLY_COLOR_MASK, &json!({})).unwrap(), json!({"changed": 1, "ids": [id.0]}));
|
||||
let d = doc(&s);
|
||||
assert_eq!((image_of(d, id).key, mask_of(d, id)), (m.key.clone(), None));
|
||||
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
|
||||
assert_eq!(drawn(d, id, 0, 0)[3], 0);
|
||||
assert_eq!(undo_len(&s), steps + 1);
|
||||
@@ -149,7 +198,23 @@ fn applying_the_mask_makes_it_part_of_the_pixels() {
|
||||
fn svg_image(svg: &str) -> DynamicImage {
|
||||
let at = svg.find("data:image/png;base64,").expect("an embedded PNG") + "data:image/png;base64,".len();
|
||||
let end = at + svg[at..].find('"').unwrap();
|
||||
image::load_from_memory(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap()).unwrap()
|
||||
craft_image_codecs::decode(&vectorcraft_format::base64_decode(&svg[at..end]).unwrap())
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -159,7 +224,28 @@ fn outputs_write_the_masked_pixels() {
|
||||
|s: &Session, format: &str| crate::cmd::fileio::encode_all(doc(s), format, &json!({"useArtboards": true})).unwrap().files.remove(0).1;
|
||||
let (png0, svg0, pdf0, eps0) = (export(&s, "png"), export(&s, "svg"), export(&s, "pdf"), export(&s, "eps"));
|
||||
s.execute(COLOR_MASK, &hide_white()).unwrap();
|
||||
let alpha = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(0, 0).0[3];
|
||||
let alpha = |bytes: &[u8]| {
|
||||
craft_image_codecs::decode(bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8()
|
||||
.get_pixel(0, 0)
|
||||
.0[3]
|
||||
};
|
||||
assert_eq!((alpha(&png0), alpha(&export(&s, "png"))), (255, 0), "PNG");
|
||||
let svg_alpha = |bytes: &[u8]| svg_image(std::str::from_utf8(bytes).unwrap()).to_rgba8().get_pixel(0, 0).0[3];
|
||||
assert_eq!((svg_alpha(&svg0), svg_alpha(&export(&s, "svg"))), (255, 0), "SVG");
|
||||
@@ -344,7 +430,24 @@ fn cropping_off_the_pixel_grid_keeps_the_hidden_colors_in_the_pixels() {
|
||||
let d = doc(&s);
|
||||
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
|
||||
assert_eq!(m.from, im.key, "the mask is made for the cut pixels");
|
||||
let own = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let own = craft_image_codecs::decode(&d.images[&im.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert!(own.pixels().all(|p| p.0[3] == 255), "the cut pixels are the image's own, white included");
|
||||
assert_eq!(drawn(d, id, 0, 0)[3], 0, "white is hidden");
|
||||
s.execute(REMOVE_COLOR_MASK, &json!({"ids": [id.0]})).unwrap();
|
||||
@@ -377,7 +480,24 @@ fn applying_a_mask_made_for_older_pixels_makes_it_again_and_keeps_the_size() {
|
||||
assert_eq!((im.width, im.height, mask_of(d, id)), (24, 20, None));
|
||||
let after = d.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert!((after.width() - before.width()).abs() < 1e-9 && (after.height() - before.height()).abs() < 1e-9, "{before:?} {after:?}");
|
||||
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(10, 10).0), (0, RED));
|
||||
}
|
||||
|
||||
@@ -435,7 +555,24 @@ fn another_image_colorized_with_transparency_does_not_change_the_refusal() {
|
||||
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
|
||||
assert_eq!(s.execute(COLOR_MASK, &hide_white()).unwrap()["changed"], 1, "an image colorized with black takes the mask beside the other");
|
||||
let m = mask_of(doc(&s), id).unwrap();
|
||||
let masked = image::load_from_memory(&doc(&s).images[&m.key].bytes).unwrap().to_luma_alpha8();
|
||||
let masked = craft_image_codecs::decode(&doc(&s).images[&m.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_luma_alpha8();
|
||||
assert_eq!((masked.get_pixel(0, 0).0[1], masked.get_pixel(4, 4).0[1]), (0, 255), "white is hidden and black shows");
|
||||
}
|
||||
|
||||
@@ -580,7 +717,24 @@ fn masks_outside_the_layers_are_made_again() {
|
||||
let art = &d.node(holder_id).unwrap().extras().mask.as_ref().unwrap().art;
|
||||
assert_eq!(from(art), key, "in the opacity mask's art");
|
||||
let m = Document::color_mask_of(art).unwrap();
|
||||
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(1, 0).0), (0, RED));
|
||||
}
|
||||
|
||||
@@ -696,7 +850,24 @@ fn a_linked_file_read_again_on_open_takes_the_mask_again() {
|
||||
let d = doc(&s);
|
||||
let (im, m) = (image_of(d, id), mask_of(d, id).unwrap());
|
||||
assert_eq!(m.from, im.key, "made for the file's new pixels");
|
||||
let px = image::load_from_memory(&d.images[&m.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&m.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, [0, 0, 200, 255]));
|
||||
}
|
||||
|
||||
@@ -812,7 +983,24 @@ fn a_live_color_adjustment_recolors_the_image_when_its_masked_pixels_are_missing
|
||||
let NodeKind::Image(im) = &out.kind else { panic!("an image") };
|
||||
assert_ne!(im.key, image_of(&d, id).key, "the expanded image is recolored");
|
||||
assert_eq!(Document::color_mask_of(&out), None, "the expanded image has no mask to make again from the recolored pixels");
|
||||
let px = image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&im.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!(px.get_pixel(1, 1).0, WHITE, "the expanded image shows the white");
|
||||
}
|
||||
|
||||
@@ -1002,6 +1190,23 @@ fn placing_a_document_brings_the_masked_pixels() {
|
||||
}
|
||||
let [(im, placed)] = found.as_slice() else { panic!("one masked image: {found:?}") };
|
||||
assert!(placed.made_for(im) && placed.from != m.from, "the image was renamed and the mask follows: {placed:?}");
|
||||
let px = image::load_from_memory(&d.images[&placed.key].bytes).unwrap().to_rgba8();
|
||||
let px = craft_image_codecs::decode(&d.images[&placed.key].bytes)
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8();
|
||||
assert_eq!((px.get_pixel(0, 0).0[3], px.get_pixel(4, 4).0), (0, RED));
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb};
|
||||
@@ -21,7 +20,41 @@ fn settings(background: Background) -> Settings {
|
||||
|
||||
fn png(img: DynamicImage) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
img.write_to(&mut Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
{
|
||||
let __dyn: image::DynamicImage = img;
|
||||
let (__w, __h) = (__dyn.width(), __dyn.height());
|
||||
let (__layout, __sample, __raw) = match __dyn {
|
||||
image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
|
||||
image::DynamicImage::ImageLuma16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Gray,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageLumaA16(b) => (
|
||||
craft_image_codecs::ChannelLayout::GrayA,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgb16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgb,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
image::DynamicImage::ImageRgba16(b) => (
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U16,
|
||||
b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
|
||||
),
|
||||
other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
|
||||
};
|
||||
let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
|
||||
craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
|
||||
.map(|__b| out.extend_from_slice(&__b))
|
||||
}
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -53,7 +86,32 @@ fn bytes_of(s: &Session, id: NodeId) -> Arc<Vec<u8>> {
|
||||
}
|
||||
|
||||
fn pixels(s: &Session, id: NodeId) -> DynamicImage {
|
||||
image::load_from_memory(&bytes_of(s, id)).unwrap()
|
||||
craft_image_codecs::decode(&bytes_of(s, id))
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(layout, craft_image_codecs::SampleType::U16) => {
|
||||
let v = __cimg.to_u16_samples().unwrap();
|
||||
match layout {
|
||||
craft_image_codecs::ChannelLayout::Gray => image::DynamicImage::ImageLuma16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
|
||||
craft_image_codecs::ChannelLayout::GrayA => image::DynamicImage::ImageLumaA16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
|
||||
craft_image_codecs::ChannelLayout::Rgb => image::DynamicImage::ImageRgb16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
|
||||
_ => image::DynamicImage::ImageRgba16(ImageBuffer::from_raw(__w, __h, v).unwrap()),
|
||||
}
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn alpha(img: &DynamicImage, x: u32, y: u32) -> u8 {
|
||||
@@ -164,13 +222,13 @@ fn preview_steps_on_the_same_pixels_decode_them_once() {
|
||||
/// image with an ICC profile comes out as a run on freshly decoded pixels gives it.
|
||||
#[test]
|
||||
fn reused_pixels_keep_their_depth_gray_and_profile() {
|
||||
use image::{ImageDecoder as _, ImageEncoder as _};
|
||||
let icc = b"a profile's bytes".to_vec();
|
||||
let gray16 = ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 7_000u16 } else { 61_000 }]));
|
||||
let mut bytes = Vec::new();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
|
||||
encoder.set_icc_profile(icc.clone()).unwrap();
|
||||
DynamicImage::ImageLuma16(gray16).write_with_encoder(encoder).unwrap();
|
||||
let raw: Vec<u8> = gray16.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect();
|
||||
let mut cimg =
|
||||
craft_image_codecs::Image::from_raw(8, 8, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U16, raw).unwrap();
|
||||
cimg.icc = Some(icc.clone());
|
||||
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
let decodes = || super::DECODES.with(std::cell::Cell::get);
|
||||
let (mut s, id) = open(&bytes);
|
||||
let start = decodes();
|
||||
@@ -184,8 +242,8 @@ fn reused_pixels_keep_their_depth_gray_and_profile() {
|
||||
let DynamicImage::ImageLumaA16(out) = pixels(&s, id) else { panic!("16-bit gray with alpha") };
|
||||
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
|
||||
let result = bytes_of(&s, id);
|
||||
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(result.as_slice())).unwrap();
|
||||
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
|
||||
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, result.as_slice()).unwrap();
|
||||
assert_eq!(decoded.icc, Some(icc));
|
||||
}
|
||||
|
||||
/// Once the background is cleared, most edge pixels are clear and a second run clears nothing: the
|
||||
@@ -385,16 +443,22 @@ fn a_gray_image_colorized_with_a_process_color_is_refused() {
|
||||
/// The ICC profile the colors are in stays with them.
|
||||
#[test]
|
||||
fn the_color_profile_is_kept() {
|
||||
use image::{ImageDecoder as _, ImageEncoder as _};
|
||||
let icc = b"a profile's bytes".to_vec();
|
||||
let mut bytes = Vec::new();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut bytes);
|
||||
encoder.set_icc_profile(icc.clone()).unwrap();
|
||||
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
|
||||
let f = framed();
|
||||
let mut cimg = craft_image_codecs::Image::from_raw(
|
||||
f.width(),
|
||||
f.height(),
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
f.into_raw(),
|
||||
)
|
||||
.unwrap();
|
||||
cimg.icc = Some(icc.clone());
|
||||
let bytes = craft_image_codecs::encode(&cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
|
||||
let blob = ImageBlob::png(bytes);
|
||||
let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap();
|
||||
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
|
||||
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
|
||||
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, out.blob.bytes.as_slice()).unwrap();
|
||||
assert_eq!(decoded.icc, Some(icc));
|
||||
}
|
||||
|
||||
/// The resolution the file declares stays with the pixels, so a later Replace or relink sizes the
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
|
||||
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod check;
|
||||
mod roles;
|
||||
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and
|
||||
//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`].
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks};
|
||||
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
||||
use super::roles::{Role, RoleTable, can_carry, role_targets};
|
||||
use crate::{Result, Session};
|
||||
|
||||
const CHECK: &str = "addon.packaging.check";
|
||||
|
||||
/// How far apart the ends of two lines may be and still be joined, in points.
|
||||
const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.packaging.check",
|
||||
"Check Fold Lines",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document; hidden lines are left out, also in a selected group. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate (two cut lines, or two lines that fold of any role), danglingCrease, noSplit, outside (wholly, or in part for tolerance or more), notStraight (a hinge's pieces are not on one straight line), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}",
|
||||
has_doc,
|
||||
check
|
||||
)]
|
||||
}
|
||||
|
||||
/// The English message for an issue (the Fold Lines panel shows it in the interface language).
|
||||
fn message(code: IssueCode, scope: &str) -> &'static str {
|
||||
match code {
|
||||
IssueCode::NoCut if scope == "document" => "No cut lines are in the document.",
|
||||
IssueCode::NoCut if scope == "ids" => "No cut lines are among the given objects.",
|
||||
IssueCode::NoCut => "No cut lines are in the selection.",
|
||||
IssueCode::Open => "The cut lines do not enclose an area.",
|
||||
IssueCode::LooseEnd => "A cut line ends without meeting another cut line.",
|
||||
IssueCode::Gap => "A gap between cut lines was closed.",
|
||||
IssueCode::TooComplex => "The fold lines are too complex to check.",
|
||||
IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.",
|
||||
IssueCode::Duplicate => "Two fold lines lie on top of each other.",
|
||||
IssueCode::DanglingCrease => "A crease ends inside a panel.",
|
||||
IssueCode::NoSplit => "A crease does not divide two panels.",
|
||||
IssueCode::Outside => "A crease lies outside the cut outline, wholly or in part.",
|
||||
IssueCode::NotStraight => "The pieces of a hinge are not on one straight line.",
|
||||
IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.",
|
||||
IssueCode::Ambiguous => "A cut-out area holds other fold lines or another blank.",
|
||||
IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.",
|
||||
IssueCode::NonPrinting => "A fold line is on a non-printing layer.",
|
||||
}
|
||||
}
|
||||
|
||||
/// Every object of the document that can carry a role and is shown: on a shown layer, in shown
|
||||
/// groups, and shown itself.
|
||||
fn shown_targets(d: &Document) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
/// The path of object `n` in document coordinates: a path's own, or a compound path's members'.
|
||||
fn path_of(n: &Node) -> Option<PathData> {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => Some(path.clone()),
|
||||
NodeKind::Compound { children, .. } => Some(PathData::new(
|
||||
children
|
||||
.iter()
|
||||
.filter_map(|c| match &c.kind {
|
||||
NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect(),
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether object `id` is on a layer, or a sublayer, that does not print.
|
||||
fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
|
||||
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
|
||||
}
|
||||
|
||||
fn kind(role: Role) -> LineKind {
|
||||
match role {
|
||||
Role::Cut => LineKind::Cut,
|
||||
Role::Crease => LineKind::Crease,
|
||||
Role::PartialCut => LineKind::PartialCut,
|
||||
Role::Perforation => LineKind::Perforation,
|
||||
}
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let select = switch_or(p, "select", false, CHECK)?;
|
||||
let tolerance = match length_given(p, "tolerance", CHECK)? {
|
||||
None => TOLERANCE.1,
|
||||
Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t,
|
||||
Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))),
|
||||
};
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, CHECK)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Hidden lines are left out in every scope, members of a selected group included.
|
||||
let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>();
|
||||
let (scope, targets) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", shown(role_targets(d, &roots, false).0)),
|
||||
(false, false) => ("selection", shown(role_targets(d, &roots, false).0)),
|
||||
(false, true) => ("document", shown_targets(d)),
|
||||
};
|
||||
let table = RoleTable::of(d);
|
||||
let mut lines = vec![];
|
||||
let mut non_printing = vec![];
|
||||
let mut segments = 0usize;
|
||||
for id in targets {
|
||||
// Once the lines have more segments than the check takes, it reports them as too complex:
|
||||
// the rest are not copied.
|
||||
if segments > MAX_SEGMENTS {
|
||||
break;
|
||||
}
|
||||
let Some(n) = d.node(id) else { continue };
|
||||
let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue };
|
||||
if on_non_printing_layer(d, id) {
|
||||
non_printing.push(id.0);
|
||||
}
|
||||
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
|
||||
}
|
||||
let (found, mut issues) = blanks(&lines, tolerance);
|
||||
if !non_printing.is_empty() {
|
||||
issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None });
|
||||
}
|
||||
let ok = !issues.iter().any(|i| i.code.is_error());
|
||||
let rows: Vec<Value> = issues
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut row = json!({
|
||||
"severity": if i.code.is_error() { "error" } else { "warning" },
|
||||
"code": i.code.id(),
|
||||
"message": message(i.code, scope),
|
||||
"ids": i.keys,
|
||||
});
|
||||
if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) {
|
||||
o.insert("at".into(), json!([at.x, at.y]));
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
if select {
|
||||
let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect();
|
||||
ids.sort_unstable_by_key(|id| id.0);
|
||||
ids.dedup();
|
||||
if !ids.is_empty() {
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({
|
||||
"ok": ok,
|
||||
"blanks": found.len(),
|
||||
"panels": found.iter().map(|b| b.panels.len()).sum::<usize>(),
|
||||
"hinges": found.iter().map(|b| b.hinges.len()).sum::<usize>(),
|
||||
"holes": found.iter().map(|b| b.holes.len()).sum::<usize>(),
|
||||
"issues": rows,
|
||||
"scope": scope,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a
|
||||
//! document.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> u64 {
|
||||
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn role(s: &mut Session, role: &str, ids: &[u64]) {
|
||||
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.check", &p).unwrap()
|
||||
}
|
||||
|
||||
fn codes(r: &Value) -> Vec<&str> {
|
||||
r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect()
|
||||
}
|
||||
|
||||
/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the
|
||||
/// base's four sides creases → (outline, creases).
|
||||
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
|
||||
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
|
||||
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
|
||||
role(s, "cut", &[outline]);
|
||||
role(s, "crease", &creases);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(outline, creases)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tray_checks_clean_with_five_panels_and_four_hinges() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}");
|
||||
assert!(codes(&r).is_empty(), "{r}");
|
||||
assert_eq!(r["scope"], "document");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_or_ids_limit_the_check_to_their_lines() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false)));
|
||||
assert_eq!(codes(&r), ["noCut"]);
|
||||
assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection.");
|
||||
let r = check(&mut s, json!({ "ids": [outline] }));
|
||||
assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}");
|
||||
let r = check(&mut s, json!({ "ids": [creases[1]] }));
|
||||
assert_eq!((r["scope"].as_str(), codes(&r)), (Some("ids"), vec!["noCut"]));
|
||||
assert_eq!(r["issues"][0]["message"], "No cut lines are among the given objects.");
|
||||
// No fold lines at all in the document.
|
||||
let mut s = session();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!(codes(&r), ["noCut"]);
|
||||
assert_eq!(r["issues"][0]["message"], "No cut lines are in the document.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issues_name_their_lines_and_select_selects_them() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
// A slit from the outline that stops in the middle of the base.
|
||||
let slit = path(&mut s, "M190 100 L190 190");
|
||||
role(&mut s, "cut", &[slit]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!(r["ok"], false);
|
||||
let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap();
|
||||
assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}");
|
||||
assert_eq!(loose["at"], json!([190.0, 190.0]));
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays");
|
||||
let r = check(&mut s, json!({ "select": true }));
|
||||
let named: std::collections::BTreeSet<u64> =
|
||||
r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect();
|
||||
let selected: std::collections::BTreeSet<u64> = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
|
||||
assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}");
|
||||
assert!(!selected.contains(&creases[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_check_with_select_leaves_the_selection_alone() {
|
||||
let mut s = session();
|
||||
let (outline, _) = tray(&mut s);
|
||||
s.execute("select.set", &json!({ "ids": [outline] })).unwrap();
|
||||
let r = check(&mut s, json!({ "ids": [outline], "select": true }));
|
||||
assert!(codes(&r).is_empty(), "{r}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), [outline]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tolerance_is_checked_and_joins_gaps_up_to_it() {
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] {
|
||||
let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string();
|
||||
assert!(e.contains("tolerance"), "{e}");
|
||||
}
|
||||
let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string();
|
||||
assert!(e.contains("select"), "{e}");
|
||||
for edge in [json!(0.01), json!(10), json!("2 mm")] {
|
||||
assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true);
|
||||
}
|
||||
// A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt.
|
||||
let mut s = session();
|
||||
tray(&mut s);
|
||||
let slit = path(&mut s, "M190 100 L190 139.5");
|
||||
role(&mut s, "cut", &[slit]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd"));
|
||||
let near = check(&mut s, json!({ "tolerance": 1 }));
|
||||
assert!(!codes(&near).contains(&"looseEnd"), "{near}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
// A hidden crease is not checked while nothing is selected: the tray has three hinges and a
|
||||
// panel joined by none.
|
||||
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
|
||||
// The same in a selected group, and with the group named by `ids`: the hidden member is left
|
||||
// out too.
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3]] })).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap();
|
||||
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
|
||||
for p in [json!({}), json!({ "ids": [group] })] {
|
||||
let r = check(&mut s, p);
|
||||
assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}");
|
||||
}
|
||||
// A cut line on a layer that does not print.
|
||||
let mut s = session();
|
||||
s.execute("layer.new", &json!({ "printable": false })).unwrap();
|
||||
let (outline, _) = tray(&mut s);
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!(r["ok"], true, "a warning only");
|
||||
let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap();
|
||||
assert_eq!(note["severity"], "warning");
|
||||
assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}");
|
||||
assert_eq!(note["message"], "A fold line is on a non-printing layer.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compound_path_and_a_grouped_line_are_checked() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
// A window: a closed cut line in the base, made a compound path with nothing else.
|
||||
let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z");
|
||||
s.execute("select.set", &json!({ "ids": [window] })).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64();
|
||||
let window = compound.unwrap_or(window);
|
||||
role(&mut s, "cut", &[window]);
|
||||
s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let r = check(&mut s, json!({}));
|
||||
assert_eq!(r["scope"], "selection");
|
||||
assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}");
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
|
||||
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
|
||||
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
|
||||
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
|
||||
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
|
||||
//! string, takes its default swatch, named after the role.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Document unknown key: the role table, `{role id: swatch name}`.
|
||||
pub(crate) const ROLES_KEY: &str = "packagingRoles";
|
||||
|
||||
const SET_ROLE: &str = "addon.packaging.setRole";
|
||||
const ROLES: &str = "addon.packaging.roles";
|
||||
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
|
||||
|
||||
/// What a fold line does when the blank is cut and folded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Role {
|
||||
/// Separates the material.
|
||||
Cut,
|
||||
/// A fold.
|
||||
Crease,
|
||||
/// A fold cut part way through the board.
|
||||
PartialCut,
|
||||
/// A fold along a line of cuts.
|
||||
Perforation,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
|
||||
|
||||
/// The role's id in params and in the role table.
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "cut",
|
||||
Role::Crease => "crease",
|
||||
Role::PartialCut => "partialCut",
|
||||
Role::Perforation => "perforation",
|
||||
}
|
||||
}
|
||||
|
||||
/// The role's name, which is also its default swatch's name.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "Cut",
|
||||
Role::Crease => "Crease",
|
||||
Role::PartialCut => "Partial Cut",
|
||||
Role::Perforation => "Perforation",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_id(id: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.id() == id)
|
||||
}
|
||||
|
||||
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
|
||||
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
|
||||
fn color(self) -> Color {
|
||||
match self {
|
||||
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
|
||||
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
|
||||
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
|
||||
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch each role is carried by, in [`Role::ALL`] order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct RoleTable([String; 4]);
|
||||
|
||||
impl RoleTable {
|
||||
/// The document's role table, with each missing or damaged entry at its default. When a damaged
|
||||
/// table names one swatch for two roles, the later role takes its default name instead, or
|
||||
/// "Crease 2" and so on when an earlier role has that.
|
||||
pub(crate) fn of(d: &Document) -> RoleTable {
|
||||
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
|
||||
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
|
||||
for r in Role::ALL {
|
||||
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
|
||||
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
|
||||
_ => {
|
||||
let base = r.name();
|
||||
std::iter::once(base.to_string())
|
||||
.chain((2..).map(|i| format!("{base} {i}")))
|
||||
.find(|n| !names.contains(n))
|
||||
.unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
};
|
||||
names.push(name);
|
||||
}
|
||||
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
|
||||
}
|
||||
|
||||
/// The swatch of `role`.
|
||||
pub(crate) fn swatch(&self, role: Role) -> &str {
|
||||
self.0.get(role.index()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// The role swatch `name` carries.
|
||||
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
|
||||
}
|
||||
|
||||
/// The role of object `n`: the role of the swatch its top stroke is painted with.
|
||||
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
|
||||
if !can_carry(n) {
|
||||
return None;
|
||||
}
|
||||
match &n.appearance.stroke()?.paint {
|
||||
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(&self) -> Value {
|
||||
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
|
||||
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
|
||||
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
|
||||
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
|
||||
/// two roles share a swatch.
|
||||
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
|
||||
let before = RoleTable::of(d);
|
||||
let mut table = before.clone();
|
||||
for r in Role::ALL {
|
||||
let name = table.swatch(r).to_string();
|
||||
let moved = if name == from && global {
|
||||
Some(to.to_string())
|
||||
} else if name == from || (name == to && from != to) {
|
||||
Some(free_role_name(d, &table, r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
if table != before {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
|
||||
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
|
||||
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
|
||||
/// role keeps its name, which the next `setRole` makes a swatch for.
|
||||
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
|
||||
let mut table = RoleTable::of(d);
|
||||
if !linked || table.role_of_swatch(kept).is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = kept.to_string();
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
|
||||
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
|
||||
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
|
||||
/// always ends at a free one.
|
||||
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
|
||||
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
|
||||
let base = role.name();
|
||||
if free(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
|
||||
/// guide, or a compound path.
|
||||
pub(super) fn can_carry(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
|
||||
/// are on a locked artboard are left out and counted as skipped.
|
||||
pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => {
|
||||
for c in children {
|
||||
// A group's clipping path draws no stroke: it is skipped.
|
||||
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
|
||||
*skipped += 1;
|
||||
} else {
|
||||
walk(c, out, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => *skipped += 1,
|
||||
}
|
||||
}
|
||||
let (mut out, mut skipped) = (vec![], 0);
|
||||
// A path of a compound path is painted with the compound's appearance: the compound takes the
|
||||
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
|
||||
// group and its member are never both roots.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
|
||||
walk(n, &mut out, &mut skipped);
|
||||
}
|
||||
if editable {
|
||||
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
|
||||
// layer or on a locked artboard, stays as it is.
|
||||
let ok = d.editable();
|
||||
let before = out.len();
|
||||
out.retain(|id| ok(*id));
|
||||
skipped += before - out.len();
|
||||
}
|
||||
(out, skipped)
|
||||
}
|
||||
|
||||
/// Every object of the document that can carry a role, through layers and groups.
|
||||
fn document_targets(d: &Document) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.packaging.setRole",
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
cmd!(
|
||||
query "addon.packaging.roles",
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
cmd!(
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"Role Swatches…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
|
||||
has_doc,
|
||||
set_role_swatch
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
|
||||
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
|
||||
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
|
||||
match Role::from_id(id) {
|
||||
Some(r) => Ok(Some(r)),
|
||||
None if none && id == "none" => Ok(None),
|
||||
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
|
||||
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why swatch `name` of `d` can't carry a role, if it can't.
|
||||
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
|
||||
if name == REGISTRATION || name == "[None]" {
|
||||
return Some(format!("`{name}` can't carry a role"));
|
||||
}
|
||||
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
|
||||
match &sw.paint {
|
||||
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
|
||||
Paint::Solid { .. } if sw.global => None,
|
||||
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
|
||||
_ => Some(format!("`{name}` isn't a color swatch")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
|
||||
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
|
||||
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
|
||||
/// free name, which the role table then gives the role.
|
||||
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
|
||||
let mut table = RoleTable::of(d);
|
||||
let current = table.swatch(role);
|
||||
let taken = match d.swatch(current) {
|
||||
Some(_) => unfit_swatch(d, current).is_some(),
|
||||
None => d.swatch_name_taken(current),
|
||||
};
|
||||
if taken {
|
||||
let free = free_role_name(d, &table, role);
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = free;
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
let name = table.swatch(role);
|
||||
if d.swatch(name).is_none() {
|
||||
let model = d.color_mode.model();
|
||||
let color = role.color();
|
||||
let color = if color.model() == model {
|
||||
color
|
||||
} else {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&color, model, cms.settings().intent)
|
||||
};
|
||||
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
|
||||
}
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
|
||||
}
|
||||
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
|
||||
}
|
||||
|
||||
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
|
||||
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
let had = table.role_of(n);
|
||||
let mut a = (*n.appearance).clone();
|
||||
match paint {
|
||||
Some(paint) => {
|
||||
a.set_stroke(paint.clone());
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
// A hidden stroke would carry the role without drawing or printing the line.
|
||||
st.visible = true;
|
||||
st.overprint = overprint;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if had.is_none() {
|
||||
return false;
|
||||
}
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if let Paint::Solid { color, .. } = st.paint {
|
||||
st.paint = Paint::solid(color);
|
||||
}
|
||||
st.overprint = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if a == *n.appearance {
|
||||
return false;
|
||||
}
|
||||
n.appearance = vectorcraft_doc::Shared::new(a);
|
||||
true
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
|
||||
let mut changed = 0;
|
||||
edit_counted(s, label, |d| {
|
||||
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
|
||||
let paint = role.map(|r| role_paint(d, r)).transpose()?;
|
||||
// A role swatch made again (its strokes may still name it) is a change of its own.
|
||||
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
|
||||
let table = RoleTable::of(d);
|
||||
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
|
||||
Ok(changed + usize::from(made))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
.zip(counts)
|
||||
.map(|(r, count)| {
|
||||
let swatch = table.swatch(r);
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
|
||||
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, why));
|
||||
}
|
||||
let mut table = RoleTable::of(d);
|
||||
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
|
||||
}
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = name.to_string();
|
||||
}
|
||||
let value = table.to_value();
|
||||
let changed = RoleTable::of(d) != table;
|
||||
if changed {
|
||||
s.edit("Role Swatches", |d, _| {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), value);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session(mode: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.setRole", &p).unwrap()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
|
||||
s.execute(cmd, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// The `roles` query's counts, in role order.
|
||||
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
|
||||
let r = s.execute("addon.packaging.roles", &p).unwrap();
|
||||
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sw = d.swatch("Cut").unwrap();
|
||||
assert!(sw.global && sw.spot, "{sw:?}");
|
||||
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
|
||||
assert!(st.overprint, "role strokes overprint by default");
|
||||
// Again: nothing changes, and no undo step is recorded.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// Undo takes the swatch away with the role.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
|
||||
let mut s = session("rgb");
|
||||
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
|
||||
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
|
||||
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
|
||||
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
|
||||
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("strip", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
n.appearance.items.retain(AppearanceItem::is_fill);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(node(&s, a).appearance.stroke().is_none());
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.width, 1.0, "a 1 pt stroke");
|
||||
assert!(!st.overprint);
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_takes_the_role_away_and_keeps_the_color() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.paint, Paint::solid(shown));
|
||||
assert!(!st.overprint);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
|
||||
// Nothing left with a role: no undo step.
|
||||
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_roles_and_targets_are_refused() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
|
||||
// Text beside a path is skipped and counted.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
d.node_mut(c).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
|
||||
// Named directly, a locked or hidden path is left out too.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
|
||||
let mut s = session("cmyk");
|
||||
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A locked line keeps its role and is counted, whether its group is selected or not.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
|
||||
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
|
||||
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
|
||||
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
|
||||
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
|
||||
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
|
||||
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
|
||||
// The next Make Cut Line makes the Cut role's swatch again.
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_swatch_can_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_counts_the_selection_or_the_whole_document() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
|
||||
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
|
||||
let rows = r["roles"].as_array().unwrap();
|
||||
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
|
||||
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_maps_a_role_to_another_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
// The old swatch's objects keep their color and lose the role.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
// The same mapping again changes nothing.
|
||||
let steps_now = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_role_swatch_keeps_its_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
// A swatch that carries no role leaves the table alone.
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
|
||||
// Undo puts the old name back in the table with the swatch.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
// No Crease swatch exists yet, so the name is free for the Cut swatch.
|
||||
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
|
||||
assert_eq!(steps(&s), before + 1, "as one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
|
||||
st.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(node(&s, a).appearance.stroke().unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
for (swatch, says) in [
|
||||
("Nope", "no swatch"),
|
||||
("Ramp", "isn't a color swatch"),
|
||||
("Plain", "process color"),
|
||||
("Ink Tint", "tint swatch"),
|
||||
("[None]", "can't carry a role"),
|
||||
("[Registration]", "can't carry a role"),
|
||||
("Crease", "already carries the Crease role"),
|
||||
] {
|
||||
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
|
||||
assert!(e.contains(says), "{swatch}: {e}");
|
||||
}
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_role_table_reads_as_the_defaults() {
|
||||
let mut s = session("cmyk");
|
||||
s.edit("damage", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
|
||||
s.edit("not an object", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!("Cut"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
// One swatch named for two roles: the later role takes its own default.
|
||||
s.edit("duplicate", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
|
||||
let b = rect(&mut s, 100.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_open_keep_the_role_table_and_the_roles() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// A document with one rectangle of each of Cut and Crease.
|
||||
fn two_roles() -> Session {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, format: &str) -> String {
|
||||
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
|
||||
let mut s = two_roles();
|
||||
let c = rect(&mut s, 180.0);
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&s.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = String::from_utf8_lossy(&bytes);
|
||||
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
|
||||
assert!(pdf.contains("/Separation/Crease"));
|
||||
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
|
||||
assert!(pdf.contains("/OP true"), "the role strokes overprint");
|
||||
// Without overprint, nothing in the file overprints.
|
||||
let mut plain = session("cmyk");
|
||||
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
|
||||
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
|
||||
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&plain.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
|
||||
assert!(!export(&mut s, "pdf").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
|
||||
let mut s = two_roles();
|
||||
let svg = export(&mut s, "svg");
|
||||
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
|
||||
let strokes = if strokes.is_empty() {
|
||||
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
|
||||
} else {
|
||||
strokes
|
||||
};
|
||||
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
|
||||
let dxf = export(&mut s, "dxf");
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The rectangles' white fills come out as true colors too.
|
||||
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
|
||||
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
|
||||
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
|
||||
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
|
||||
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_paths_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
|
||||
assert_eq!(r["ids"], json!([c.0]));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
|
||||
// A member named by id gives its compound the role.
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
Loaded 100 of 882 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user