mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 17:37:10 +01:00
7234: resolve main conflicts preserving contribution
This commit is contained in:
commit
65351f9f6c
1428 files changed
+262293
-17178
No files matched your search
@@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
|
||||
|
||||
Generated
+364
-107
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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -146,3 +146,125 @@ Indic hyphenation patterns (crates/text/patterns/):
|
||||
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
jpeg-encoder 0.6.1, https://crates.io/crates/jpeg-encoder/0.6.1
|
||||
Licensed under (MIT OR Apache-2.0) AND IJG. The MIT option and the IJG and SIMD
|
||||
notices are reproduced below. Original license texts and provenance hashes are
|
||||
retained in licenses/jpeg-encoder-0.6.1/.
|
||||
|
||||
--- jpeg-encoder 0.6.1: LICENSE-MIT ---
|
||||
|
||||
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
|
||||
--- jpeg-encoder 0.6.1: IJG-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg to rust
|
||||
*
|
||||
* This file was part of the Independent JPEG Group's software:
|
||||
* Copyright (C) 1991-1996, Thomas G. Lane.
|
||||
* libjpeg-turbo Modifications:
|
||||
* Copyright (C) 2015, 2020, D. R. Commander.
|
||||
*
|
||||
* Conditions of distribution and use:
|
||||
* In plain English:
|
||||
*
|
||||
* 1. We don't promise that this software works. (But if you find any bugs,
|
||||
* please let us know!)
|
||||
* 2. You can use this software for whatever you want. You don't have to pay us.
|
||||
* 3. You may not pretend that you wrote this software. If you use it in a
|
||||
* program, you must acknowledge somewhere in your documentation that
|
||||
* you've used the IJG code.
|
||||
*
|
||||
* In legalese:
|
||||
*
|
||||
* The authors make NO WARRANTY or representation, either express or implied,
|
||||
* with respect to this software, its quality, accuracy, merchantability, or
|
||||
* fitness for a particular purpose. This software is provided "AS IS", and you,
|
||||
* its user, assume the entire risk as to its quality and accuracy.
|
||||
*
|
||||
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
|
||||
* All Rights Reserved except as specified below.
|
||||
*
|
||||
* Permission is hereby granted to use, copy, modify, and distribute this
|
||||
* software (or portions thereof) for any purpose, without fee, subject to these
|
||||
* conditions:
|
||||
* (1) If any part of the source code for this software is distributed, then this
|
||||
* README file must be included, with this copyright and no-warranty notice
|
||||
* unaltered; and any additions, deletions, or changes to the original files
|
||||
* must be clearly indicated in accompanying documentation.
|
||||
* (2) If only executable code is distributed, then the accompanying
|
||||
* documentation must state that "this software is based in part on the work of
|
||||
* the Independent JPEG Group".
|
||||
* (3) Permission for use of this software is granted only if the user accepts
|
||||
* full responsibility for any undesirable consequences; the authors accept
|
||||
* NO LIABILITY for damages of any kind.
|
||||
*
|
||||
* These conditions apply to any software derived from or based on the IJG code,
|
||||
* not just to the unmodified library. If you use our work, you ought to
|
||||
* acknowledge us.
|
||||
*
|
||||
* Permission is NOT granted for the use of any IJG author's name or company name
|
||||
* in advertising or publicity relating to this software or products derived from
|
||||
* it. This software may be referred to only as "the Independent JPEG Group's
|
||||
* software".
|
||||
*
|
||||
* We specifically permit and encourage the use of this software as the basis of
|
||||
* commercial products, provided that all warranty or liability claims are
|
||||
* assumed by the product vendor.
|
||||
*
|
||||
* This file contains a slower but more accurate integer implementation of the
|
||||
* forward DCT (Discrete Cosine Transform).
|
||||
*
|
||||
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
|
||||
* on each column. Direct algorithms are also available, but they are
|
||||
* much more complex and seem not to be any faster when reduced to code.
|
||||
*
|
||||
* This implementation is based on an algorithm described in
|
||||
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
|
||||
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
|
||||
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
|
||||
* The primary algorithm described there uses 11 multiplies and 29 adds.
|
||||
* We use their alternate method with 12 multiplies and 32 adds.
|
||||
* The advantage of this method is that no data path contains more than one
|
||||
* multiplication; this allows a very simple and accurate implementation in
|
||||
* scaled fixed-point arithmetic, with a minimal number of shifts.
|
||||
*/
|
||||
|
||||
--- jpeg-encoder 0.6.1: SIMD-NOTICE.txt ---
|
||||
|
||||
/*
|
||||
* Ported from mozjpeg / jfdctint-avx2.asm to rust
|
||||
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
|
||||
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
|
||||
*
|
||||
* Based on the x86 SIMD extension for IJG JPEG library
|
||||
* Copyright (C) 1999-2006, MIYASAKA Masaru.
|
||||
*/
|
||||
@@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified
|
||||
The scores are self-assessed from our code against public documentation;
|
||||
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
|
||||
|
||||
All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview.
|
||||
|
||||
**What's missing:**
|
||||
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
|
||||
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
|
||||
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
|
||||
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
|
||||
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
|
||||
- scripting, and the rest of Variables (image and graph kinds, dataset import);
|
||||
- generative AI features.
|
||||
|
||||
+21
-4
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -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
|
||||
@@ -125,14 +125,23 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
## Progress log
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). 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-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). 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-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers 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.
|
||||
@@ -140,9 +149,15 @@ 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-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). 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-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). 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.
|
||||
@@ -224,6 +239,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
|
||||
|
||||
@@ -238,10 +238,13 @@ 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 each script's `Folder.userData` in the Script Data folder there, 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_script_data(&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);
|
||||
|
||||
@@ -17,7 +17,7 @@ path = "src/main.rs"
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" }
|
||||
vectorcraft-format = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
|
||||
@@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) {
|
||||
pub(crate) async fn sleep(ms: i32) {
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most
|
||||
//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after
|
||||
//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures.
|
||||
|
||||
/// The wait after a face's first failed fetch before it is fetched again (ms).
|
||||
const RETRY_MS: i32 = 30_000;
|
||||
/// Failed fetches of a face after which it is not fetched again this session.
|
||||
pub(crate) const MAX_TRIES: u32 = 5;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum State {
|
||||
Idle,
|
||||
/// Being fetched, after `tries` failed fetches.
|
||||
Loading {
|
||||
tries: u32,
|
||||
},
|
||||
Loaded,
|
||||
/// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or
|
||||
/// at once when the clock reads earlier than `failed_at`.
|
||||
Failed {
|
||||
tries: u32,
|
||||
failed_at: f64,
|
||||
retry_at: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// The fetch state of each face of a web font list, by index.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Demand {
|
||||
states: Vec<State>,
|
||||
}
|
||||
|
||||
impl Demand {
|
||||
/// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not
|
||||
/// loaded, not being fetched, and not waiting to be fetched again. They are marked as being
|
||||
/// fetched.
|
||||
pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec<usize> {
|
||||
let mut out = Vec::new();
|
||||
for &i in wanted {
|
||||
if self.states.len() <= i {
|
||||
self.states.resize(i + 1, State::Idle);
|
||||
}
|
||||
let Some(state) = self.states.get_mut(i) else { continue };
|
||||
let tries = match *state {
|
||||
State::Idle => Some(0),
|
||||
State::Loading { .. } | State::Loaded => None,
|
||||
State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries),
|
||||
};
|
||||
if let Some(tries) = tries {
|
||||
*state = State::Loading { tries };
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`.
|
||||
/// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it
|
||||
/// loaded or has failed [`MAX_TRIES`] times.
|
||||
pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option<i32> {
|
||||
let state = self.states.get_mut(i)?;
|
||||
let State::Loading { tries } = *state else { return None };
|
||||
if ok {
|
||||
*state = State::Loaded;
|
||||
return None;
|
||||
}
|
||||
let tries = tries + 1;
|
||||
let wait = RETRY_MS << (tries - 1).min(4);
|
||||
*state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) };
|
||||
(tries < MAX_TRIES).then_some(wait)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_face_is_fetched_once_and_kept() {
|
||||
let mut d = Demand::default();
|
||||
assert_eq!(d.start(&[2], 0.0), [2]);
|
||||
assert!(d.start(&[2], 1.0).is_empty(), "already being fetched");
|
||||
assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry");
|
||||
assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again");
|
||||
assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own");
|
||||
assert_eq!(d.finished(7, false, 4.0), None, "a face never started");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_face_waits_longer_after_each_failure_and_then_stops() {
|
||||
let mut d = Demand::default();
|
||||
let mut now = 0.0;
|
||||
// The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first.
|
||||
for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) {
|
||||
assert_eq!(d.start(&[0], now), [0], "at {now}");
|
||||
assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}");
|
||||
assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}");
|
||||
now += f64::from(wait);
|
||||
}
|
||||
// The fifth fetch, and after it fails, none.
|
||||
assert_eq!(d.start(&[0], now), [0]);
|
||||
assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures");
|
||||
assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures");
|
||||
// A later success after failures keeps the face.
|
||||
let mut d = Demand::default();
|
||||
d.start(&[1], 0.0);
|
||||
assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS));
|
||||
assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]);
|
||||
assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None);
|
||||
assert!(d.start(&[1], 1e12).is_empty());
|
||||
}
|
||||
|
||||
/// While a face is fetched again after a failure, neither the interface asking for its script
|
||||
/// again nor the retry timer starts a second fetch of it.
|
||||
#[test]
|
||||
fn a_face_being_fetched_again_is_not_fetched_twice_at_once() {
|
||||
let mut d = Demand::default();
|
||||
d.start(&[0], 0.0);
|
||||
assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS));
|
||||
let retry = f64::from(RETRY_MS);
|
||||
assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice");
|
||||
assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again");
|
||||
assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer");
|
||||
assert_eq!(d.finished(0, true, retry + 2_000.0), None);
|
||||
assert!(d.start(&[0], 1e12).is_empty(), "loaded");
|
||||
}
|
||||
|
||||
/// A clock that reads earlier than the failure (one set back meanwhile) does not hold the
|
||||
/// retry back: the timer that asks for it has waited already.
|
||||
#[test]
|
||||
fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() {
|
||||
let mut d = Demand::default();
|
||||
let failed_at = 1e12;
|
||||
d.start(&[0], failed_at);
|
||||
assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS));
|
||||
assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting");
|
||||
assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour");
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
//! Craft-fonts faces served beside the wasm (`fonts/<sha16>/…`, copied by
|
||||
//! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup`
|
||||
//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks
|
||||
//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped:
|
||||
//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing.
|
||||
//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and
|
||||
//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the
|
||||
//! interface's own text needs its script. The browser checks each file against its SHA-256
|
||||
//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With
|
||||
//! `WEB_FONTS` empty (built without craft-fonts) these do nothing.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_text::craft_fonts::demand_fonts;
|
||||
use vectorcraft_text::{FontDb, WEB_FONTS, WebFont};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use crate::demand::Demand;
|
||||
|
||||
/// Per startup face: the page shows its loading text meanwhile.
|
||||
const STARTUP_TIMEOUT_MS: i32 = 20_000;
|
||||
/// Per background face.
|
||||
@@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4;
|
||||
thread_local! {
|
||||
/// The background fetch runs once per page, though a graphics restart creates the app again.
|
||||
static BACKGROUND_STARTED: Cell<bool> = const { Cell::new(false) };
|
||||
/// The `demand` faces' fetches.
|
||||
static DEMAND: RefCell<Demand> = RefCell::new(Demand::default());
|
||||
/// The running app's context, asked for a frame when a `demand` face arrives (none before the
|
||||
/// app starts: its first frame looks through the faces loaded by then).
|
||||
static REPAINT: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or
|
||||
/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those
|
||||
/// characters with it from then on. Set as the interface's missing-glyph handler
|
||||
/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name
|
||||
/// before the app starts.
|
||||
pub fn want_chars(chars: &[char]) {
|
||||
let wanted = demand_fonts(WEB_FONTS, chars.iter().copied());
|
||||
if !wanted.is_empty() {
|
||||
fetch_demand(&wanted);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start.
|
||||
/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives.
|
||||
fn fetch_demand(wanted: &[usize]) {
|
||||
for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) {
|
||||
let Some(f) = WEB_FONTS.get(i) else { continue };
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let ok = load(f, BACKGROUND_TIMEOUT_MS).await;
|
||||
let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms()));
|
||||
if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if let Some(wait) = retry {
|
||||
// A second longer, so a clock the browser coarsens still reads the wait as over.
|
||||
crate::api::sleep(wait.saturating_add(1_000)).await;
|
||||
fetch_demand(&[i]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch and register the `startup` faces (one after the other). Returns how many loaded.
|
||||
pub async fn load_startup_fonts() -> usize {
|
||||
let mut loaded = 0;
|
||||
for f in WEB_FONTS.iter().filter(|f| f.startup) {
|
||||
for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) {
|
||||
if load(f, STARTUP_TIMEOUT_MS).await {
|
||||
loaded += 1;
|
||||
}
|
||||
@@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize {
|
||||
}
|
||||
|
||||
/// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for
|
||||
/// a frame after each so the font menus and the canvas pick it up. Only the first call does
|
||||
/// anything.
|
||||
/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches
|
||||
/// anything; each call makes `ctx` the context a `demand` face asks for a frame.
|
||||
pub fn spawn_background_fonts(ctx: egui::Context) {
|
||||
REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone()));
|
||||
if BACKGROUND_STARTED.with(|s| s.replace(true)) {
|
||||
return;
|
||||
}
|
||||
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect());
|
||||
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect());
|
||||
let next = Rc::new(Cell::new(0usize));
|
||||
for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) {
|
||||
let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone());
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod demand;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -81,6 +81,11 @@ pub fn start() {
|
||||
return;
|
||||
};
|
||||
detect_language();
|
||||
// The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the
|
||||
// startup fonts, without holding up the start. Text in those scripts painted later (a saved
|
||||
// interface language, another one chosen, a layer or file name) has its face fetched then.
|
||||
vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars);
|
||||
crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::<Vec<_>>());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
// Before the first frame, which looks for copies a crash left behind.
|
||||
let locks = WebLocks::start(RECOVERY_PREFIX).await;
|
||||
|
||||
@@ -40,6 +40,9 @@ craft-print = { workspace = true }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
clipboard-win = { workspace = true }
|
||||
# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs).
|
||||
# MIT, already in the build through the update client.
|
||||
winreg = "0.55"
|
||||
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
|
||||
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
|
||||
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
|
||||
|
||||
@@ -43,6 +43,16 @@ impl eframe::App for App {
|
||||
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
|
||||
/// app's raw-input hook while the keyboard user is unconfined.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// Without vsync, a main-window frame starts no sooner than the minimum interval after the
|
||||
// last one. eframe runs this hook once per frame, shown or not, before egui reads the input.
|
||||
// The frame's time moves on by the wait, and the hang report's frame time starts after it.
|
||||
if raw.viewport_id == egui::ViewportId::ROOT {
|
||||
if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) {
|
||||
std::thread::sleep(wait);
|
||||
raw.time = raw.time.map(|time| time + wait.as_secs_f64());
|
||||
}
|
||||
self.last_frame_began = Some(std::time::Instant::now());
|
||||
}
|
||||
let _timed = BEACON.enter_timed(Stage::Input);
|
||||
self.frame_start = Some(std::time::Instant::now());
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
|
||||
//!
|
||||
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
|
||||
//! and at once when the window moves to another display.
|
||||
//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -31,6 +31,8 @@ pub(crate) struct Reader {
|
||||
looked: Option<f64>,
|
||||
/// A reading is running.
|
||||
busy: Arc<AtomicBool>,
|
||||
/// [`DisplayProfile::attach_reader`] was called.
|
||||
attached: bool,
|
||||
}
|
||||
|
||||
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
|
||||
@@ -45,22 +47,22 @@ impl Drop for Done {
|
||||
impl Reader {
|
||||
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
|
||||
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
|
||||
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
|
||||
return;
|
||||
if !self.attached {
|
||||
profile.attach_reader();
|
||||
self.attached = true;
|
||||
}
|
||||
self.looked = Some(now);
|
||||
let display = window.current_monitor().and_then(|m| m.name());
|
||||
if !due(self.last.as_ref(), now, display.as_deref()) {
|
||||
let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else {
|
||||
return;
|
||||
}
|
||||
self.last = Some((now, display.clone()));
|
||||
};
|
||||
profile.pending();
|
||||
self.busy.store(true, Ordering::Release);
|
||||
let done = Done(self.busy.clone());
|
||||
let (profile, ctx) = (profile.clone(), ctx.clone());
|
||||
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
|
||||
let _done = done;
|
||||
if profile.report(read(display)) {
|
||||
let changed = profile.report(read(display));
|
||||
drop(done);
|
||||
// A request made while this reading ran starts on the next frame.
|
||||
if changed || profile.read_requested() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
@@ -68,6 +70,32 @@ impl Reader {
|
||||
log::warn!("couldn't start reading the display profile: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The display to read at `now` when a reading is to start, looked up with `display`. A
|
||||
/// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once,
|
||||
/// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the
|
||||
/// preference off drops it. A request made with the preference on is kept when the preference
|
||||
/// goes off and on again between two frames.
|
||||
fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option<String>) -> Option<Option<String>> {
|
||||
if !enabled {
|
||||
profile.take_request();
|
||||
return None;
|
||||
}
|
||||
if self.busy.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
let asked = profile.take_request();
|
||||
if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
|
||||
return None;
|
||||
}
|
||||
self.looked = Some(now);
|
||||
let display = display();
|
||||
if !asked && !due(self.last.as_ref(), now, display.as_deref()) {
|
||||
return None;
|
||||
}
|
||||
self.last = Some((now, display.clone()));
|
||||
Some(display)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
|
||||
@@ -570,6 +598,56 @@ mod tests {
|
||||
assert!(due(Some(&last), 50.0, Some("DP-1")));
|
||||
}
|
||||
|
||||
fn attached() -> DisplayProfile {
|
||||
let profile = DisplayProfile::default();
|
||||
profile.attach_reader();
|
||||
profile
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
// Inside the display lookup interval and the reading interval: nothing starts.
|
||||
assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None);
|
||||
assert_eq!(r.start(102.0, true, &profile, dp1), None);
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
assert!(!profile.read_requested(), "the request is taken");
|
||||
// The intervals run again from the requested reading.
|
||||
assert_eq!(r.start(102.2, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(111.0, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_made_while_a_reading_runs_waits_for_it_to_end() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert!(r.start(0.0, true, &profile, dp1).is_some());
|
||||
r.busy.store(true, Ordering::Release);
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(0.1, true, &profile, dp1), None);
|
||||
assert_eq!(r.start(5.0, true, &profile, dp1), None);
|
||||
assert!(profile.read_requested(), "kept while the reading runs");
|
||||
r.busy.store(false, Ordering::Release);
|
||||
assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into())));
|
||||
assert!(!profile.read_requested());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_is_dropped_when_the_preference_goes_off() {
|
||||
let (mut r, profile) = (Reader::default(), attached());
|
||||
let dp1 = || Some("DP-1".to_string());
|
||||
assert!(r.start(0.0, true, &profile, dp1).is_some());
|
||||
profile.request_read(true).unwrap();
|
||||
assert_eq!(r.start(0.1, false, &profile, dp1), None);
|
||||
assert!(!profile.read_requested());
|
||||
assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it");
|
||||
assert!(profile.request_read(false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
|
||||
let env = |pairs: &'static [(&'static str, &'static str)]| {
|
||||
|
||||
@@ -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};
|
||||
@@ -71,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(
|
||||
@@ -81,8 +83,9 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
PickRequest::FolderAt(folder) => return d.folder(folder),
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
@@ -93,7 +96,55 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
Some(folder) => d.folder(folder),
|
||||
None => d,
|
||||
};
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
if pick.name.is_empty() {
|
||||
return d;
|
||||
}
|
||||
// Windows' save dialog changes the extension when a different file type is chosen only when
|
||||
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
|
||||
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
|
||||
// A remaining dot in the stem would look like another explicit extension to Windows.
|
||||
#[cfg(windows)]
|
||||
if matches!(request, PickRequest::Save(_))
|
||||
&& pick.filters.len() > 1
|
||||
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
|
||||
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
|
||||
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
|
||||
&& !stem.contains('.')
|
||||
{
|
||||
return d.file_name(stem);
|
||||
}
|
||||
d.file_name(&pick.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_folder_picker_asked_for_a_folder_starts_there() {
|
||||
/// The settings a dialog was given, by name.
|
||||
#[derive(Default)]
|
||||
struct Recorded(Vec<String>);
|
||||
impl DialogSettings for Recorded {
|
||||
fn parent(self, _: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(mut self, title: &str) -> Self {
|
||||
self.0.push(format!("title {title}"));
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, _: &[impl ToString]) -> Self {
|
||||
self.0.push(format!("filter {name}"));
|
||||
self
|
||||
}
|
||||
fn folder(mut self, folder: &str) -> Self {
|
||||
self.0.push(format!("folder {folder}"));
|
||||
self
|
||||
}
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.0.push(format!("name {name}"));
|
||||
self
|
||||
}
|
||||
}
|
||||
assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]);
|
||||
assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty());
|
||||
}
|
||||
|
||||
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
|
||||
@@ -128,9 +179,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
|
||||
}
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
@@ -313,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
let picked = dialog.pick_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
PickRequest::OpenMany => {
|
||||
PickRequest::OpenMany | PickRequest::OpenFiles(_) => {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
|
||||
}
|
||||
@@ -332,7 +383,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
// on that nil; treat the pick as cancelled instead (#5980).
|
||||
Err(()) => Box::pin(async move { Vec::new() }),
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
PickRequest::Folder | PickRequest::FolderAt(_) => {
|
||||
let picked = dialog.pick_folder();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
@@ -353,14 +404,15 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.and_then(|w| w.window_handle().ok())
|
||||
.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"))]
|
||||
let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
|
||||
// dialogs run the window's events while they are open.
|
||||
@@ -408,11 +460,14 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
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()
|
||||
@@ -758,7 +813,7 @@ mod dialog_tests {
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
@@ -774,7 +829,8 @@ mod dialog_tests {
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.1 = Some(name.to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -831,4 +887,24 @@ mod dialog_tests {
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
|
||||
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
|
||||
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
|
||||
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
|
||||
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
|
||||
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
|
||||
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -136,6 +142,11 @@ struct App {
|
||||
display_profile: display_profile::Reader,
|
||||
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
|
||||
frame_start: Option<std::time::Instant>,
|
||||
/// The shortest time between the starts of two frames, while the window presents without vsync
|
||||
/// ([`presentation::min_frame_interval`]).
|
||||
min_frame: Option<std::time::Duration>,
|
||||
/// When the last frame started, after its wait for [`Self::min_frame`].
|
||||
last_frame_began: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
|
||||
@@ -158,6 +169,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 +196,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 +218,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 +261,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 +287,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 +310,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),
|
||||
}
|
||||
@@ -334,6 +370,10 @@ fn main() -> std::process::ExitCode {
|
||||
let saved_window = saved.as_ref().and_then(|ui| ui.window);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str);
|
||||
// Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off.
|
||||
#[cfg(feature = "wgpu")]
|
||||
let low_latency_drawing =
|
||||
saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let power_env = eframe::wgpu::PowerPreference::from_env();
|
||||
#[cfg(feature = "wgpu")]
|
||||
@@ -427,7 +467,11 @@ 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, and Low-Latency Drawing
|
||||
// asks for no vsync when neither sets the mode (`presentation`).
|
||||
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing);
|
||||
// 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, low_latency_drawing));
|
||||
// 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 +502,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")]
|
||||
@@ -470,6 +518,11 @@ fn main() -> std::process::ExitCode {
|
||||
// For the hang report (`hang_watch`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
let requested_surface = options.wgpu_options.surface;
|
||||
// Without vsync, frames start at most 240 times a second (`presentation`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
let min_frame = presentation::min_frame_interval(&requested_surface);
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let min_frame = None;
|
||||
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
|
||||
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -498,7 +551,10 @@ 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);
|
||||
prefs_dir::attach_script_data(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
@@ -551,14 +607,15 @@ fn main() -> std::process::ExitCode {
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
let hint = if chosen_gpu {
|
||||
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
));
|
||||
} else {
|
||||
""
|
||||
};
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
|
||||
));
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
|
||||
));
|
||||
}
|
||||
} else if let Some(crash) = &crash {
|
||||
app.status(match crash {
|
||||
gpu::Crash::Adapter { name, .. } => format!(
|
||||
@@ -653,6 +710,8 @@ fn main() -> std::process::ExitCode {
|
||||
monitors_listed: None,
|
||||
display_profile: Default::default(),
|
||||
frame_start: None,
|
||||
min_frame,
|
||||
last_frame_began: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -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) {
|
||||
@@ -73,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people
|
||||
/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first
|
||||
/// needs them.
|
||||
pub fn attach_script_data(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Script Data") {
|
||||
session.attach_script_data(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
//! `--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`.
|
||||
//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at
|
||||
//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the
|
||||
//! surface presents without vsync, frames start at most 240 times a second. The surface the app
|
||||
//! asks for is logged at start-up, with where its present mode came from.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The most frames a second the window draws while it presents without vsync.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub const UNSYNCED_FRAME_CAP: u32 = 240;
|
||||
|
||||
/// A present mode the command line or the environment can ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Fifo,
|
||||
AutoVsync,
|
||||
NoVsync,
|
||||
}
|
||||
|
||||
/// The present mode and frame latency this launch asked for (`None`: the app's own setting).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Overrides {
|
||||
pub mode: Option<Mode>,
|
||||
pub latency: Option<u32>,
|
||||
}
|
||||
|
||||
/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case.
|
||||
fn mode(name: &str, value: Option<&str>) -> Result<Mode, String> {
|
||||
let need = format!("{name} needs fifo, autovsync or novsync");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
match v.trim().to_ascii_lowercase().as_str() {
|
||||
"fifo" => Ok(Mode::Fifo),
|
||||
"autovsync" => Ok(Mode::AutoVsync),
|
||||
"novsync" => Ok(Mode::NoVsync),
|
||||
_ => Err(format!("{need}, not `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame latency named by `name`: 1, 2 or 3.
|
||||
fn latency(name: &str, value: Option<&str>) -> Result<u32, String> {
|
||||
let need = format!("{name} needs 1, 2 or 3 frames");
|
||||
let Some(v) = value else { return Err(need) };
|
||||
v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`"))
|
||||
}
|
||||
|
||||
/// The value of `--flag <value>` or `--flag=<value>` when `arg` is that flag; `None` when it isn't.
|
||||
fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) -> Option<Option<String>> {
|
||||
match arg.strip_prefix(flag)? {
|
||||
"" => Some(args.next()),
|
||||
rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
/// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is
|
||||
/// its value whatever it is, as with `--control`.
|
||||
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
|
||||
if let Some(value) = flag_value("--present-mode", arg, args) {
|
||||
if self.mode.is_some() {
|
||||
return Err("--present-mode given twice".into());
|
||||
}
|
||||
self.mode = Some(mode("--present-mode", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
if let Some(value) = flag_value("--frame-latency", arg, args) {
|
||||
if self.latency.is_some() {
|
||||
return Err("--frame-latency given twice".into());
|
||||
}
|
||||
self.latency = Some(latency("--frame-latency", value.as_deref())?);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`.
|
||||
/// Unset or empty is no override; a variable is not read when its flag was given.
|
||||
pub fn with_env(self, mode_var: Option<OsString>, latency_var: Option<OsString>) -> Result<Self, String> {
|
||||
let set = |v: Option<OsString>| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned());
|
||||
let mode = match (self.mode, set(mode_var)) {
|
||||
(Some(m), _) => Some(m),
|
||||
(None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
let latency = match (self.latency, set(latency_var)) {
|
||||
(Some(n), _) => Some(n),
|
||||
(None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?),
|
||||
(None, None) => None,
|
||||
};
|
||||
Ok(Self { mode, latency })
|
||||
}
|
||||
|
||||
/// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and
|
||||
/// no present mode override, the mode is `novsync`.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> 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 if low_latency_drawing => 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 shortest time between the starts of two frames on `surface`: `None` with vsync, where the
|
||||
/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option<Duration> {
|
||||
use eframe::wgpu::PresentMode;
|
||||
match surface.present_mode {
|
||||
PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP),
|
||||
PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a frame waits before it starts, `since_last` after the previous frame started, so that
|
||||
/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed).
|
||||
pub fn frame_wait(min: Option<Duration>, since_last: Option<Duration>) -> Option<Duration> {
|
||||
min?.checked_sub(since_last?).filter(|wait| !wait.is_zero())
|
||||
}
|
||||
|
||||
/// 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, and
|
||||
/// "(preference)" after a present mode Low-Latency Drawing set.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> 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 { "" };
|
||||
let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) };
|
||||
format!("{mode}{mode_tag}, frame latency {latency}{}", 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, false), app);
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app, false);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)");
|
||||
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
|
||||
let s = fifo.apply(app, false);
|
||||
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, false);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
|
||||
assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)");
|
||||
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
|
||||
assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default");
|
||||
}
|
||||
|
||||
/// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an
|
||||
/// explicit Immediate or Mailbox; off, the app's surface is exactly its own.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let none = Overrides::default();
|
||||
assert_eq!(none.apply(app, false), app);
|
||||
let s = none.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::AutoNoVsync);
|
||||
assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency);
|
||||
let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
|
||||
assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}"));
|
||||
// A latency override still applies with the preference's mode.
|
||||
let latency = Overrides { mode: None, latency: Some(2) };
|
||||
let s = latency.apply(app, true);
|
||||
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2)));
|
||||
assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)");
|
||||
}
|
||||
|
||||
/// The flag and the variable each set the present mode over Low-Latency Drawing.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_flag_and_the_variable_win_over_low_latency_drawing() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let flag = parse(&["--present-mode", "fifo"]).unwrap();
|
||||
let s = flag.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::Fifo);
|
||||
assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true));
|
||||
let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap();
|
||||
let s = var.apply(app, true);
|
||||
assert_eq!(s.present_mode, PresentMode::AutoVsync);
|
||||
assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true));
|
||||
// The flag wins over the variable, and both over the preference.
|
||||
let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap();
|
||||
assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo);
|
||||
}
|
||||
|
||||
/// Frames start at most 240 times a second without vsync, from the preference or an override,
|
||||
/// and the display paces them with vsync.
|
||||
#[cfg(feature = "wgpu")]
|
||||
#[test]
|
||||
fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() {
|
||||
use eframe::egui_wgpu::SurfaceConfig;
|
||||
use eframe::wgpu::PresentMode;
|
||||
let app = SurfaceConfig::LOW_LATENCY;
|
||||
let cap = Duration::from_secs(1) / 240;
|
||||
assert_eq!(cap.as_nanos(), 4_166_666);
|
||||
assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap));
|
||||
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap));
|
||||
assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None);
|
||||
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None);
|
||||
for (mode, capped) in [
|
||||
(PresentMode::Immediate, true),
|
||||
(PresentMode::Mailbox, true),
|
||||
(PresentMode::AutoNoVsync, true),
|
||||
(PresentMode::Fifo, false),
|
||||
(PresentMode::FifoRelaxed, false),
|
||||
(PresentMode::AutoVsync, false),
|
||||
] {
|
||||
let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) };
|
||||
assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_waits_out_the_rest_of_the_minimum_interval() {
|
||||
let min = Some(Duration::from_millis(4));
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3)));
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None);
|
||||
assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None);
|
||||
assert_eq!(frame_wait(min, None), None, "the first frame starts at once");
|
||||
assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync");
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,16 @@
|
||||
use std::process::Command;
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
|
||||
mod direct_pdf;
|
||||
|
||||
pub struct SystemPrint;
|
||||
impl PrintService for SystemPrint {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,16 +30,28 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect()
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
if job.direct_pdf {
|
||||
return super::direct_pdf::print(job);
|
||||
}
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +140,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port.
|
||||
//!
|
||||
//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page
|
||||
//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The
|
||||
//! PDF already carries the paper size, so the printer's interpreter prints it as laid out.
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::io::Write;
|
||||
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use vectorcraft_ui_egui::print::PrintJob;
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ};
|
||||
|
||||
/// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port.
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
let printer = job
|
||||
.printer
|
||||
.map(str::to_string)
|
||||
.or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name))
|
||||
.ok_or("direct PDF needs a selected printer")?;
|
||||
let (host, port) = tcp_port(&printer)?;
|
||||
send(&host, port, &pjl(job.title, job.pdf))?;
|
||||
Ok(format!(" (direct PDF to {host}:{port})"))
|
||||
}
|
||||
|
||||
/// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port.
|
||||
fn tcp_port(printer: &str) -> Result<(String, u16), String> {
|
||||
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
|
||||
let printer_key = hklm
|
||||
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ)
|
||||
.map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?;
|
||||
let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?;
|
||||
let port_key = hklm
|
||||
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ)
|
||||
.map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?;
|
||||
let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1);
|
||||
if protocol != 1 {
|
||||
return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port"));
|
||||
}
|
||||
let host = port_key
|
||||
.get_value::<String, _>("HostName")
|
||||
.ok()
|
||||
.filter(|h| !h.trim().is_empty())
|
||||
.or_else(|| port_key.get_value::<String, _>("IPAddress").ok().filter(|h| !h.trim().is_empty()))
|
||||
.ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?;
|
||||
let number = port_key.get_value::<u32, _>("PortNumber").unwrap_or(9100);
|
||||
let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?;
|
||||
Ok((host.trim().to_string(), port))
|
||||
}
|
||||
|
||||
/// Frame the PDF for the printer's PJL interpreter.
|
||||
fn pjl(title: &str, pdf: &[u8]) -> Vec<u8> {
|
||||
let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect();
|
||||
if name.is_empty() {
|
||||
name.push_str("VectorCraft");
|
||||
}
|
||||
let mut out = Vec::with_capacity(pdf.len() + 96);
|
||||
out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\"");
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n");
|
||||
out.extend_from_slice(pdf);
|
||||
out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Stream `data` to the first reachable address of `host:port`.
|
||||
fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> {
|
||||
let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?;
|
||||
let mut last = None;
|
||||
for addr in addrs {
|
||||
match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) {
|
||||
Ok(mut stream) => {
|
||||
stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?;
|
||||
stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?;
|
||||
stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
Err(match last {
|
||||
Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"),
|
||||
None => format!("direct PDF: {host}:{port} has no addresses"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
#[test]
|
||||
fn the_pjl_frames_the_pdf() {
|
||||
let out = pjl("witch hat\"", b"%PDF-1.7");
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"));
|
||||
assert!(text.contains("%PDF-1.7"));
|
||||
assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pdf_reaches_a_listening_port() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let t = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut got = Vec::new();
|
||||
stream.read_to_end(&mut got).unwrap();
|
||||
got
|
||||
});
|
||||
send("127.0.0.1", port, b"%PDF-1.7 test").unwrap();
|
||||
assert_eq!(t.join().unwrap(), b"%PDF-1.7 test");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use imp::print;
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result<String, String> {
|
||||
Err("direct PDF printing is only available on Windows".into())
|
||||
}
|
||||
@@ -78,7 +78,7 @@ impl Monitor {
|
||||
let scale = self.scale * zoom;
|
||||
let [x, y] = self.pos;
|
||||
let [w, h] = self.size;
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,13 +248,13 @@ mod tests {
|
||||
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
|
||||
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
|
||||
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None });
|
||||
// A window at (3000, 200) on this monitor reports (1500, 100).
|
||||
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None });
|
||||
// The UI zoom divides what egui reports as well.
|
||||
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="7.5"/><circle cx="4.5" cy="12" r="1.6" fill="currentColor"/><circle cx="19.5" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="4.5" r="1.6" fill="currentColor"/></svg>
|
||||
|
After Width: | Height: | Size: 386 B |
@@ -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]));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
|
||||
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
|
||||
|
||||
@@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option<BezPath> {
|
||||
Some(bp)
|
||||
}
|
||||
|
||||
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec<Node> {
|
||||
/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and
|
||||
/// barrel rotation turn that spread in the path's local frame. Original path corners are included
|
||||
/// in the samples so a turn is not rounded away by the pose sampling interval.
|
||||
fn posed_bristle_track(
|
||||
t: &Track,
|
||||
d: f64,
|
||||
trim0: f64,
|
||||
trim1: f64,
|
||||
size: f64,
|
||||
stroke: &StrokeLayer,
|
||||
varies: bool,
|
||||
) -> Option<(BezPath, Vec<(f64, f64)>)> {
|
||||
let l = t.len();
|
||||
let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l));
|
||||
if s1 - s0 < 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 };
|
||||
let mut positions: Vec<f64> = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect();
|
||||
positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1));
|
||||
positions.sort_by(f64::total_cmp);
|
||||
positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
|
||||
let mut path = BezPath::new();
|
||||
// Distance along the posed strand -> fraction along the original, untrimmed path.
|
||||
let mut source = Vec::with_capacity(positions.len());
|
||||
let mut previous: Option<Point> = None;
|
||||
let mut distance = 0.0;
|
||||
for (i, s) in positions.into_iter().enumerate() {
|
||||
let pen = PenAt::of(stroke, s / l);
|
||||
let pressure = pen.control(Variation::Pressure).unwrap_or(0.5);
|
||||
let tilt = pen.control(Variation::Tilt).unwrap_or(0.5);
|
||||
let bearing = pen.control(Variation::Bearing).unwrap_or(0.5);
|
||||
let rotation = pen.control(Variation::Rotation).unwrap_or(0.5);
|
||||
let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt);
|
||||
let angle = std::f64::consts::TAU * (bearing + rotation - 1.0);
|
||||
let p = t.map(s + spread * angle.sin(), spread * angle.cos());
|
||||
if i == 0 {
|
||||
path.move_to(p)
|
||||
} else {
|
||||
path.line_to(p)
|
||||
}
|
||||
if let Some(previous) = previous {
|
||||
distance += previous.distance(p);
|
||||
}
|
||||
source.push((distance, s / l));
|
||||
previous = Some(p);
|
||||
}
|
||||
Some((path, source))
|
||||
}
|
||||
|
||||
fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 {
|
||||
let next = source.partition_point(|(d, _)| *d < distance);
|
||||
if next == 0 {
|
||||
return source.first().map_or(0.0, |(_, f)| *f);
|
||||
}
|
||||
if next >= source.len() {
|
||||
return source.last().map_or(1.0, |(_, f)| *f);
|
||||
}
|
||||
let (d0, f0) = source[next - 1];
|
||||
let (d1, f1) = source[next];
|
||||
if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) }
|
||||
}
|
||||
|
||||
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let size = b.size.max(0.1) * weight;
|
||||
let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize;
|
||||
@@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
|
||||
let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0;
|
||||
let ragged = b.length.clamp(25.0, 300.0) / 100.0;
|
||||
let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32;
|
||||
let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some();
|
||||
let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6));
|
||||
let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points));
|
||||
let pose_varies = pressure_varies
|
||||
|| stroke.tilt.as_ref().is_some_and(|p| varies(&p.points))
|
||||
|| stroke.bearing.as_ref().is_some_and(|p| varies(&p.points))
|
||||
|| stroke.rotation.as_ref().is_some_and(|p| varies(&p.points));
|
||||
let mut out = vec![];
|
||||
for t in tracks(bp, tolerance(size)) {
|
||||
let l = t.len();
|
||||
@@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
|
||||
let edge = 1.0 - lane.abs();
|
||||
let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8;
|
||||
let (t0, t1) = (trim(&mut rng), trim(&mut rng));
|
||||
let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue };
|
||||
let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3));
|
||||
let sp = if posed {
|
||||
posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies)
|
||||
} else {
|
||||
offset_track(&t, off, t0, t1).map(|path| (path, Vec::new()))
|
||||
};
|
||||
let Some((sp, source)) = sp else { continue };
|
||||
let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2);
|
||||
let nib = Nib::new(0.0, 1.0, w);
|
||||
let subs: Vec<SubPath> = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect();
|
||||
let subs: Vec<SubPath> = tracks(&sp, tolerance(w))
|
||||
.iter()
|
||||
.flat_map(|tt| {
|
||||
if posed {
|
||||
sweep(
|
||||
tt,
|
||||
&|f| {
|
||||
let original_fraction = source_fraction(&source, f * tt.len());
|
||||
let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5);
|
||||
Nib::new(0.0, 1.0, w * (0.5 + pressure))
|
||||
},
|
||||
pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)),
|
||||
)
|
||||
} else {
|
||||
let nib = Nib::new(0.0, 1.0, w);
|
||||
sweep(tt, &|_| nib, None)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if subs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut n = filled(PathData::new(subs), paint);
|
||||
let mut n = filled(PathData::new(subs), &stroke.paint);
|
||||
n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0);
|
||||
out.push(n);
|
||||
}
|
||||
|
||||
@@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
walk(n, mode, key);
|
||||
}
|
||||
|
||||
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
|
||||
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
|
||||
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
|
||||
|
||||
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
|
||||
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
|
||||
for n in copies {
|
||||
let turn = rng.range(-amount, amount) as f32;
|
||||
turn_hues(n, turn);
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it
|
||||
/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as
|
||||
/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue:
|
||||
/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink).
|
||||
fn turned(c: &Color, degrees: f32) -> Option<Color> {
|
||||
if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
|
||||
return None;
|
||||
}
|
||||
let turn = |v: [f32; 3]| {
|
||||
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
|
||||
(s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b]))
|
||||
};
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
|
||||
Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
|
||||
Color::Gray { .. } => None,
|
||||
Color::Lab { l, a, b } => {
|
||||
let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
|
||||
let (a, b) = (f64::from(a), f64::from(b));
|
||||
Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_paint(p: &mut Paint, degrees: f32) {
|
||||
if let Paint::Solid { color, .. } = p
|
||||
&& let Some(c) = turned(color, degrees)
|
||||
{
|
||||
*p = Paint::solid(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
|
||||
/// mask's colors are its values, so they stay.
|
||||
fn turn_hues(n: &mut Node, degrees: f32) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
|
||||
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
turn_paint(&mut r.style.fill, degrees);
|
||||
turn_paint(&mut r.style.stroke, degrees);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
turn_hues(Arc::make_mut(c), degrees);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip the brushes from every stroke under `n`, its masks' art included.
|
||||
fn strip_brushes(n: &mut Node) {
|
||||
for it in &mut n.appearance.items {
|
||||
|
||||
@@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation: (-180.0, 180.0),
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::Tints,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
@@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation: (-35.0, 35.0),
|
||||
rotation_relative_to_path: true,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
|
||||
+267
-2
@@ -298,6 +298,12 @@ pub struct Scatter {
|
||||
/// Rotation relative to the path direction (else to the page).
|
||||
pub rotation_relative_to_path: bool,
|
||||
pub colorization: Colorization,
|
||||
/// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after
|
||||
/// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's
|
||||
/// path and the brush name fix the amounts, so a stroke draws the same colors every time.
|
||||
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub hue_jitter: f64,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
@@ -318,6 +324,7 @@ impl Default for Scatter {
|
||||
rotation: (0.0, 0.0),
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
modes: None,
|
||||
}
|
||||
}
|
||||
@@ -326,6 +333,8 @@ impl Default for Scatter {
|
||||
impl Scatter {
|
||||
/// The ranges of size (%), spacing (%), scatter (%) and rotation (°).
|
||||
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
|
||||
/// The range of [`Scatter::hue_jitter`] (°).
|
||||
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
|
||||
|
||||
/// Size, spacing, scatter and rotation, each as its (first, second) values.
|
||||
pub fn values(&self) -> [(f64, f64); 4] {
|
||||
@@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6
|
||||
(within(a, range, fallback), within(b, range, fallback))
|
||||
}
|
||||
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
fn valid_tile_frame(frame: Rect) -> bool {
|
||||
[frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite)
|
||||
&& frame.width().is_finite()
|
||||
@@ -714,6 +727,7 @@ impl Brush {
|
||||
s.spacing = within_pair(s.spacing, spacing, d.spacing.0);
|
||||
s.scatter = within_pair(s.scatter, scatter, 0.0);
|
||||
s.rotation = within_pair(s.rotation, rotation, 0.0);
|
||||
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
|
||||
s.colorization.sanitize();
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
@@ -753,6 +767,229 @@ impl Brush {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- stroke options ----------
|
||||
|
||||
/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]).
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ScatterOptions {
|
||||
size: (f64, f64),
|
||||
spacing: (f64, f64),
|
||||
scatter: (f64, f64),
|
||||
rotation: (f64, f64),
|
||||
modes: Option<[Variation; 4]>,
|
||||
rotation_relative_to_path: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
/// The Art brush fields a stroke can set for itself.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ArtOptions {
|
||||
width: f64,
|
||||
width_mode: Option<Variation>,
|
||||
width_max: Option<f64>,
|
||||
flip_along: bool,
|
||||
flip_across: bool,
|
||||
overlap: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
/// The Pattern brush fields a stroke can set for itself.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PatternOptions {
|
||||
scale: f64,
|
||||
spacing: f64,
|
||||
fit: PatternFit,
|
||||
flip_along: bool,
|
||||
flip_across: bool,
|
||||
colorization: Colorization,
|
||||
}
|
||||
|
||||
impl BrushKind {
|
||||
/// The definition fields, by their `brush.options` names, that one stroke can set for itself
|
||||
/// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle
|
||||
/// brush has none.
|
||||
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
|
||||
match self {
|
||||
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
|
||||
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
|
||||
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Bristle(_) => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the
|
||||
/// values are a `null` `modes`, so a stroke that sets them so keeps that setting.
|
||||
fn option_values(&self) -> serde_json::Value {
|
||||
let v = match self {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| {
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.entry("modes").or_insert(serde_json::Value::Null);
|
||||
}
|
||||
v
|
||||
}),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions {
|
||||
size: s.size,
|
||||
spacing: s.spacing,
|
||||
scatter: s.scatter,
|
||||
rotation: s.rotation,
|
||||
modes: s.modes,
|
||||
rotation_relative_to_path: s.rotation_relative_to_path,
|
||||
colorization: s.colorization,
|
||||
}),
|
||||
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
|
||||
width: a.width,
|
||||
width_mode: a.width_mode,
|
||||
width_max: a.width_max,
|
||||
flip_along: a.flip_along,
|
||||
flip_across: a.flip_across,
|
||||
overlap: a.overlap,
|
||||
colorization: a.colorization,
|
||||
}),
|
||||
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
|
||||
scale: p.scale,
|
||||
spacing: p.spacing,
|
||||
fit: p.fit,
|
||||
flip_along: p.flip_along,
|
||||
flip_across: p.flip_across,
|
||||
colorization: p.colorization,
|
||||
}),
|
||||
BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())),
|
||||
};
|
||||
v.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives
|
||||
/// them). An error when a value is of the wrong kind.
|
||||
fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> {
|
||||
match self {
|
||||
BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?,
|
||||
BrushKind::Scatter(s) => {
|
||||
let o: ScatterOptions = serde_json::from_value(v)?;
|
||||
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
|
||||
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
let o: ArtOptions = serde_json::from_value(v)?;
|
||||
(a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across);
|
||||
(a.overlap, a.colorization) = (o.overlap, o.colorization);
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
let o: PatternOptions = serde_json::from_value(v)?;
|
||||
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
|
||||
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
}
|
||||
BrushKind::Bristle(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Stroke option value `new` with each `null` item of an array taken from the same place in
|
||||
/// `current`, an array of the same length: a stroke option that changes some items of a range or a
|
||||
/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as
|
||||
/// it is.
|
||||
pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value {
|
||||
match (new, current) {
|
||||
(serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => {
|
||||
serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect())
|
||||
}
|
||||
_ => new.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Brush {
|
||||
/// The brush as a stroke whose own settings are `options` draws it: each field of
|
||||
/// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization`
|
||||
/// object changes only the fields it gives), and the values are kept within their ranges
|
||||
/// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there
|
||||
/// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of
|
||||
/// the wrong kind.
|
||||
pub fn with_stroke_options(&self, options: &serde_json::Map<String, serde_json::Value>) -> Result<Brush, String> {
|
||||
let keys = self.kind.stroke_option_keys();
|
||||
let mut values = self.kind.option_values();
|
||||
let Some(o) = values.as_object_mut() else { return Ok(self.clone()) };
|
||||
for (k, v) in options {
|
||||
if !keys.contains(&k.as_str()) {
|
||||
continue;
|
||||
}
|
||||
match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) {
|
||||
(Some(inner), Some(fields)) if k == "colorization" => {
|
||||
for (f, fv) in fields {
|
||||
inner.insert(f.clone(), fv.clone());
|
||||
}
|
||||
}
|
||||
// Set below, once the values the modes may follow are in.
|
||||
_ if k == "modes" => {}
|
||||
_ => {
|
||||
let current = o.get(k).cloned().unwrap_or_default();
|
||||
o.insert(k.clone(), keep_items(v, ¤t));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it.
|
||||
if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut)
|
||||
&& c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift")
|
||||
&& c.get("key").is_none_or(serde_json::Value::is_null)
|
||||
{
|
||||
let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK);
|
||||
c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?);
|
||||
}
|
||||
let mut b = self.clone();
|
||||
b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?;
|
||||
if let Some(m) = options.get("modes")
|
||||
&& keys.contains(&"modes")
|
||||
{
|
||||
// A null item keeps the mode the brush with the other settings has: modes it leaves to
|
||||
// its values follow the stroke's values, as they are kept within their ranges. Modes
|
||||
// equal to those are left as the brush has them, so they keep following the values.
|
||||
b.sanitize();
|
||||
let current = match &b.kind {
|
||||
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(),
|
||||
BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(),
|
||||
_ => serde_json::Value::Null,
|
||||
};
|
||||
let modes = keep_items(m, ¤t);
|
||||
if modes != current {
|
||||
if let Some(o) = values.as_object_mut() {
|
||||
o.insert("modes".into(), modes);
|
||||
}
|
||||
b = self.clone();
|
||||
b.kind.set_option_values(values).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
b.sanitize();
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
/// The stroke options of `options` that make the brush draw differently: each field of
|
||||
/// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs
|
||||
/// from the brush's own, with that value (kept within its range). An error for a field the
|
||||
/// type does not take and for a value of the wrong kind.
|
||||
pub fn stroke_options_that_differ(
|
||||
&self,
|
||||
options: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
|
||||
let keys = self.kind.stroke_option_keys();
|
||||
if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
return Err(if keys.is_empty() {
|
||||
format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase())
|
||||
} else {
|
||||
format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", "))
|
||||
});
|
||||
}
|
||||
let edited = self.with_stroke_options(options)?.kind.option_values();
|
||||
let own = self.kind.option_values();
|
||||
Ok(keys
|
||||
.iter()
|
||||
.filter_map(|k| {
|
||||
let v = edited.get(*k)?;
|
||||
(own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone()))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- library ----------
|
||||
|
||||
/// The brush library of `doc`: its stored brushes, or the defaults when it has none.
|
||||
@@ -842,12 +1079,26 @@ fn tolerance(scale: f64) -> f64 {
|
||||
/// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id
|
||||
/// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush,
|
||||
/// and what they draw by name that would draw one is left out ([`leave_out_brushed`]).
|
||||
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`).
|
||||
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own
|
||||
/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values
|
||||
/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is.
|
||||
pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let edited;
|
||||
let brush = if stroke.brush_options.is_empty() {
|
||||
brush
|
||||
} else {
|
||||
match brush.with_stroke_options(&stroke.brush_options) {
|
||||
Ok(b) => {
|
||||
edited = b;
|
||||
&edited
|
||||
}
|
||||
Err(_) => brush,
|
||||
}
|
||||
};
|
||||
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
@@ -856,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
for n in &mut out {
|
||||
colorize(n, colorization, &stroke.paint);
|
||||
}
|
||||
// One piece per copy, in the order the copies run along the path.
|
||||
if let BrushKind::Scatter(s) = &brush.kind
|
||||
&& s.hue_jitter > 0.0
|
||||
{
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
leave_out_brushed(doc, &mut out, &mut Known::new());
|
||||
out
|
||||
}
|
||||
@@ -1008,6 +1265,14 @@ pub fn has_brush(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
|
||||
}
|
||||
|
||||
/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes
|
||||
/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so
|
||||
/// the profile does not change what such a stroke draws. A stroke without a brush, or one that
|
||||
/// names a brush `lib` lacks, draws a plain stroke, which follows the profile.
|
||||
pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool {
|
||||
stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name))
|
||||
}
|
||||
|
||||
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
|
||||
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
|
||||
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
|
||||
|
||||
@@ -120,6 +120,13 @@ impl StoredArt {
|
||||
doc.number_mounted_art();
|
||||
}
|
||||
|
||||
/// Sets the art on `doc` as [`Document::mounted_art`] with the ids it is stored with, the id
|
||||
/// counter left as it is: what a save looks through, writing back only the brushes whose art it
|
||||
/// changed ([`Self::write_back`]).
|
||||
pub fn mount_as_stored(&self, doc: &mut Document) {
|
||||
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
|
||||
}
|
||||
|
||||
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
|
||||
/// included) back into its library entry: the entry at its index when that entry is as it was
|
||||
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
|
||||
@@ -826,6 +827,86 @@ fn bristle_makes_translucent_strands() {
|
||||
assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bristle_pen_pressure_changes_its_footprint() {
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
|
||||
let render = |pressure| {
|
||||
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) };
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
|
||||
};
|
||||
let light = render(0.0);
|
||||
let heavy = render(1.0);
|
||||
assert_eq!(light.len(), heavy.len());
|
||||
assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bristle_pen_pressure_is_sampled_along_the_stroke() {
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
|
||||
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s);
|
||||
let mut points = Vec::new();
|
||||
for n in &out {
|
||||
all_points(n, &mut points);
|
||||
}
|
||||
let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
|
||||
let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
|
||||
assert!(late > early * 1.4, "spread along stroke: {early} -> {late}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimmed_bristle_strands_read_pressure_where_they_begin() {
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) };
|
||||
let render = |points| {
|
||||
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) };
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s)
|
||||
};
|
||||
let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]);
|
||||
assert_eq!(ramp.len(), neutral.len());
|
||||
let start = |n: &Node| {
|
||||
let anchors = &n.path_data().unwrap().subpaths[0].anchors;
|
||||
let first = anchors[0].p;
|
||||
let opposite = anchors[anchors.len() - 16].p;
|
||||
(first.x, (first.y - opposite.y).abs())
|
||||
};
|
||||
let mut checked = false;
|
||||
for (ramp, neutral) in ramp.iter().zip(&neutral) {
|
||||
let (x, width) = start(ramp);
|
||||
if x < 12.0 {
|
||||
continue;
|
||||
}
|
||||
let (_, neutral_width) = start(neutral);
|
||||
let expected = 0.5 + x / 80.0;
|
||||
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
|
||||
checked = true;
|
||||
}
|
||||
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bristle_pen_orientation_changes_its_footprint() {
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
|
||||
let render = |tilt, bearing, rotation| {
|
||||
let flat = |x| vec![(0.0, x), (1.0, x)];
|
||||
let s = StrokeLayer {
|
||||
tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }),
|
||||
bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }),
|
||||
rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }),
|
||||
..stroke(1.0)
|
||||
};
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
|
||||
};
|
||||
let neutral = bounds(&render(0.5, 0.0, 0.0)).height();
|
||||
let flat = bounds(&render(1.0, 0.0, 0.0)).height();
|
||||
let upright = bounds(&render(0.0, 0.0, 0.0)).height();
|
||||
let bearing = bounds(&render(0.5, 90.0, 0.0)).height();
|
||||
let rotation = bounds(&render(0.5, 0.0, 90.0)).height();
|
||||
assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}");
|
||||
assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}");
|
||||
assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tints_colorization_uses_stroke_colour() {
|
||||
let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
@@ -952,6 +1033,165 @@ fn stain_mixes_type_strokes_too() {
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
}
|
||||
|
||||
/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`.
|
||||
fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush {
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(Paint::solid(fill));
|
||||
Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// The fill color of each copy.
|
||||
fn fill_colors(out: &[Node]) -> Vec<Color> {
|
||||
out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect()
|
||||
}
|
||||
|
||||
/// How far hue `h` is from `from`, in degrees, either way round.
|
||||
fn hue_gap(h: f32, from: f32) -> f32 {
|
||||
let d = (h - from).rem_euclid(360.0);
|
||||
d.min(360.0 - d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_turns_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hues: Vec<f32> = colors.iter().map(|c| c.to_hsb()[0]).collect();
|
||||
assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}");
|
||||
assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}");
|
||||
// Saturation and brightness stay; the copies stay where they were, at their size and angle.
|
||||
assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}");
|
||||
let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_of_zero_changes_nothing() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red));
|
||||
// A brush without hue jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap();
|
||||
assert!(v.get("hue_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["hue_jitter"] = serde_json::json!(45.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, 45.0);
|
||||
// Values outside 0..180 are clamped.
|
||||
for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["hue_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.hue_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_turns_after_the_colorization() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Tints: black art takes the blue stroke color, which then turns.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hues: Vec<f32> =
|
||||
fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect();
|
||||
assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}");
|
||||
assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}");
|
||||
// A gray stroke color has no hue: its tints stay as they are.
|
||||
let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0);
|
||||
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray);
|
||||
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray);
|
||||
assert_eq!(fill_colors(&turned), fill_colors(&still));
|
||||
// Nor does black ink alone, nor a gray, as a process stroke color.
|
||||
for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] {
|
||||
let key = StrokeLayer::new(Paint::solid(key), 1.0);
|
||||
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key);
|
||||
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key);
|
||||
assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}");
|
||||
}
|
||||
// A turned process color stays a process color, turned over its C, M and Y with its K kept.
|
||||
let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0)));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert_eq!(k, 0.25);
|
||||
// Full ink in one channel and none in another, as the color before it.
|
||||
assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}");
|
||||
}
|
||||
// An RGB color keeps its saturation and brightness in its own values.
|
||||
let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0)));
|
||||
for c in &rgb {
|
||||
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
|
||||
assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}");
|
||||
}
|
||||
// A Lab color keeps its lightness and chroma.
|
||||
let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0)));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
for c in &lab {
|
||||
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
|
||||
assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color
|
||||
/// linked to a swatch (which loses the link); a pattern paint stays.
|
||||
#[test]
|
||||
fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let typed = |hue_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }),
|
||||
};
|
||||
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
|
||||
let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0)));
|
||||
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
|
||||
assert_eq!(turned.len(), still.len());
|
||||
assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}");
|
||||
assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}");
|
||||
// Tints and Shades and Hue Shift: the colors they give turn.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] {
|
||||
let art = Color::rgb(1.0, 0.0, 0.0);
|
||||
let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue));
|
||||
let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue));
|
||||
assert_eq!(turned.len(), still.len());
|
||||
assert_ne!(turned, still, "{colorization:?}");
|
||||
for (t, s) in turned.iter().zip(&still) {
|
||||
assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}");
|
||||
}
|
||||
}
|
||||
// A color linked to a swatch turns and loses the link; a pattern paint stays.
|
||||
let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 };
|
||||
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art.appearance.set_stroke(pattern.clone());
|
||||
let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) };
|
||||
let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0));
|
||||
let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0));
|
||||
assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked));
|
||||
assert_eq!(turned.len(), still.len());
|
||||
for n in &turned {
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
@@ -2037,3 +2277,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `options` as a stroke's own brush settings.
|
||||
fn with_options(options: serde_json::Value) -> StrokeLayer {
|
||||
StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strokes_own_options_change_its_art_and_leave_the_brush() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
let path = line(20.0, 50.0, 220.0, 50.0);
|
||||
let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0})));
|
||||
assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half));
|
||||
assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush");
|
||||
let BrushKind::Art(a) = &brush.kind else { panic!("art brush") };
|
||||
assert_eq!(a.width, 100.0, "the brush keeps its width");
|
||||
// A calligraphic stroke's own size and angle.
|
||||
let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0})));
|
||||
assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib));
|
||||
// A pattern stroke's own scale doubles the tiles across it.
|
||||
let pattern = pattern_brush(PatternFit::Stretch, false);
|
||||
let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height();
|
||||
let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height();
|
||||
assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_options_are_checked_and_kept_within_their_ranges() {
|
||||
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// Out of range: clamped; equal to the brush's own value: left out.
|
||||
let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap();
|
||||
assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0}));
|
||||
// A field the type does not take, and a value of the wrong kind, are errors.
|
||||
assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle"));
|
||||
assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err());
|
||||
let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
|
||||
assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err());
|
||||
assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty());
|
||||
// A colorization object changes only the fields it gives: Hue Shift keeps the key it has.
|
||||
let key = Color::rgb(0.0, 0.0, 1.0);
|
||||
let hue = Brush {
|
||||
name: "h".into(),
|
||||
kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }),
|
||||
};
|
||||
let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap();
|
||||
assert_eq!(tints.kind.colorization(), Colorization::Tints);
|
||||
let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
|
||||
assert!(back.is_empty(), "the brush's own colorization: {back:?}");
|
||||
// Hue Shift without a key takes the art's main color, as brush.options gives it.
|
||||
let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
|
||||
let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK);
|
||||
assert_eq!(keyless["colorization"]["method"], json!("hueShift"));
|
||||
assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap());
|
||||
// Settings that do not read draw the brush as it is.
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(20.0, 50.0, 220.0, 50.0);
|
||||
let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]})));
|
||||
assert!(near(bounds(&odd).height(), 4.0, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_stroke_option_items_keep_the_items_the_stroke_has() {
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// A scatter brush at fixed sizes, with no modes of its own: they follow its values.
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) };
|
||||
let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") };
|
||||
assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's");
|
||||
// A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode.
|
||||
let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap();
|
||||
let BrushKind::Scatter(s) = e.kind else { panic!("scatter") };
|
||||
assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]);
|
||||
// The kept modes follow the values as they are kept within their ranges.
|
||||
let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap();
|
||||
let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") };
|
||||
assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]);
|
||||
// Modes that change nothing are no setting of the stroke's: they keep following its values.
|
||||
let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap();
|
||||
assert!(same.is_empty(), "{same:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() {
|
||||
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
|
||||
// A brush whose modes are its own, and a stroke whose modes follow its values instead.
|
||||
let mut b = calli(0.0, 100.0, 3.0);
|
||||
if let BrushKind::Calligraphic(c) = &mut b.kind {
|
||||
c.modes = Some([Variation::Pressure; 3]);
|
||||
}
|
||||
let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap();
|
||||
assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0}));
|
||||
let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") };
|
||||
assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give");
|
||||
// A brush whose modes follow its values: a null `modes` is the brush's own and is left out.
|
||||
let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap();
|
||||
assert!(plain.is_empty(), "{plain:?}");
|
||||
}
|
||||
@@ -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};
|
||||
@@ -596,6 +596,9 @@ struct Walk<'a> {
|
||||
clips: Vec<Region>,
|
||||
/// The points those masks hold ([`MAX_MASK_POINTS`]).
|
||||
mask_points: usize,
|
||||
/// Set while the stroke pieces of a clipping path whose fill paints are drawn: they close, as
|
||||
/// its fill closes its outline.
|
||||
closing: bool,
|
||||
runs: Vec<Run>,
|
||||
points: usize,
|
||||
clip_tests: u64,
|
||||
@@ -624,6 +627,7 @@ impl<'a> Walk<'a> {
|
||||
tolerance,
|
||||
clips: vec![],
|
||||
mask_points: 0,
|
||||
closing: false,
|
||||
runs: vec![],
|
||||
points: 0,
|
||||
clip_tests: 0,
|
||||
@@ -827,7 +831,9 @@ impl<'a> Walk<'a> {
|
||||
let mut paint = first.clip_paint();
|
||||
// A stroke at 0% opacity isn't drawn, so the clipping path is drawn in its fill.
|
||||
let type_stroke = |s: &Node| matches!(&s.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.has_stroke()));
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s));
|
||||
// The strokes of a clipping path whose stroke effects were applied are a group of pieces,
|
||||
// which effects around it may have put in groups of their own.
|
||||
paint.stroke = paint.stroke.filter(|s| top_stroke(s).is_some() || type_stroke(s) || strokes_in_pieces(s));
|
||||
if paint.stroke.is_none()
|
||||
&& let Some(fill) = &paint.fill
|
||||
{
|
||||
@@ -852,9 +858,16 @@ impl<'a> Walk<'a> {
|
||||
None => {}
|
||||
}
|
||||
// Drawn whole where its stroke paints: a fill closes its outline, and type's characters
|
||||
// without a stroke are drawn too.
|
||||
if paint.stroke.is_some() {
|
||||
self.node(first, false);
|
||||
// without a stroke are drawn too. Pieces of a clipping path whose fill and stroke effects
|
||||
// were applied are drawn in its stroke pieces alone, closed where its fill paints.
|
||||
if let Some(stroke) = &paint.stroke {
|
||||
if first.extras().clip_pieces {
|
||||
let closing = std::mem::replace(&mut self.closing, paint.fill.as_ref().is_some_and(fills_in_pieces));
|
||||
self.node(stroke, false);
|
||||
self.closing = closing;
|
||||
} else {
|
||||
self.node(first, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,7 +887,8 @@ impl<'a> Walk<'a> {
|
||||
|
||||
/// A path drawn in its color: the topmost stroke's that paints, else the topmost fill's that
|
||||
/// paints (visible, with a paint and some opacity). A filled path's every subpath is closed,
|
||||
/// as its fill closes it, also when its stroke gives the color.
|
||||
/// as its fill closes it, also when its stroke gives the color, and so is each stroke piece
|
||||
/// of a clipping path whose fill paints ([`Walk::closing`]).
|
||||
fn shape(&mut self, n: &Node, bp: &BezPath) {
|
||||
if bp.elements().is_empty() {
|
||||
return;
|
||||
@@ -896,7 +910,7 @@ impl<'a> Walk<'a> {
|
||||
(None, None) => return,
|
||||
};
|
||||
let rgb = self.flat(paint);
|
||||
self.draw(rgb, bp, fill.is_some());
|
||||
self.draw(rgb, bp, fill.is_some() || self.closing);
|
||||
}
|
||||
|
||||
/// `bp` drawn in `rgb`: flattened (with `close` every subpath closed), then cut and added.
|
||||
@@ -1146,6 +1160,18 @@ fn top_stroke(n: &Node) -> Option<&StrokeLayer> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a stroke that paints ([`top_stroke`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn strokes_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_stroke(c).is_some() || strokes_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// Whether a member of `n`, at any depth of its groups, has a fill that paints ([`top_fill`]),
|
||||
/// with it and the groups around it shown and not fully transparent.
|
||||
fn fills_in_pieces(n: &Node) -> bool {
|
||||
n.children().is_some_and(|ch| ch.iter().filter(|c| c.visible && c.opacity > 0.0).any(|c| top_fill(c).is_some() || fills_in_pieces(c)))
|
||||
}
|
||||
|
||||
/// The paint of the topmost fill of `n` that paints: visible, with a paint and some opacity.
|
||||
fn top_fill(n: &Node) -> Option<&Paint> {
|
||||
n.appearance.items.iter().rev().find_map(|i| match i {
|
||||
|
||||
@@ -747,6 +747,86 @@ fn a_clipping_path_is_drawn_where_it_paints() {
|
||||
});
|
||||
let t = text(&plot(&open_doc, &opts(&open_doc)));
|
||||
assert!(t.ends_with("SP2;PU282,1129;PD564,1129,564,847,282,1129;PU;SP0;"), "{t}");
|
||||
// A stroke with a geometry effect of its own is drawn once, over the art it clips, in its color.
|
||||
let moved = doc_with(|d| {
|
||||
let (blue, red) = (Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)));
|
||||
let mut clip = Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), Appearance::basic(blue, red, 1.0));
|
||||
for item in &mut clip.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
});
|
||||
assert_eq!(plot(&moved, &opts(&moved)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// So are the stroke's pieces when an effect around them put them in a group of their own.
|
||||
let grouped = |opacity: f32| {
|
||||
doc_with(|d| {
|
||||
// One path for each, carrying only that fill or stroke.
|
||||
let piece = |d: &mut Document, fill: bool| {
|
||||
let mut a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
a.items.retain(|i| matches!(i, AppearanceItem::Fill(_)) == fill);
|
||||
Arc::new(Node::path(d.alloc_id(), rect(20.0, 20.0, 40.0, 40.0), a))
|
||||
};
|
||||
let (fill, stroke) = (piece(d, true), piece(d, false));
|
||||
let mut copies = Node::group(d.alloc_id(), vec![stroke]);
|
||||
copies.opacity = opacity;
|
||||
let mut clip = Node::group(d.alloc_id(), vec![fill, Arc::new(copies)]);
|
||||
clip.extras_mut().clip_pieces = true;
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let shown = grouped(1.0);
|
||||
assert_eq!(plot(&shown, &opts(&shown)).pens, [[0, 0, 0], [255, 0, 0]]);
|
||||
// In a group at 0% opacity they are not drawn, and the clipping path is drawn in its fill.
|
||||
let faded = grouped(0.0);
|
||||
assert_eq!(plot(&faded, &opts(&faded)).pens, [[0, 0, 255], [0, 0, 0]]);
|
||||
// An open clipping path with a fill is drawn closed also where its stroke's effect moved it.
|
||||
let open_moved = |fill_opacity: f32| {
|
||||
doc_with(|d| {
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((20.0, 20.0));
|
||||
open.line_to((40.0, 20.0));
|
||||
open.line_to((40.0, 40.0));
|
||||
let a = Appearance::basic(Paint::solid(Color::rgb8(0, 0, 255)), Paint::solid(Color::rgb8(255, 0, 0)), 1.0);
|
||||
let mut clip = Node::path(d.alloc_id(), PathData::from_bezpath(&open), a);
|
||||
for item in &mut clip.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => f.opacity = fill_opacity,
|
||||
AppearanceItem::Stroke(s) => {
|
||||
let params = serde_json::json!({"moveH": 5});
|
||||
s.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
let black = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let clipped = Node::path(d.alloc_id(), line((0.0, 30.0), (200.0, 30.0)), black);
|
||||
let mut group = Node::group(d.alloc_id(), vec![Arc::new(clip), Arc::new(clipped)]);
|
||||
if let NodeKind::Group { clip, .. } = &mut group.kind {
|
||||
*clip = true;
|
||||
}
|
||||
vec![group]
|
||||
})
|
||||
};
|
||||
let filled = open_moved(1.0);
|
||||
let t = text(&plot(&filled, &opts(&filled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847,353,1129;PU;SP0;"), "{t}");
|
||||
// A fill at 0% opacity does not close it.
|
||||
let unfilled = open_moved(0.0);
|
||||
let t = text(&plot(&unfilled, &opts(&unfilled)));
|
||||
assert!(t.ends_with("SP2;PU353,1129;PD635,1129,635,847;PU;SP0;"), "{t}");
|
||||
}
|
||||
|
||||
/// A symbol `art` and an instance of it at its place.
|
||||
|
||||
+52
-10
@@ -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
|
||||
@@ -7,6 +7,8 @@
|
||||
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
|
||||
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
|
||||
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
|
||||
//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
|
||||
//! effects once for all of them.
|
||||
//!
|
||||
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
|
||||
//! clipping) is approximated or left out, and each such loss comes back as a warning.
|
||||
@@ -15,7 +17,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 +26,6 @@ mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -136,11 +137,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)]
|
||||
@@ -421,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6;
|
||||
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
|
||||
/// layers, guides and hidden objects are left out.
|
||||
pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
|
||||
Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as
|
||||
/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied
|
||||
/// once for all the drawings.
|
||||
pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result<Vec<DxfOutput>, String> {
|
||||
export_drawings_with(doc, opts, drawings, bake_for_drawings)
|
||||
}
|
||||
|
||||
/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when
|
||||
/// nothing changes.
|
||||
fn bake_for_drawings(doc: &Document) -> Option<Document> {
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, false, layers)
|
||||
}
|
||||
|
||||
/// [`export_drawings`] with `bake` applying the live effects.
|
||||
fn export_drawings_with(
|
||||
doc: &Document,
|
||||
opts: &DxfOptions,
|
||||
drawings: &[(Rect, bool)],
|
||||
bake: impl Fn(&Document) -> Option<Document>,
|
||||
) -> Result<Vec<DxfOutput>, String> {
|
||||
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
|
||||
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
|
||||
}
|
||||
let r = opts.region;
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
|
||||
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 });
|
||||
if drawings.is_empty() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let baked = bake(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
Ok(scene::Scene::new(doc, opts).run())
|
||||
Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+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))
|
||||
}
|
||||
}
|
||||
|
||||
+244
-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,221 @@ 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());
|
||||
}
|
||||
}
|
||||
|
||||
/// One drawing written by applying the live effects for it alone and walking the result, as each
|
||||
/// drawing of a multi-drawing export was written before [`export_drawings`].
|
||||
fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput {
|
||||
let baked = crate::bake_for_drawings(doc);
|
||||
crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run()
|
||||
}
|
||||
|
||||
/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes.
|
||||
type Written = (Vec<u8>, Vec<(String, Vec<u8>)>, Vec<String>, Vec<String>);
|
||||
|
||||
/// Every field of a written drawing, for comparing two.
|
||||
fn written(out: &DxfOutput) -> Written {
|
||||
let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect();
|
||||
(out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone())
|
||||
}
|
||||
|
||||
/// A Transform effect that moves its object `x` pt right.
|
||||
fn moved_by(mut n: Node, x: f64) -> Node {
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true });
|
||||
n
|
||||
}
|
||||
|
||||
/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect
|
||||
/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image.
|
||||
fn drawings_doc() -> Document {
|
||||
let png = craft_image_codecs::encode(
|
||||
&craft_image_codecs::Image::from_raw(
|
||||
2,
|
||||
2,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
[0u8, 128, 255, 255].repeat(4),
|
||||
)
|
||||
.unwrap(),
|
||||
craft_image_codecs::Format::Png,
|
||||
&craft_image_codecs::EncodeOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
|
||||
instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
|
||||
let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
faint.opacity = 0.5;
|
||||
faint.blend = vectorcraft_color::BlendMode::Multiply;
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 2,
|
||||
height: 2,
|
||||
xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
|
||||
});
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() {
|
||||
let d = drawings_doc();
|
||||
assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply");
|
||||
// The left and right halves cropped, the whole page uncropped, and a region off the page.
|
||||
let drawings = [
|
||||
(Rect::new(0.0, 0.0, 100.0, 100.0), true),
|
||||
(Rect::new(100.0, 0.0, 200.0, 100.0), true),
|
||||
(Rect::new(0.0, 0.0, 200.0, 100.0), false),
|
||||
(Rect::new(300.0, 0.0, 400.0, 100.0), true),
|
||||
];
|
||||
// With every option, and with images and hatches left out (which adds setting notes).
|
||||
let all_in = opts(&d);
|
||||
for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] {
|
||||
let bakes = std::cell::Cell::new(0);
|
||||
let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| {
|
||||
bakes.set(bakes.get() + 1);
|
||||
crate::bake_for_drawings(doc)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing");
|
||||
assert_eq!(outs.len(), drawings.len());
|
||||
for ((region, crop), out) in drawings.iter().zip(&outs) {
|
||||
let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() });
|
||||
assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}");
|
||||
let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap();
|
||||
assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}");
|
||||
}
|
||||
let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect();
|
||||
assert_eq!(public, outs.iter().map(written).collect::<Vec<_>>());
|
||||
// The halves hold different art, the left half a line with losses, and the region off the
|
||||
// page nothing.
|
||||
assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty());
|
||||
assert_ne!(outs[0].bytes, outs[1].bytes);
|
||||
assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty());
|
||||
if o.include_images {
|
||||
assert_eq!(outs[2].images.len(), 1);
|
||||
} else {
|
||||
assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawings_are_checked_before_the_live_effects_are_applied() {
|
||||
let d = drawings_doc();
|
||||
let o = opts(&d);
|
||||
let bakes = std::cell::Cell::new(0);
|
||||
let count = |doc: &Document| {
|
||||
bakes.set(bakes.get() + 1);
|
||||
crate::bake_for_drawings(doc)
|
||||
};
|
||||
let page = (d.artboards[0].rect, false);
|
||||
let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false);
|
||||
assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite");
|
||||
let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err();
|
||||
assert!(e.starts_with("scale must be a number"), "{e}");
|
||||
assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty());
|
||||
assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none");
|
||||
}
|
||||
|
||||
/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`.
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by
|
||||
/// drawing with the effects applied for each (as before [`export_drawings`]) and with
|
||||
/// [`export_drawings`], alternating, seven times each, and check that both write the same
|
||||
/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of
|
||||
/// wall-clock time.
|
||||
/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn dxf_artboards_bake_perf() {
|
||||
const BOARDS: usize = 8;
|
||||
let mut d = Document::new(200.0 * BOARDS as f64, 200.0);
|
||||
let layer = d.layers[0].id;
|
||||
let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
|
||||
let mut art = vec![];
|
||||
for i in 0..50 {
|
||||
let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0);
|
||||
art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5)));
|
||||
}
|
||||
let mut cell = Node::group(d.alloc_id(), art);
|
||||
cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"})));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) });
|
||||
for b in 0..BOARDS {
|
||||
let x0 = 200.0 * b as f64;
|
||||
for i in 0..250 {
|
||||
let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0);
|
||||
let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5);
|
||||
let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i});
|
||||
n.appearance.effects.push(effect("distort.roughen", params));
|
||||
d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
for i in 0..20 {
|
||||
let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0));
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf });
|
||||
d.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
}
|
||||
}
|
||||
let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() };
|
||||
let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect();
|
||||
let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::<Vec<_>>();
|
||||
let after = || export_drawings(&d, &o, &drawings).unwrap();
|
||||
let time = |f: &dyn Fn() -> Vec<DxfOutput>| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
let outs = f();
|
||||
let wall = wall.elapsed().as_secs_f64() * 1000.0;
|
||||
let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6);
|
||||
(outs, cpu, wall)
|
||||
};
|
||||
let (mut runs_before, mut runs_after) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
let (a, cpu_a, wall_a) = time(&before);
|
||||
let (b, cpu_b, wall_b) = time(&after);
|
||||
assert_eq!(a.len(), BOARDS);
|
||||
assert_eq!(a.iter().map(written).collect::<Vec<_>>(), b.iter().map(written).collect::<Vec<_>>(), "both write the same drawings");
|
||||
runs_before.push((cpu_a, wall_a));
|
||||
runs_after.push((cpu_b, wall_b));
|
||||
}
|
||||
let median = |runs: &[(Option<f64>, f64)], cpu: bool| {
|
||||
let mut v: Vec<f64> = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.get(v.len() / 2).copied()
|
||||
};
|
||||
for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] {
|
||||
println!(
|
||||
"{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}",
|
||||
median(runs, true),
|
||||
median(runs, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
+112
-5
@@ -94,6 +94,50 @@ impl Intent {
|
||||
}
|
||||
}
|
||||
|
||||
/// A color management policy (Edit → Color Settings): what opening a document does with a profile
|
||||
/// it is tagged with that is not the working space of its model.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Policy {
|
||||
/// The document loses the profile; its color numbers stay as they are.
|
||||
Off,
|
||||
/// The document keeps the profile.
|
||||
#[default]
|
||||
PreserveEmbedded,
|
||||
/// The colors are converted from the profile into the working space, which keeps their
|
||||
/// appearance, and the document loses the profile.
|
||||
Convert,
|
||||
/// CMYK only: the document loses the profile; its color numbers stay as they are.
|
||||
PreserveNumbers,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// The RGB policies, in menu order.
|
||||
pub const RGB: [Policy; 3] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert];
|
||||
/// The CMYK policies, in menu order.
|
||||
pub const CMYK: [Policy; 4] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers];
|
||||
/// Parse an id of [`Policy::id`].
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers].into_iter().find(|p| p.id() == s)
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "off",
|
||||
Policy::PreserveEmbedded => "preserveEmbedded",
|
||||
Policy::Convert => "convert",
|
||||
Policy::PreserveNumbers => "preserveNumbers",
|
||||
}
|
||||
}
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "Off",
|
||||
Policy::PreserveEmbedded => "Preserve Embedded Profiles",
|
||||
Policy::Convert => "Convert to Working Space",
|
||||
Policy::PreserveNumbers => "Preserve Numbers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProfileKind {
|
||||
@@ -134,11 +178,25 @@ pub struct ColorSettings {
|
||||
pub intent: Intent,
|
||||
/// Black-point compensation.
|
||||
pub bpc: bool,
|
||||
/// The color management policy for RGB profiles (one of [`Policy::RGB`]). Settings saved
|
||||
/// without one take the default.
|
||||
#[serde(default)]
|
||||
pub rgb_policy: Policy,
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
fn default() -> Self {
|
||||
Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
|
||||
Self {
|
||||
rgb: SRGB.into(),
|
||||
cmyk: GENERIC_CMYK.into(),
|
||||
intent: Intent::RelativeColorimetric,
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +347,9 @@ pub fn profiles_generation() -> u64 {
|
||||
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
|
||||
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
|
||||
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
|
||||
/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
|
||||
/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper
|
||||
/// as the media white point; the colorimetric Lab → CMYK table without black-point
|
||||
/// compensation, the perceptual and saturation ones with it); a profile the user
|
||||
/// loaded is the file it came from. Cached.
|
||||
pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
|
||||
static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new());
|
||||
@@ -303,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
|
||||
let bytes: Arc<[u8]> = if name == GRAY {
|
||||
icc::encode(&icc::gray_profile(name))?
|
||||
} else if BUILTIN_CMYK.contains(&name) {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
|
||||
icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
// The perceptual and saturation tables map the shadows with black-point compensation; the
|
||||
// colorimetric table is the inverse of the CMYK → Lab table, without it.
|
||||
let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?;
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?;
|
||||
let paper = match &cms.cmyk {
|
||||
CmykSpace::Generic(g) => g.paper_xyz(),
|
||||
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
|
||||
};
|
||||
let to_lab = |c| cms.cmyk_to_lab(c);
|
||||
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
|
||||
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
|
||||
} else {
|
||||
icc::builtin_rgb_bytes(name)?
|
||||
}
|
||||
@@ -518,6 +587,41 @@ impl Cms {
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let icc = |s: &RgbSpace| match s {
|
||||
RgbSpace::Icc(p) => Some(p.clone()),
|
||||
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
|
||||
};
|
||||
let [r, g, b] = icc(&self.rgb)
|
||||
.zip(icc(&dest.rgb))
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &[r, g, b], intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| dest.srgb_to_rgb(self.rgb_to_srgb([r, g, b])));
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
let inks = [c, m, y, k].map(|v| v.clamp(0.0, 1.0));
|
||||
let direct = match (&self.cmyk, &dest.cmyk) {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
Color::Gray { .. } | Color::Lab { .. } => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
|
||||
pub fn gamut_error(&self, c: &Color) -> f32 {
|
||||
match c {
|
||||
@@ -966,8 +1070,11 @@ pub fn working_settings() -> ColorSettings {
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
/// leaving both unchanged, if a profile is unknown or the RGB policy is Preserve Numbers).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
if !Policy::RGB.contains(&settings.rgb_policy) {
|
||||
return Err(CmsError::Unsupported(format!("the RGB policy can't be {}", settings.rgb_policy.id())));
|
||||
}
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
|
||||
@@ -133,6 +133,11 @@ pub struct GenericCmyk {
|
||||
}
|
||||
|
||||
impl GenericCmyk {
|
||||
/// Absolute XYZ (D50) of the paper.
|
||||
pub fn paper_xyz(&self) -> [f32; 3] {
|
||||
self.paper_xyz
|
||||
}
|
||||
|
||||
pub fn new(params: GenericCmykParams) -> Self {
|
||||
let paper_xyz = lab_to_xyz(params.paper);
|
||||
let mut prim = [D50; 16];
|
||||
|
||||
+119
-12
@@ -34,6 +34,17 @@ type Xf = Option<Arc<TransformF32Executor>>;
|
||||
/// generation only lets the cache drop what reloads left behind.
|
||||
type DirectKey = (u64, u64, usize, bool);
|
||||
|
||||
/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear
|
||||
/// tone curves, where black-point compensation is a linear remap, and from there into the
|
||||
/// destination.
|
||||
struct SameModel {
|
||||
into: Arc<TransformF32Executor>,
|
||||
out_of: Arc<TransformF32Executor>,
|
||||
/// The source's and the destination's black as luminance in the linear space (both 0 without
|
||||
/// compensation).
|
||||
black: [f32; 2],
|
||||
}
|
||||
|
||||
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
|
||||
pub struct IccProfile {
|
||||
pub name: String,
|
||||
@@ -49,6 +60,9 @@ pub struct IccProfile {
|
||||
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
|
||||
/// and black-point compensation.
|
||||
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
|
||||
/// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as
|
||||
/// [`Self::direct`] is.
|
||||
same_model: Mutex<Vec<(DirectKey, Option<Arc<SameModel>>)>>,
|
||||
}
|
||||
|
||||
/// A transform from one profile into an RGB profile without passing through sRGB: into the
|
||||
@@ -99,6 +113,7 @@ impl IccProfile {
|
||||
to_srgb: Default::default(),
|
||||
from_srgb: Default::default(),
|
||||
direct: Mutex::new(Vec::new()),
|
||||
same_model: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -172,6 +187,21 @@ impl IccProfile {
|
||||
Some(dst.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// Device pixels `v` (RGB / CMYK / Gray, 0..1, the profile's channels a pixel, any number of
|
||||
/// pixels) → sRGB in `dst` (three values a pixel), converted with `intent` in one pass of the
|
||||
/// cached transform. `None` when `v` doesn't hold whole pixels, `dst` doesn't hold three values
|
||||
/// for each, or no transform can be built.
|
||||
pub fn to_srgb_pixels(&self, v: &[f32], dst: &mut [f32], intent: Intent) -> Option<()> {
|
||||
let n = self.channels();
|
||||
if !v.len().is_multiple_of(n) || dst.len() != v.len() / n * 3 {
|
||||
return None;
|
||||
}
|
||||
let xf = self.to_xf(intent)?;
|
||||
xf.transform(v, dst).ok()?;
|
||||
dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// sRGB → device values.
|
||||
pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
|
||||
let xf = self.inverse_xf(intent)?;
|
||||
@@ -249,6 +279,69 @@ impl IccProfile {
|
||||
Some(Direct { to_linear, to_dest: Some(to_dest), black })
|
||||
}
|
||||
|
||||
/// Device values of this profile → device values of `dest`, a profile of the same model,
|
||||
/// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB
|
||||
/// keep their place. With `bpc` (and an intent other than absolute), this profile's black
|
||||
/// maps onto the destination's black (black-point compensation). `None` when `dest` is of
|
||||
/// another model or no transform can be built.
|
||||
pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
|
||||
if dest.kind != self.kind || v.len() != self.channels() {
|
||||
return None;
|
||||
}
|
||||
let bpc = bpc && intent != Intent::AbsoluteColorimetric;
|
||||
let generation = profiles_generation();
|
||||
let key = (dest.id, generation, intent_index(intent), bpc);
|
||||
let t = {
|
||||
let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.retain(|(k, _)| k.1 == generation);
|
||||
match cache.iter().find(|(k, _)| *k == key) {
|
||||
Some((_, t)) => t.clone(),
|
||||
None => {
|
||||
let t = self.build_same_model(dest, intent, bpc).map(Arc::new);
|
||||
cache.push((key, t.clone()));
|
||||
t
|
||||
}
|
||||
}
|
||||
}?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
t.into.transform(v, &mut lin).ok()?;
|
||||
let [from, to] = t.black;
|
||||
if from > 0.0 || to > 0.0 {
|
||||
lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from));
|
||||
}
|
||||
let lin = lin.map(|x| x.clamp(0.0, 1.0));
|
||||
let mut out = vec![0.0f32; dest.channels()];
|
||||
t.out_of.transform(&lin, &mut out).ok()?;
|
||||
Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
|
||||
}
|
||||
|
||||
fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<SameModel> {
|
||||
let mut linear = rgb_space(super::PROPHOTO_RGB)?;
|
||||
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
|
||||
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
|
||||
}
|
||||
linear.cicp = None;
|
||||
let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?;
|
||||
let black = if bpc {
|
||||
// Each profile's black: the darkest colour it reproduces, found as `build_direct`
|
||||
// finds it, as luminance in the linear space.
|
||||
let luminance = |p: &IccProfile, xf: &Arc<TransformF32Executor>| -> Option<f32> {
|
||||
let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
xf.transform(&inks, &mut lin).ok()?;
|
||||
let y = |c: &moxcms::Xyzd| c.y as f32;
|
||||
let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant);
|
||||
Some(lum.clamp(0.0, 0.5))
|
||||
};
|
||||
let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
[luminance(self, &into)?, luminance(dest, &back)?]
|
||||
} else {
|
||||
[0.0; 2]
|
||||
};
|
||||
Some(SameModel { into, out_of, black })
|
||||
}
|
||||
|
||||
/// Whether transforms can be built for this profile (checked at registration).
|
||||
pub fn usable(&self) -> bool {
|
||||
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
|
||||
@@ -353,11 +446,20 @@ const B2A_GRID: usize = 17;
|
||||
const GAMUT_GRID: usize = 9;
|
||||
|
||||
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
|
||||
/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
|
||||
/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped,
|
||||
/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the
|
||||
/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag.
|
||||
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
|
||||
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
|
||||
/// TIFF that embedded one, #2707).
|
||||
pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
|
||||
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
|
||||
/// the ICC-absolute colorimetric intent reproduces.
|
||||
pub(super) fn cmyk_profile(
|
||||
name: &str,
|
||||
paper: [f32; 3],
|
||||
to_lab: impl Fn([f32; 4]) -> lab::Lab,
|
||||
mapped: impl Fn(lab::Lab) -> [f32; 4],
|
||||
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
|
||||
) -> ColorProfile {
|
||||
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
|
||||
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
|
||||
@@ -366,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
let l = to_lab(cmyk);
|
||||
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
|
||||
}
|
||||
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
|
||||
for i in 0..B2A_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
|
||||
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
|
||||
}
|
||||
let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| {
|
||||
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
|
||||
for i in 0..B2A_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
|
||||
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
|
||||
}
|
||||
b2a
|
||||
};
|
||||
let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric));
|
||||
// Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut.
|
||||
let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3));
|
||||
for i in 0..GAMUT_GRID.pow(3) {
|
||||
let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID));
|
||||
let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0);
|
||||
gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX });
|
||||
gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX });
|
||||
}
|
||||
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
|
||||
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| {
|
||||
@@ -397,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
})
|
||||
};
|
||||
let a2b = table(4, 3, A2B_GRID, a2b);
|
||||
let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped);
|
||||
let b2a = table(3, 4, B2A_GRID, b2a);
|
||||
let gamut = table(3, 1, GAMUT_GRID, gamut);
|
||||
let mut p = ColorProfile::default();
|
||||
@@ -405,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
|
||||
p.pcs = DataColorSpace::Lab;
|
||||
p.rendering_intent = RenderingIntent::RelativeColorimetric;
|
||||
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
|
||||
p.media_white_point = Some(p.white_point);
|
||||
p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])));
|
||||
p.lut_a_to_b_perceptual = Some(a2b.clone());
|
||||
p.lut_a_to_b_saturation = Some(a2b.clone());
|
||||
p.lut_a_to_b_colorimetric = Some(a2b);
|
||||
p.lut_b_to_a_perceptual = Some(b2a.clone());
|
||||
p.lut_b_to_a_saturation = Some(b2a.clone());
|
||||
p.lut_b_to_a_perceptual = Some(b2a_mapped.clone());
|
||||
p.lut_b_to_a_saturation = Some(b2a_mapped);
|
||||
p.lut_b_to_a_colorimetric = Some(b2a);
|
||||
p.gamut = Some(gamut);
|
||||
labelled(p, name)
|
||||
|
||||
@@ -442,3 +442,39 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
let unknown = for_document(Some("no such profile"), Some(SRGB));
|
||||
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
|
||||
}
|
||||
|
||||
/// The color management policies parse from their ids, Preserve Numbers is a CMYK policy only, and
|
||||
/// settings saved before the policies existed read with the default policy.
|
||||
#[test]
|
||||
fn policies_parse_and_default_in_saved_settings() {
|
||||
for p in Policy::CMYK {
|
||||
assert_eq!(Policy::parse(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(Policy::parse("bogus"), None);
|
||||
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert_eq!((old.rgb_policy, old.cmyk_policy), (Policy::PreserveEmbedded, Policy::PreserveEmbedded));
|
||||
let saved = serde_json::to_value(ColorSettings { cmyk_policy: Policy::PreserveNumbers, ..Default::default() }).unwrap();
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
#[test]
|
||||
fn convert_into_keeps_the_appearance() {
|
||||
let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let working = cms();
|
||||
let rgb = Color::Rgb { r: 0.25, g: 0.4, b: 0.6 };
|
||||
let moved = wide.convert_into(&working, &rgb, Intent::RelativeColorimetric);
|
||||
assert_ne!(moved, rgb, "the numbers change");
|
||||
assert!(de(wide.display_rgb(&rgb), working.display_rgb(&moved)) < 1.0, "{rgb:?} → {moved:?}");
|
||||
let ink = Color::Cmyk { c: 0.2, m: 0.4, y: 0.6, k: 0.1 };
|
||||
let moved = wide.convert_into(&working, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }) && moved != ink, "{ink:?} → {moved:?}");
|
||||
assert!(delta_e2000(wide.lab(&ink), working.lab(&moved)) < 3.0, "{ink:?} → {moved:?}");
|
||||
for c in [Color::Gray { k: 0.3 }, Color::Lab { l: 50.0, a: 10.0, b: -20.0 }] {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() {
|
||||
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
|
||||
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
|
||||
}
|
||||
// And back: an in-gamut colour separates to about the same inks.
|
||||
let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
|
||||
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
|
||||
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
|
||||
assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
|
||||
// And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is
|
||||
// the colorimetric inverse of the CMYK → Lab table, with no black-point compensation.
|
||||
for inks in [
|
||||
[0.1, 0.6, 0.8, 0.0],
|
||||
[0.5, 0.1, 0.3, 0.1],
|
||||
[0.3, 0.3, 0.3, 0.2],
|
||||
[0.05, 0.05, 0.4, 0.0],
|
||||
[0.4, 0.3, 0.3, 0.6],
|
||||
[0.6, 0.5, 0.5, 0.4],
|
||||
[0.2, 0.2, 0.2, 0.8],
|
||||
[0.0, 0.0, 0.0, 0.5],
|
||||
] {
|
||||
let srgb = cms.cmyk_to_srgb(inks, false);
|
||||
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
|
||||
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
|
||||
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again));
|
||||
assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})");
|
||||
}
|
||||
// The perceptual table keeps black-point compensation: source black separates to inks
|
||||
// that print the press's black point, as the CMS separates it with compensation.
|
||||
let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap();
|
||||
let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap();
|
||||
let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]);
|
||||
let de = delta_e2000(printed(&want), printed(&got));
|
||||
assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() {
|
||||
// CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto
|
||||
// RGB, which holds every color these profiles print, so no display gamut clips the inks.
|
||||
// Inks that print outside sRGB come back to inks that print the same color.
|
||||
for name in BUILTIN_CMYK {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap();
|
||||
for inks in
|
||||
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]]
|
||||
{
|
||||
let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]]));
|
||||
// Within the ΔE of 3 that the gamut tag counts as reproduced.
|
||||
assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmyk_profiles_carry_their_paper_as_the_media_white() {
|
||||
let generic = generic::swop_like();
|
||||
let p = parse(&icc_bytes(GENERIC_CMYK).unwrap());
|
||||
let white = p.media_white_point.unwrap();
|
||||
let paper = lab::lab_to_xyz(generic.paper);
|
||||
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
|
||||
assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +99,28 @@ fn gray_is_srgb_toned() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_pixels_convert_as_each_one_does() {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(DISPLAY_P3).unwrap()).unwrap();
|
||||
let px = [[1.0f32, 0.0, 0.0], [0.2, 0.6, 0.9], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]];
|
||||
for intent in Intent::ALL {
|
||||
let v: Vec<f32> = px.iter().flatten().copied().collect();
|
||||
let mut dst = vec![0.0; v.len()];
|
||||
p.to_srgb_pixels(&v, &mut dst, intent).unwrap();
|
||||
for (i, rgb) in px.iter().enumerate() {
|
||||
let one = p.to_srgb(rgb, intent).unwrap();
|
||||
assert!(dst[i * 3..i * 3 + 3].iter().zip(one).all(|(a, b)| (a - b).abs() < 1e-5), "{intent:?} {rgb:?}: {dst:?} vs {one:?}");
|
||||
}
|
||||
}
|
||||
// Lengths that aren't whole pixels, or a destination of another size, are refused.
|
||||
assert!(p.to_srgb_pixels(&[0.5; 4], &mut [0.0; 3], Intent::Perceptual).is_none());
|
||||
assert!(p.to_srgb_pixels(&[0.5; 3], &mut [0.0; 6], Intent::Perceptual).is_none());
|
||||
let gray = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
|
||||
let mut dst = [0.0; 6];
|
||||
gray.to_srgb_pixels(&[0.25, 0.75], &mut dst, Intent::RelativeColorimetric).unwrap();
|
||||
assert!(dst.iter().zip([0.25, 0.25, 0.25, 0.75, 0.75, 0.75]).all(|(a, b)| (a - b).abs() < 0.01), "{dst:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_profiles_are_reproducible() {
|
||||
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
|
||||
@@ -94,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
|
||||
let rich = [0.75, 0.68, 0.67, 0.9];
|
||||
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
|
||||
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
|
||||
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
|
||||
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the
|
||||
// profile's Lab → CMYK table carries no compensation of its own).
|
||||
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
|
||||
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
|
||||
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}");
|
||||
// The screen shows what an sRGB conversion writes, compensated alike.
|
||||
let srgb = |bpc| {
|
||||
let c = icc_cmyk(bpc);
|
||||
@@ -252,3 +326,55 @@ fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones()
|
||||
assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}");
|
||||
assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}");
|
||||
}
|
||||
|
||||
/// A CMYK profile converts into another CMYK profile, ink for ink, and refuses a profile
|
||||
/// of another model or inks of the wrong count.
|
||||
#[test]
|
||||
fn cmyk_profiles_convert_into_each_other_directly() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let srgb = IccProfile::from_bytes(None, &icc_bytes(SRGB).unwrap()).unwrap();
|
||||
let inks = [0.2, 0.4, 0.6, 0.1];
|
||||
let out = generic.to_same_model_of(&device, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
assert_eq!(out.len(), 4);
|
||||
assert!(out.iter().zip(inks).any(|(a, b)| (a - b).abs() > 0.01), "{out:?}");
|
||||
assert!(generic.to_same_model_of(&srgb, &inks, Intent::RelativeColorimetric, false).is_none());
|
||||
assert!(generic.to_same_model_of(&device, &inks[..3], Intent::RelativeColorimetric, false).is_none());
|
||||
}
|
||||
|
||||
/// With black-point compensation, a CMYK profile's darkest ink converts into an ink as dark as a
|
||||
/// darker profile's darkest ink, and a dark grey of a darker profile converts lighter into a
|
||||
/// profile whose black is lighter; absolute colorimetric never compensates.
|
||||
#[test]
|
||||
fn cmyk_to_cmyk_compensates_the_black_point() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let rel = Intent::RelativeColorimetric;
|
||||
let lightness = |p: &IccProfile, inks: &[f32]| lab::srgb_to_lab(p.to_srgb(inks, rel).unwrap()).l;
|
||||
let black = |p: &IccProfile| p.from_srgb([0.0; 3], rel).unwrap();
|
||||
// Generic CMYK's black is a dark grey, the uncalibrated profile's is black.
|
||||
let (light, dark) = (lightness(&generic, &black(&generic)), lightness(&device, &black(&device)));
|
||||
assert!(light > dark + 5.0, "{light} vs {dark}");
|
||||
let into_device = |bpc| lightness(&device, &generic.to_same_model_of(&device, &black(&generic), rel, bpc).unwrap());
|
||||
let (on, off) = (into_device(true), into_device(false));
|
||||
assert!((on - dark).abs() < 1.5 && off > dark + 5.0, "with {on}, without {off}, the black {dark}");
|
||||
let grey = device.from_srgb([0.2; 3], rel).unwrap();
|
||||
let into_generic = |bpc| lightness(&generic, &device.to_same_model_of(&generic, &grey, rel, bpc).unwrap());
|
||||
let (on, off) = (into_generic(true), into_generic(false));
|
||||
assert!(on > off + 1.0, "with {on}, without {off}");
|
||||
for (from, to, inks) in [(&generic, &device, black(&generic)), (&device, &generic, grey)] {
|
||||
let abs = |bpc| from.to_same_model_of(to, &inks, Intent::AbsoluteColorimetric, bpc).unwrap();
|
||||
assert_eq!(abs(true), abs(false));
|
||||
}
|
||||
// Convert to Working Space (Cms::convert_into) compensates as Color Settings say.
|
||||
let device_name = register_icc(&icc_bytes(DEVICE_CMYK).unwrap(), Some("Test ICC Device CMYK".into())).unwrap().name;
|
||||
let rich = Color::Cmyk { c: 0.9, m: 0.8, y: 0.8, k: 1.0 };
|
||||
let convert = |bpc| {
|
||||
let dest = Cms::new(&ColorSettings { cmyk: device_name.clone(), bpc, ..ColorSettings::default() }).unwrap();
|
||||
icc_cmyk(bpc).convert_into(&dest, &rich, rel)
|
||||
};
|
||||
assert_ne!(convert(true), convert(false));
|
||||
// White is untouched.
|
||||
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
|
||||
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
}
|
||||
@@ -294,13 +294,19 @@ impl GuideOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
|
||||
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
|
||||
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
|
||||
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
|
||||
}
|
||||
|
||||
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
|
||||
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
|
||||
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
|
||||
if step == 0 {
|
||||
return c;
|
||||
}
|
||||
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
|
||||
let f = step_fraction(opts, step);
|
||||
let v = match opts.variation {
|
||||
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
|
||||
Variation::WarmCool => {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -11,21 +11,27 @@ workspace = true
|
||||
[features]
|
||||
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
|
||||
spine-count = []
|
||||
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
|
||||
symbol-read-count = []
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
image = { workspace = true }
|
||||
# Image headers (PNG and JPEG sizes, `pixels::header_size`) and CMYK JPEG inks (`cmyk`).
|
||||
craft-image-codecs = { workspace = true }
|
||||
tiff = { workspace = true }
|
||||
# 1-bit TIFFs compressed with CCITT Group 3 (Compression 2 and 3).
|
||||
hayro-ccitt = { workspace = true }
|
||||
zune-jpeg = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
flate2 = { workspace = true }
|
||||
# The CMYK JPEG reader `cmyk` had before craft-image-codecs, kept as the reference its inks match.
|
||||
zune-jpeg = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
@@ -143,6 +143,11 @@ impl Appearance {
|
||||
pub fn fill_paint(&self) -> Paint {
|
||||
self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None)
|
||||
}
|
||||
/// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this
|
||||
/// includes lower fills in the stack; zero opacity still counts for selecting its geometry.
|
||||
pub fn has_visible_fill(&self) -> bool {
|
||||
self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none()))
|
||||
}
|
||||
pub fn stroke_paint(&self) -> Paint {
|
||||
self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,11 @@ pub struct StrokeLayer {
|
||||
/// Brush applied to the stroke (by brush name).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub brush: Option<String>,
|
||||
/// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush
|
||||
/// definition fields, by their `brush.options` names, that replace the brush's values on this
|
||||
/// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them.
|
||||
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
|
||||
pub brush_options: serde_json::Map<String, serde_json::Value>,
|
||||
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -170,6 +175,7 @@ impl StrokeLayer {
|
||||
arrow_scale: (100.0, 100.0),
|
||||
profile: None,
|
||||
brush: None,
|
||||
brush_options: serde_json::Map::new(),
|
||||
opacity: 1.0,
|
||||
blend: BlendMode::Normal,
|
||||
visible: true,
|
||||
|
||||
+118
-8
@@ -840,15 +840,19 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
|
||||
/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
|
||||
/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
|
||||
/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
|
||||
/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
|
||||
/// end.
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return };
|
||||
let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
|
||||
let subpaths: Vec<&SubPath> = match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
|
||||
_ => return,
|
||||
};
|
||||
let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
|
||||
let mut o = Orient::of(sp);
|
||||
if reversed.get(i).copied().unwrap_or(false) {
|
||||
if sp.closed {
|
||||
@@ -2170,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
|
||||
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
|
||||
}
|
||||
|
||||
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
|
||||
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
|
||||
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
|
||||
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
|
||||
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
|
||||
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
|
||||
let rail = Rail::new(keys, spec);
|
||||
keys.windows(2).enumerate().all(|(i, w)| {
|
||||
let [a, b] = w else { return true };
|
||||
match spec.spacing {
|
||||
BlendSpacing::Steps(_) => true,
|
||||
// The count is `len / d` rounded, which grows with `len`.
|
||||
BlendSpacing::Distance(d) => {
|
||||
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
|
||||
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
|
||||
count(len - length) == count(len + length)
|
||||
}
|
||||
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
|
||||
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
|
||||
/// between their edges in key sizes), so the pair is settled when the least and the most of
|
||||
/// these ask for the same count.
|
||||
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ, but by too little to count, or by little more: moving them may cross
|
||||
// where they stop counting as the same. (The same colors stay the same.)
|
||||
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach =
|
||||
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
// The centers and sizes move by up to twice `length`.
|
||||
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
|
||||
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
|
||||
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
|
||||
reach.is_finite() && least == most
|
||||
}
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
|
||||
(_, Some((ba, bb))) => {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
if w <= 4.0 * length || h <= 4.0 * length {
|
||||
return false;
|
||||
}
|
||||
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
|
||||
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
|
||||
// Each edge moves by up to `length`: the distances between them by up to twice that,
|
||||
// and the mean sizes too.
|
||||
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
|
||||
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
|
||||
let m = 2.0 * length;
|
||||
let least = q(dx - m, dy - m, w + m, h + m);
|
||||
let most = q(dx + m, dy + m, w - m, h - m);
|
||||
least.is_finite() && most.is_finite() && count(least) == count(most)
|
||||
}
|
||||
(_, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
|
||||
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
|
||||
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
@@ -3531,4 +3599,46 @@ mod tests {
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
|
||||
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
|
||||
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
|
||||
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
|
||||
/// color difference or the keys' reach sits where its count changes, or keys of the same color
|
||||
/// are at most four times 0.01 pt wide.
|
||||
#[test]
|
||||
fn steps_settle_unless_rounding_can_change_their_count() {
|
||||
let (length, color) = (0.01, 0.001);
|
||||
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
|
||||
let spec = BlendSpec { spacing, ..Default::default() };
|
||||
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
|
||||
};
|
||||
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
|
||||
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
|
||||
|
||||
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
|
||||
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
|
||||
|
||||
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
|
||||
// (settled) and by 51.5 (where the count changes).
|
||||
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
|
||||
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
|
||||
// 10.0625 pt (80.5 steps) is not.
|
||||
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
|
||||
assert!(near(10.0));
|
||||
assert!(!near(10.0625));
|
||||
// Keys without bounds are counted by their colors alone.
|
||||
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
|
||||
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
|
||||
// are never settled.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
}
|
||||
}
|
||||
+950
-154
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,96 @@
|
||||
//! Images decoded through craft-image-codecs as the image crate gave them (#778): the renderer,
|
||||
//! File › Open and Place, SVG import, and embedded and linked images read their pixels with
|
||||
//! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`].
|
||||
|
||||
/// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds.
|
||||
pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
|
||||
|
||||
/// `bytes` decoded as `format` within `allowance` bytes, the pixels as stored (not turned
|
||||
/// upright) and as the image crate gave them ([`dynamic`]), with the ICC profile the file embeds.
|
||||
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
|
||||
/// with it.
|
||||
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
|
||||
let opts = craft_image_codecs::DecodeOptions {
|
||||
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
|
||||
keep_orientation: true,
|
||||
};
|
||||
let mut img = craft_image_codecs::decode_as_with(format, bytes, &opts)?;
|
||||
let icc = img.icc.take();
|
||||
let img = dynamic(img).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the decoded samples don't fit the image".into()))?;
|
||||
Ok((img, icc))
|
||||
}
|
||||
|
||||
/// `bytes` decoded within `max` bytes, counted as the file's samples and as RGBA (#1717), the
|
||||
/// pixels as stored and as the image crate gave them, with the ICC profile the file embeds.
|
||||
/// Image blobs read their pixels with it. `Ok(None)` when they would take more than `max` as
|
||||
/// samples or as RGBA (the header alone decides; the pixels are not read). `Err` when the bytes
|
||||
/// aren't an image the decoder reads, including a file whose header fits the allowance but whose
|
||||
/// pixels can't be decoded (a cut-short file, or one the decoder refuses as a decompression bomb).
|
||||
pub fn decode_within(bytes: &[u8], max: u64) -> Result<Option<DecodedImage>, craft_image_codecs::CodecError> {
|
||||
let format = craft_image_codecs::detect(bytes).ok_or(craft_image_codecs::CodecError::UnknownFormat)?;
|
||||
let (w, h, per_pixel) =
|
||||
decoded_layout(bytes, format).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the image's size can't be read".into()))?;
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
if pixels.saturating_mul(per_pixel) > max || pixels.saturating_mul(4) > max {
|
||||
return Ok(None);
|
||||
}
|
||||
decode_image(format, bytes, max).map(Some)
|
||||
}
|
||||
|
||||
/// A decoded image as the image crate's: 8- and 16-bit gray, gray and alpha, RGB and RGBA as they
|
||||
/// are, 32-bit float RGB and RGBA as they are, anything else as 8-bit RGBA.
|
||||
fn dynamic(img: craft_image_codecs::Image) -> Option<image::DynamicImage> {
|
||||
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
|
||||
use image::{DynamicImage as D, ImageBuffer as B};
|
||||
let (w, h) = img.dimensions();
|
||||
Some(match (img.layout(), img.sample_type()) {
|
||||
(L::Gray, S::U8) => D::ImageLuma8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::GrayA, S::U8) => D::ImageLumaA8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::Rgb, S::U8) => D::ImageRgb8(B::from_raw(w, h, img.into_data())?),
|
||||
(L::Rgba, S::U8) => D::ImageRgba8(B::from_raw(w, h, img.into_data())?),
|
||||
(layout @ (L::Gray | L::GrayA | L::Rgb | L::Rgba), S::U16) => {
|
||||
let v = img.to_u16_samples()?;
|
||||
match layout {
|
||||
L::Gray => D::ImageLuma16(B::from_raw(w, h, v)?),
|
||||
L::GrayA => D::ImageLumaA16(B::from_raw(w, h, v)?),
|
||||
L::Rgb => D::ImageRgb16(B::from_raw(w, h, v)?),
|
||||
_ => D::ImageRgba16(B::from_raw(w, h, v)?),
|
||||
}
|
||||
}
|
||||
_ => D::ImageRgba8(B::from_raw(w, h, img.to_rgba8())?),
|
||||
})
|
||||
}
|
||||
|
||||
/// The image's size and the bytes a pixel of it takes decoded ([`decode_as`]), read from its
|
||||
/// header: palettes as RGB (RGBA with a transparent entry; GIF frames always RGBA), bitmaps as 8-bit
|
||||
/// gray, 16-bit samples as two bytes. A PNG whose header alone is there is read from its `IHDR`;
|
||||
/// a format whose header says only its size (TGA, ICO and the like) counts RGBA.
|
||||
pub fn decoded_layout(bytes: &[u8], format: craft_image_codecs::Format) -> Option<(u32, u32, u64)> {
|
||||
use craft_image_codecs::{Format as F, RasterColorType as T};
|
||||
if let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() {
|
||||
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
|
||||
let channels = match i.color_type {
|
||||
_ if format == F::Gif => 4,
|
||||
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
|
||||
T::Bitmap => 1,
|
||||
_ => u64::from(i.channels.max(1)),
|
||||
};
|
||||
return Some((i.width, i.height, channels * if deep { 2 } else { 1 }));
|
||||
}
|
||||
if format != F::Png {
|
||||
return crate::header_size(bytes).map(|(w, h)| (w, h, 4));
|
||||
}
|
||||
if bytes.get(12..16)? != b"IHDR" {
|
||||
return None;
|
||||
}
|
||||
let be = |at: usize| Some(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?));
|
||||
let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?);
|
||||
let channels: u64 = match color {
|
||||
0 => 1,
|
||||
2 | 3 => 3,
|
||||
4 => 2,
|
||||
6 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
Some((be(16)?, be(20)?, channels * if depth == 16 { 2 } else { 1 }))
|
||||
}
|
||||
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
|
||||
None,
|
||||
}
|
||||
|
||||
impl ArrowStyle {
|
||||
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
|
||||
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
|
||||
match self {
|
||||
Self::Filled => Some(crate::Arrowhead::Triangle),
|
||||
Self::Open => Some(crate::Arrowhead::TriangleOpen),
|
||||
Self::Tick => Some(crate::Arrowhead::Slash),
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the label sits across the dimension line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
|
||||
@@ -339,6 +339,7 @@ impl Document {
|
||||
/// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in
|
||||
/// tree order where `id` appears.
|
||||
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
|
||||
crate::id_index::note_path_lookup();
|
||||
// The cached path, while the node there still has the id ([`id_index`]).
|
||||
let cached = self.index.get();
|
||||
match cached.as_ref().and_then(|m| m.get(&id)) {
|
||||
@@ -423,6 +424,44 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
|
||||
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
|
||||
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
|
||||
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
|
||||
/// them. As for every cached lookup, a second node given an existing id after the cache was
|
||||
/// built is not found while the first one's cached path checks out (see [`id_index`]).
|
||||
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
|
||||
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
|
||||
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
|
||||
// of the document.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
let mut paths = Vec::with_capacity(want.len());
|
||||
let cached = want.iter().all(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
paths.push(p);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if cached {
|
||||
// A node's path sorts after the paths of the nodes before it in tree order, its
|
||||
// ancestors included.
|
||||
paths.sort_unstable();
|
||||
return paths.iter().filter_map(|p| self.node_at(p)).collect();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
self.walk(|n| {
|
||||
if want.contains(&n.id) {
|
||||
out.push(n);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node at index path `path` (as [`Document::index_path`] gives it).
|
||||
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
@@ -752,6 +791,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 +821,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.
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its
|
||||
//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes};
|
||||
|
||||
use crate::Appearance;
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
|
||||
/// The seed of the sizes a flare's rays and rings take when its settings give none.
|
||||
pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d;
|
||||
|
||||
/// One part of a flare: its name, outline, fill and opacity.
|
||||
pub type Part = (&'static str, PathData, Paint, f32);
|
||||
|
||||
/// The number `key` of the settings `v`, or `default`.
|
||||
fn number(v: &Value, key: &str, default: f64) -> f64 {
|
||||
v.get(key).and_then(Value::as_f64).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright
|
||||
/// center, a halo ring, rays of varying length and rings along the path to the end point.
|
||||
pub fn parts(v: &Value) -> Vec<Part> {
|
||||
let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0));
|
||||
let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y));
|
||||
let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0);
|
||||
let r = (number(v, "diameter", 100.0) / 2.0).max(0.5);
|
||||
let opacity = pct("opacity").min(1.0) as f32;
|
||||
let brightness = pct("brightness").min(1.0) as f32;
|
||||
let growth = pct("growth");
|
||||
let fuzz = pct("fuzziness").min(1.0);
|
||||
let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let longest = pct("longest");
|
||||
let ray_fuzz = pct("rayFuzziness").min(1.0);
|
||||
let ray_turn = number(v, "rotation", 0.0).to_radians();
|
||||
let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
|
||||
let largest = pct("largest");
|
||||
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
|
||||
// along the path from a sequence of its own; their count and sizes and the other parts stay.
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
(state >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
};
|
||||
let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1);
|
||||
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
|
||||
let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
|
||||
let mut parts: Vec<Part> = vec![];
|
||||
// Halo: a soft ring just outside the centre.
|
||||
let halo_r = r * (1.0 + growth) * 1.6;
|
||||
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
|
||||
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
|
||||
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
|
||||
// `rotation` turns them clockwise about the center.
|
||||
if rays > 0 {
|
||||
let mut bp = BezPath::new();
|
||||
let mut reach: f64 = 0.0;
|
||||
for i in 0..rays {
|
||||
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
|
||||
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
|
||||
reach = reach.max(len);
|
||||
let w = r * 0.035;
|
||||
let dir = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-dir.y, dir.x) * w;
|
||||
bp.move_to(c + n);
|
||||
bp.line_to(c + dir * len);
|
||||
bp.line_to(c - n);
|
||||
bp.line_to(c - dir * (w * 4.0));
|
||||
bp.close_path();
|
||||
}
|
||||
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
|
||||
}
|
||||
// Centre: bright core fading to transparent.
|
||||
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
|
||||
// Rings along the path to the end point (Largest = % of the average ring size).
|
||||
for _ in 0..rings {
|
||||
let t = rnd();
|
||||
let t = ring_at.as_mut().map_or(t, |next| next());
|
||||
let at = c + (end - c) * t;
|
||||
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
|
||||
let solid = rnd() < 0.5;
|
||||
let stops = if solid {
|
||||
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
|
||||
} else {
|
||||
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
|
||||
};
|
||||
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had
|
||||
/// since it was drawn), with the pixel-aligned property when `aligned`.
|
||||
pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node {
|
||||
let (name, pd, paint, op) = part;
|
||||
let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0));
|
||||
n.name = Some(name.into());
|
||||
n.blend = BlendMode::Screen;
|
||||
n.opacity = op;
|
||||
if aligned {
|
||||
n.extras_mut().pixel_aligned = true;
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
n.transform(xf, false);
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that
|
||||
/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse
|
||||
/// (transforms applied one by one and all at once can put the end on different axes of it).
|
||||
fn ellipse(geom: &GradientGeom) -> [f64; 3] {
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
[u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y]
|
||||
}
|
||||
|
||||
/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and
|
||||
/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice
|
||||
/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a
|
||||
/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient
|
||||
/// makes smaller than the tolerance.
|
||||
fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) {
|
||||
let [xx, xy, yy] = ellipse(geom);
|
||||
let half_diff = (xx - yy) / 2.0;
|
||||
let d = half_diff.hypot(xy);
|
||||
let longer = (xx + yy) / 2.0 + d;
|
||||
if longer.is_nan() || longer <= 0.0 {
|
||||
return (0.0, [0.0; 3]);
|
||||
}
|
||||
// The product of the half-axes is the area factor of the map from the unit circle, `u` across
|
||||
// `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation
|
||||
// of `xx * yy - xy * xy` for a narrow ellipse.
|
||||
let u = geom.end - geom.start;
|
||||
let w = Vec2::new(-u.y, u.x) * geom.aspect;
|
||||
let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0);
|
||||
let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) };
|
||||
(longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin])
|
||||
}
|
||||
|
||||
/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its
|
||||
/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its
|
||||
/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned
|
||||
/// part's snap allowance, which is a length).
|
||||
fn comparable(n: &Node) -> Value {
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
for key in ["id", "bbox_angle"] {
|
||||
m.remove(key);
|
||||
}
|
||||
if let Some(geom) = m.get_mut("geom")
|
||||
&& let Ok(g) = serde_json::from_value::<GradientGeom>(geom.clone())
|
||||
&& let Value::Object(geom) = geom
|
||||
{
|
||||
let (size, shape) = ellipse_size_and_shape(&g);
|
||||
geom.remove("end");
|
||||
geom.remove("aspect");
|
||||
geom.insert("ellipse".into(), serde_json::json!(size));
|
||||
m.insert("ellipseShape".into(), serde_json::json!(shape));
|
||||
}
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut v = serde_json::to_value(n).unwrap_or(Value::Null);
|
||||
strip(&mut v);
|
||||
v
|
||||
}
|
||||
|
||||
/// How close, relative to its size, a number in an outline or a gradient's placement must be to the
|
||||
/// one its transforms give: a few thousandths of a point near the edge of the canvas.
|
||||
const GEOMETRY_TOL: f64 = 1e-9;
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each
|
||||
/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`]
|
||||
/// relative to its size (or `tol`, when smaller), and `snap` points as well.
|
||||
fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool {
|
||||
match (a, b) {
|
||||
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
|
||||
(Some(x), Some(y)) => {
|
||||
let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) };
|
||||
(x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs()))
|
||||
}
|
||||
_ => x == y,
|
||||
},
|
||||
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)),
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
x.len() == y.len()
|
||||
&& x.iter().all(|(k, v)| {
|
||||
// A gradient's shape is ratios: compared as closely as geometry, without the snap.
|
||||
let snap = if k == "ellipseShape" { 0.0 } else { snap };
|
||||
y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape"))
|
||||
})
|
||||
}
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size.
|
||||
pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool {
|
||||
close(a, b, tol, 0.0, false)
|
||||
}
|
||||
|
||||
/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to
|
||||
/// the pixel grid moves each by up to a pixel.
|
||||
const PIXEL_SNAP: f64 = 1.0;
|
||||
|
||||
/// The settings of a flare group ([`crate::NodeExtras::flare`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FlareSpec {
|
||||
/// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and
|
||||
/// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in.
|
||||
pub params: serde_json::Value,
|
||||
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections and
|
||||
/// shears).
|
||||
#[serde(default = "identity", skip_serializing_if = "is_identity")]
|
||||
pub transform: Affine,
|
||||
}
|
||||
|
||||
fn identity() -> Affine {
|
||||
Affine::IDENTITY
|
||||
}
|
||||
|
||||
fn is_identity(a: &Affine) -> bool {
|
||||
*a == Affine::IDENTITY
|
||||
}
|
||||
|
||||
impl FlareSpec {
|
||||
/// The settings of a flare drawn with `params`, not transformed since.
|
||||
pub fn new(params: serde_json::Value) -> Self {
|
||||
Self { params, transform: Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// The point `key_x`, `key_y` of the params, where it is in the document now.
|
||||
fn point(&self, key_x: &str, key_y: &str) -> Option<Point> {
|
||||
let x = self.params.get(key_x)?.as_f64()?;
|
||||
let y = self.params.get(key_y)?.as_f64()?;
|
||||
Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The flare's center, where it is in the document now.
|
||||
pub fn center(&self) -> Option<Point> {
|
||||
self.point("cx", "cy")
|
||||
}
|
||||
|
||||
/// The rings' end point, where it is in the document now.
|
||||
pub fn end(&self) -> Option<Point> {
|
||||
self.point("x2", "y2")
|
||||
}
|
||||
|
||||
/// Its art transformed by `a`.
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
self.transform = a * self.transform;
|
||||
}
|
||||
|
||||
/// Whether `group`'s parts are still the ones these settings draw, in place: none was edited,
|
||||
/// distorted, removed or added, and the transform can be undone. The parts are compared where
|
||||
/// they are in the document, at any scale.
|
||||
pub fn draws(&self, group: &Node) -> bool {
|
||||
let NodeKind::Group { children, .. } = &group.kind else { return false };
|
||||
if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() {
|
||||
return false;
|
||||
}
|
||||
let expected = parts(&self.params);
|
||||
expected.len() == children.len()
|
||||
&& expected.into_iter().zip(children).all(|(part, child)| {
|
||||
let aligned = child.extras().pixel_aligned;
|
||||
let snap = if aligned { PIXEL_SNAP } else { 0.0 };
|
||||
close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// A flare's center and end point follow its art through a transform, and a save and reload
|
||||
/// keeps its settings.
|
||||
#[test]
|
||||
fn a_flare_keeps_its_settings_through_a_transform_and_a_save() {
|
||||
let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]);
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 }))));
|
||||
g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false);
|
||||
let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let c = spec.center().unwrap_or_else(|| panic!("no center"));
|
||||
let e = spec.end().unwrap_or_else(|| panic!("no end"));
|
||||
assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}");
|
||||
assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}");
|
||||
let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}"));
|
||||
let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(back.extras().flare.as_deref(), Some(&spec));
|
||||
// A flare that was not transformed writes no transform.
|
||||
let plain = FlareSpec::new(json!({ "cx": 1.0 }));
|
||||
assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } }));
|
||||
}
|
||||
|
||||
/// A flare group draws its settings until a part's gradient, opacity or outline is edited; a
|
||||
/// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its
|
||||
/// outline and its gradient's placement.
|
||||
#[test]
|
||||
fn a_flare_with_an_edited_part_no_longer_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0,
|
||||
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
|
||||
"rotation": 0.0, "largest": 50.0 });
|
||||
let flare = |aligned: bool| {
|
||||
let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75);
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
|
||||
let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
// The center, drawn at half opacity.
|
||||
f(std::sync::Arc::make_mut(&mut children[2]));
|
||||
};
|
||||
for aligned in [false, true] {
|
||||
let g = flare(aligned);
|
||||
assert!(spec(&g).draws(&g), "aligned {aligned}");
|
||||
let mut moved = g.clone();
|
||||
edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false));
|
||||
assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}");
|
||||
let mut faded = g.clone();
|
||||
edit(&mut faded, &|n| n.opacity *= 0.8);
|
||||
assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}");
|
||||
let mut shifted = g.clone();
|
||||
edit(&mut shifted, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.start.x += 20.0;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}");
|
||||
let mut squashed = g.clone();
|
||||
edit(&mut squashed, &|n| {
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
geom.aspect *= 0.5;
|
||||
}
|
||||
});
|
||||
assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow
|
||||
/// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`].
|
||||
#[test]
|
||||
fn an_ellipse_shape_tells_narrow_gradients_apart() {
|
||||
let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None };
|
||||
let of = ellipse_size_and_shape;
|
||||
let (size, shape) = of(&geom((11.0, 2.0), 0.5));
|
||||
// The same ellipse with its end point on the other axis.
|
||||
let (size2, shape2) = of(&geom((1.0, 7.0), 2.0));
|
||||
assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}");
|
||||
// A very narrow ellipse, given both ways, keeps its shape to within the tolerance.
|
||||
let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1);
|
||||
assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}");
|
||||
let narrow = of(&geom((11.0, 2.0), 1e-4)).1;
|
||||
for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] {
|
||||
assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}");
|
||||
}
|
||||
assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3]));
|
||||
}
|
||||
|
||||
/// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its
|
||||
/// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare
|
||||
/// does not draw its settings.
|
||||
#[test]
|
||||
fn a_flare_scaled_far_down_still_draws_its_settings() {
|
||||
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 });
|
||||
let flare_aligned = |xf: Affine, aligned: bool| {
|
||||
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
|
||||
let mut g = Node::group(NodeId(1), children.collect());
|
||||
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
|
||||
g
|
||||
};
|
||||
let flare = |xf: Affine| flare_aligned(xf, false);
|
||||
// The center's gradient placement, to edit.
|
||||
let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| {
|
||||
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
|
||||
if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut()
|
||||
&& let Paint::Gradient(gp) = &mut fill.paint
|
||||
&& let Some(geom) = &mut gp.geom
|
||||
{
|
||||
f(geom);
|
||||
} else {
|
||||
panic!("the center has no gradient fill");
|
||||
}
|
||||
};
|
||||
let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g));
|
||||
assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%");
|
||||
assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis");
|
||||
assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas");
|
||||
assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away");
|
||||
assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened");
|
||||
// At that size a part whose gradient's shape was edited no longer draws the settings.
|
||||
let mut squashed = flare(Affine::scale(1e-6));
|
||||
assert!(draws(&squashed), "scaled to 0.0001%");
|
||||
center_geom(&mut squashed, &|geom| geom.aspect *= 0.5);
|
||||
assert!(!draws(&squashed), "gradient shape at 0.0001%");
|
||||
// A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change,
|
||||
// even when the ellipse keeps its size.
|
||||
let mut reshaped = flare_aligned(Affine::IDENTITY, true);
|
||||
assert!(draws(&reshaped), "aligned");
|
||||
center_geom(&mut reshaped, &|geom| {
|
||||
let a = geom.aspect;
|
||||
geom.aspect = a * 0.5;
|
||||
geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt();
|
||||
});
|
||||
assert!(!draws(&reshaped), "gradient shape of the same size, aligned");
|
||||
}
|
||||
}
|
||||
+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,
|
||||
|
||||
+1050
-223
File diff suppressed because it is too large.
Load diff
+1149
-4
File diff suppressed because it is too large.
Load diff
@@ -82,6 +82,16 @@ impl Paths {
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.ids.len()
|
||||
}
|
||||
/// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None`
|
||||
/// when it isn't in the table.
|
||||
pub(crate) fn entry(&self, id: &NodeId) -> Option<Option<u32>> {
|
||||
self.ids.get(id).copied()
|
||||
}
|
||||
/// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its
|
||||
/// siblings.
|
||||
pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> {
|
||||
self.at.get(e as usize).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
|
||||
@@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() {
|
||||
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`path_lookups`] of this thread.
|
||||
static PATH_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that
|
||||
/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included.
|
||||
pub fn path_lookups() -> u64 {
|
||||
PATH_LOOKUPS.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_lookups`].
|
||||
pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
|
||||
#[derive(Default)]
|
||||
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
|
||||
|
||||
+137
-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,35 +75,56 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
|
||||
})
|
||||
.collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for sw in doc.swatches_iter() {
|
||||
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
|
||||
&& !v.iter().any(|p| p.name == sw.name)
|
||||
// Only the first swatch of a name is the one [`spot_swatch`] finds.
|
||||
if !seen.insert(sw.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let (true, Some(color)) = (sw.spot, sw.paint.color())
|
||||
&& !PROCESS_PLATES.contains(&sw.name.as_str())
|
||||
{
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
|
||||
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
|
||||
/// prints on that plate.
|
||||
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
let s = doc.swatch(name).filter(|s| s.spot)?;
|
||||
s.paint.color().map(|c| doc.linked_color(c, true))
|
||||
if process_plate(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
|
||||
}
|
||||
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
pub type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
/// An ink amount clamped to 0..1; an amount that is not a finite number prints no ink.
|
||||
fn ink_amount(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate.
|
||||
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
|
||||
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
|
||||
/// tint on every plate. A tint that is not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [tint.clamp(0.0, 1.0); 4], spot: None, registration: true };
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
&& spot_swatch(doc, name).is_some()
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), tint.clamp(0.0, 1.0))), registration: false };
|
||||
let tint = ink_amount(tint);
|
||||
let mut cmyk = [0.0; 4];
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = tint;
|
||||
}
|
||||
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -100,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(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
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
|
||||
}
|
||||
@@ -195,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`.
|
||||
@@ -227,6 +269,85 @@ 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();
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
|
||||
let ink = |link: Link| inks(&d, &c, &look, link, Intent::RelativeColorimetric);
|
||||
for t in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let spot = ink(Some(("Gold", t)));
|
||||
assert_eq!(spot, Inks { cmyk: [0.0; 4], spot: Some(("Gold".into(), 0.0)), registration: false }, "{t}");
|
||||
assert_eq!((spot.on_plate("Gold"), spot.on_plate("Cyan")), (0.0, 0.0), "{t}");
|
||||
let reg = ink(Some((REGISTRATION, t)));
|
||||
assert_eq!(reg, Inks { cmyk: [0.0; 4], spot: None, registration: true }, "{t}");
|
||||
assert_eq!((reg.on_plate("Gold"), reg.on_plate("Black")), (0.0, 0.0), "{t}");
|
||||
// A stop's process plates still print beside a spot tint that prints nothing.
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Gold", t)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!((stop.cmyk, stop.on_plate("Gold")), ([0.25, 0.0, 0.4, 0.0], 0.0), "{t}");
|
||||
}
|
||||
// Finite tints outside 0..1 are clamped.
|
||||
assert_eq!(ink(Some(("Gold", 2.0))).on_plate("Gold"), 1.0);
|
||||
assert_eq!(ink(Some(("Gold", -1.0))).on_plate("Gold"), 0.0);
|
||||
assert_eq!(ink(Some((REGISTRATION, 2.0))).cmyk, [1.0; 4]);
|
||||
assert_eq!(ink(Some((REGISTRATION, -1.0))).cmyk, [0.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
|
||||
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
|
||||
|
||||
+218
-10
@@ -117,6 +117,29 @@ impl Document {
|
||||
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
|
||||
/// Returns the ids of the texts in the layers that changed.
|
||||
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
|
||||
self.resolve_inline_art_since(None, layout).changed
|
||||
}
|
||||
|
||||
/// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved,
|
||||
/// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the
|
||||
/// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the
|
||||
/// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then
|
||||
/// still measures the same, the type in the layer trees that are the same nodes as `last`'s
|
||||
/// already has these bounds: only the other layer trees are checked, in the same order, and
|
||||
/// the document and the ids returned are those of the full pass. Otherwise, or without `last`,
|
||||
/// the full pass runs.
|
||||
pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass {
|
||||
if let Some((last, kept)) = last
|
||||
&& self.same_inline_inputs(last, kept)
|
||||
{
|
||||
let measured = Measured(RefCell::new(kept.0.clone()));
|
||||
let mut changed = vec![];
|
||||
let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed);
|
||||
for (i, layer) in layers {
|
||||
self.layers[i] = layer;
|
||||
}
|
||||
return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true };
|
||||
}
|
||||
let mut out = vec![];
|
||||
let mut unused = vec![];
|
||||
let graph = InlineGraph::of(self);
|
||||
@@ -147,10 +170,44 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false }
|
||||
}
|
||||
|
||||
/// Whether the type in this document's layer trees that are the same nodes as `last`'s already
|
||||
/// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]).
|
||||
fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool {
|
||||
self.symbols.len() == last.symbols.len()
|
||||
&& self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& self.graph_designs.len() == last.graph_designs.len()
|
||||
&& self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& self.patterns.len() == last.patterns.len()
|
||||
&& self
|
||||
.patterns
|
||||
.iter()
|
||||
.zip(&last.patterns)
|
||||
.all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y)))
|
||||
&& crate::Shared::ptr_eq(&self.unknown, &last.unknown)
|
||||
&& kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pass of [`Document::resolve_inline_art_since`] did.
|
||||
#[derive(Debug)]
|
||||
pub struct InlinePass {
|
||||
/// The ids of the texts in the layers that changed, in the order the full pass finds them.
|
||||
pub changed: Vec<NodeId>,
|
||||
/// The bounds the pass gave the inline graphics of each symbol name, for the next pass.
|
||||
pub measured: InlineMeasured,
|
||||
/// Whether only the layer trees that differ from the last resolved document's were checked.
|
||||
pub partial: bool,
|
||||
}
|
||||
|
||||
/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each
|
||||
/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the
|
||||
/// pass before it measured, so the names of all the type in the document stay listed.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct InlineMeasured(HashMap<String, Option<Rect>>);
|
||||
|
||||
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
|
||||
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
|
||||
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
|
||||
@@ -185,6 +242,22 @@ fn resolve_tree(
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> bool {
|
||||
resolve_since(None, n, bounds, layout, changed)
|
||||
}
|
||||
|
||||
/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was
|
||||
/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same
|
||||
/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node
|
||||
/// of the tree is visited.
|
||||
fn resolve_since(
|
||||
old: Option<&Node>,
|
||||
n: &mut Arc<Node>,
|
||||
bounds: &dyn Fn(&str) -> Option<Rect>,
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> bool {
|
||||
#[cfg(test)]
|
||||
tests::VISITS.with(|v| v.set(v.get() + 1));
|
||||
let mut copied = false;
|
||||
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
|
||||
let node = Arc::make_mut(n);
|
||||
@@ -196,17 +269,17 @@ fn resolve_tree(
|
||||
}
|
||||
copied = true;
|
||||
}
|
||||
let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art);
|
||||
let mask = n.extras().mask.as_deref().and_then(|m| {
|
||||
let mut art = m.art.clone();
|
||||
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
|
||||
});
|
||||
let mut kids = vec![];
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let mut c = c.clone();
|
||||
if resolve_tree(&mut c, bounds, layout, changed) {
|
||||
kids.push((i, c));
|
||||
if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut art = m.art.clone();
|
||||
let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o);
|
||||
resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art)
|
||||
});
|
||||
let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice));
|
||||
let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed);
|
||||
if mask.is_none() && kids.is_empty() {
|
||||
return copied;
|
||||
}
|
||||
@@ -224,6 +297,35 @@ fn resolve_tree(
|
||||
true
|
||||
}
|
||||
|
||||
/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list
|
||||
/// before an edit) that has its id, found at the same position or else by id, and skips those that
|
||||
/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new
|
||||
/// node of each tree that changed.
|
||||
fn resolve_kids(
|
||||
old: Option<&[Arc<Node>]>,
|
||||
kids: &[Arc<Node>],
|
||||
bounds: &dyn Fn(&str) -> Option<Rect>,
|
||||
layout: &mut dyn FnMut(&mut TextObject),
|
||||
changed: &mut Vec<NodeId>,
|
||||
) -> Vec<(usize, Arc<Node>)> {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
let mut out = vec![];
|
||||
for (i, c) in kids.iter().enumerate() {
|
||||
let o = old.and_then(|old| match old.get(i) {
|
||||
Some(b) if b.id == c.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
|
||||
});
|
||||
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
|
||||
continue;
|
||||
}
|
||||
let mut c = c.clone();
|
||||
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
|
||||
out.push((i, c));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
|
||||
/// A symbol is first asked for after its own type is resolved (the pass goes in
|
||||
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
|
||||
@@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
thread_local! {
|
||||
/// How many nodes [`resolve_since`] has visited on this thread.
|
||||
pub(super) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The nodes visited since the last call.
|
||||
fn visits() -> usize {
|
||||
VISITS.with(|v| v.replace(0))
|
||||
}
|
||||
|
||||
/// A copy of `d` resolved by the full pass, and the ids that pass returns.
|
||||
fn fully_resolved(d: &Document) -> (Document, Vec<NodeId>) {
|
||||
let mut full = d.clone();
|
||||
let ids = full.resolve_inline_art_with(&mut |_| {});
|
||||
(full, ids)
|
||||
}
|
||||
|
||||
/// The children of the layer at `i`, for an edit.
|
||||
fn layer_kids(d: &mut Document, i: usize) -> &mut Vec<Arc<Node>> {
|
||||
match Arc::make_mut(&mut d.layers[i]).children_mut() {
|
||||
Some(kids) => kids,
|
||||
None => panic!("layer {i} is a group"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing
|
||||
/// `S` in the opacity mask of the second.
|
||||
fn many_groups() -> Document {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
symbol(&mut d, "S", vec![square]);
|
||||
for _ in 0..50 {
|
||||
let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect();
|
||||
let group = Node::group(d.alloc_id(), kids);
|
||||
d.layers.push(Arc::new(group));
|
||||
}
|
||||
let t = showing(&mut d, "S");
|
||||
layer_kids(&mut d, 0).push(t);
|
||||
let masked = showing(&mut d, "S");
|
||||
Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true)));
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() {
|
||||
let mut d = many_groups();
|
||||
let first = d.resolve_inline_art_since(None, &mut |_| {});
|
||||
assert!(!first.partial);
|
||||
assert_eq!(first.changed.len(), 2);
|
||||
let last = d.clone();
|
||||
visits();
|
||||
let _ = fully_resolved(&d);
|
||||
let full_visits = visits();
|
||||
// The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the
|
||||
// second group's opacity mask new type: its 20 squares stay the same nodes.
|
||||
let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0));
|
||||
layer_kids(&mut d, 30)[5] = moved;
|
||||
let added = showing(&mut d, "S");
|
||||
layer_kids(&mut d, 40).push(added.clone());
|
||||
let mask_type = showing(&mut d, "S");
|
||||
if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
m.art = mask_type.clone();
|
||||
}
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids, [mask_type.id, added.id]);
|
||||
visits();
|
||||
let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {});
|
||||
let partial_visits = visits();
|
||||
assert!(pass.partial);
|
||||
assert_eq!(pass.changed, ids);
|
||||
assert_eq!(d, want);
|
||||
// The three changed groups, the mask's new type, the moved square and the added type.
|
||||
assert_eq!(partial_visits, 6);
|
||||
assert!(full_visits > 1000, "{full_visits}");
|
||||
assert_eq!(pass.measured, first.measured);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_symbols_or_symbol_sizes_take_the_full_pass() {
|
||||
let mut d = many_groups();
|
||||
let mut pass = d.resolve_inline_art_since(None, &mut |_| {});
|
||||
// A natural size for S, its art unchanged.
|
||||
let last = d.clone();
|
||||
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] }));
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids.len(), 2);
|
||||
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert_eq!((&d, &pass.changed), (&want, &ids));
|
||||
// New art for S.
|
||||
let last = d.clone();
|
||||
let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0));
|
||||
d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger]));
|
||||
let (want, ids) = fully_resolved(&d);
|
||||
assert_eq!(ids.len(), 2);
|
||||
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert_eq!((&d, &pass.changed), (&want, &ids));
|
||||
// A measurement that no longer holds, with the same symbols and foreign data.
|
||||
let last = d.clone();
|
||||
let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))]));
|
||||
pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {});
|
||||
assert!(!pass.partial);
|
||||
assert!(pass.changed.is_empty());
|
||||
}
|
||||
|
||||
/// The position of each node in `order`.
|
||||
fn positions(order: &[usize]) -> Vec<usize> {
|
||||
let mut at = vec![0; order.len()];
|
||||
|
||||
+18
-7
@@ -14,13 +14,15 @@ 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 flare;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub use id_index::tree_walks;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
@@ -28,8 +30,9 @@ 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 inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub use shared::Shared;
|
||||
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
|
||||
pub use symbol_nine_slice::{
|
||||
@@ -37,6 +40,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;
|
||||
@@ -45,6 +49,8 @@ pub mod marks;
|
||||
mod mem;
|
||||
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
|
||||
pub mod metadata;
|
||||
mod nearest;
|
||||
pub use nearest::NearestFinder;
|
||||
pub mod node;
|
||||
pub mod objects_on_path;
|
||||
pub mod orient;
|
||||
@@ -52,7 +58,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;
|
||||
@@ -72,6 +78,9 @@ pub mod style_libs;
|
||||
pub mod swatches;
|
||||
mod symbols;
|
||||
pub use symbols::SymbolBoxes;
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
#[doc(hidden)]
|
||||
pub use symbols::symbols_read;
|
||||
pub mod text;
|
||||
pub mod trace;
|
||||
pub mod twist;
|
||||
@@ -94,8 +103,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};
|
||||
@@ -120,6 +130,7 @@ pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::GlyphForm;
|
||||
pub use text::PATH_LEAD_MAX;
|
||||
pub use text::WarichuAlign;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
@@ -127,7 +138,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -160,7 +171,7 @@ use limits::MAX_NEXT_ID;
|
||||
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
|
||||
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
|
||||
pub use stored_art::{StoredPlace, StoredRoot};
|
||||
pub use units::{ColorMode, Unit, parse_number};
|
||||
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Document {
|
||||
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+56
-1
@@ -65,7 +65,10 @@ pub use expand::{
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net,
|
||||
warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -88,6 +91,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smooth map takes each handle along the map's derivative, also far from the origin,
|
||||
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
|
||||
/// handles there.
|
||||
#[test]
|
||||
fn map_smooth_within_keeps_handles_far_from_the_origin() {
|
||||
for at in [0.0, 1e13] {
|
||||
let o = Point::new(at, at);
|
||||
let curve = PathData::single(vectorcraft_geom::SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
|
||||
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
|
||||
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
@@ -358,6 +385,34 @@ mod tests {
|
||||
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coons_places_are_where_the_patch_bends() {
|
||||
// A rectangle's sides have 65 evenly spaced points.
|
||||
let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places();
|
||||
assert_eq!((u.len(), v.len()), (65, 65));
|
||||
assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}");
|
||||
// A top object with a curved top: between two places next to each other the patch is
|
||||
// straight, in `u` and in `v`.
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0));
|
||||
path.line_to((100.0, 50.0));
|
||||
path.line_to((40.0, 50.0));
|
||||
path.line_to((0.0, 50.0));
|
||||
path.close_path();
|
||||
let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap();
|
||||
let [u, v] = c.places();
|
||||
assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}");
|
||||
assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}");
|
||||
for w in u.windows(2) {
|
||||
for y in [0.0, 0.3, 1.0] {
|
||||
let mid = c.eval((w[0] + w[1]) / 2.0, y);
|
||||
let half = c.eval(w[0], y).midpoint(c.eval(w[1], y));
|
||||
assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_go_on_past_the_content_box() {
|
||||
// A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -338,6 +338,31 @@ impl Coons {
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
|
||||
/// The places in `u` where the top or bottom side has a point, and the places in `v` where the
|
||||
/// left or right side has one, rising from 0 to 1. Between two places next to each other, each
|
||||
/// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of
|
||||
/// the grid they make.
|
||||
pub fn places(&self) -> [Vec<f64>; 2] {
|
||||
let sides = [&self.top, &self.right, &self.bottom, &self.left];
|
||||
let at = |which: usize| -> Vec<f64> {
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => knots.clone(),
|
||||
None => {
|
||||
let last = sides[which].len().saturating_sub(1).max(1);
|
||||
(0..=last).map(|i| i as f64 / last as f64).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let merge = |a: usize, b: usize| {
|
||||
let mut v = at(a);
|
||||
v.extend(at(b));
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
[merge(0, 2), merge(1, 3)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
|
||||
@@ -497,6 +497,48 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
|
||||
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
|
||||
/// mapped as points point different ways on the two sides of a join and the curve kinks there
|
||||
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
|
||||
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position.
|
||||
pub fn map_handles_within(
|
||||
path: &PathData,
|
||||
max_piece: f64,
|
||||
max: usize,
|
||||
f: impl Fn(Point) -> Point,
|
||||
handle: impl Fn(Point, Point) -> Point,
|
||||
) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, handle)
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
let v = h - p;
|
||||
let len = v.hypot();
|
||||
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
|
||||
if len.is_nan() || len <= 0.0 || len.is_infinite() {
|
||||
return f(p);
|
||||
}
|
||||
// A thousandth of the handle, or more where the coordinates are so large that so short a
|
||||
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
|
||||
// at most at the handle's own end.
|
||||
let size = p.x.abs().max(p.y.abs()).max(1.0);
|
||||
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
|
||||
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
|
||||
f(p) + d
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
|
||||
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
@@ -516,20 +558,21 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
// Evaluating an unchanged curve can overflow even when its control points are finite.
|
||||
let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) };
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
pending_in = Some(handle(sub.p3, sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -582,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod handle_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unsplit_curve_keeps_its_finite_control_points() {
|
||||
let start = Point::new(1e308, 0.0);
|
||||
let end = Point::new(1.03e308, 0.0);
|
||||
let path = PathData::new(vec![SubPath::new(
|
||||
vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)],
|
||||
false,
|
||||
)]);
|
||||
assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounded_samples_preserve_a_smooth_interior_join() {
|
||||
let center = Point::new(1e16, 0.0);
|
||||
let path = PathData::new(vec![SubPath::new(
|
||||
vec![
|
||||
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)),
|
||||
Anchor::with_handles(
|
||||
center,
|
||||
center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0),
|
||||
center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0),
|
||||
),
|
||||
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
)]);
|
||||
let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1));
|
||||
let join = &mapped.subpaths[0].anchors[1];
|
||||
let incoming = join.p - join.h_in;
|
||||
let outgoing = join.h_out - join.p;
|
||||
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
|
||||
assert!(incoming.dot(outgoing) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() {
|
||||
for x in [1e16, 1e16 + 2.0, -1e16] {
|
||||
for offset in [-6.0, -2.0, 2.0, 6.0] {
|
||||
let p = Point::new(x, 0.0);
|
||||
let h = Point::new(x + offset, 0.0);
|
||||
assert_eq!(mapped_handle(&|point| point, p, h), h);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-4
@@ -105,8 +105,13 @@ impl Document {
|
||||
n += shared(&self.para_styles, &newer.para_styles, styles);
|
||||
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
|
||||
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
|
||||
let custom = |f: &crate::CompositeFont| {
|
||||
vec_bytes(&f.custom) + f.custom.iter().map(|s| s.name.capacity() + s.characters.capacity() + part(&s.part)).sum::<usize>()
|
||||
};
|
||||
vec_bytes(c)
|
||||
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
|
||||
+ c.iter()
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
@@ -266,6 +271,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
.as_deref()
|
||||
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
|
||||
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
|
||||
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
|
||||
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
|
||||
@@ -276,7 +282,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
});
|
||||
}
|
||||
b += match &n.kind {
|
||||
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let was = other.and_then(|o| match &o.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
});
|
||||
path_bytes_besides(path, was) + boxed(live)
|
||||
}
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
@@ -293,8 +305,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
}
|
||||
|
||||
fn path_bytes(p: &PathData) -> usize {
|
||||
let anchors: usize =
|
||||
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
|
||||
path_bytes_besides(p, None)
|
||||
}
|
||||
|
||||
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
|
||||
/// a version made by changing one anchor shares every chunk but the one it changed.
|
||||
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
|
||||
let mut shared: Vec<usize> =
|
||||
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
|
||||
shared.sort_unstable();
|
||||
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
|
||||
let anchors: usize = p
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let table = s.anchors.table_bytes();
|
||||
let own: usize = s
|
||||
.anchors
|
||||
.chunk_allocations()
|
||||
.filter(|(id, _)| shared.binary_search(id).is_err())
|
||||
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
|
||||
.sum();
|
||||
if table == 0 { own } else { ALLOC + table + own }
|
||||
})
|
||||
.sum();
|
||||
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The nearest node of a kind at or above each of many objects, found along one index path per
|
||||
//! object.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::id_index::Paths;
|
||||
use crate::{Document, Node, NodeId};
|
||||
|
||||
/// Finds, for one object after another, the nearest node that passes a test: the object itself,
|
||||
/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`].
|
||||
///
|
||||
/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that
|
||||
/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache
|
||||
/// places the object and each id on its path where they are, a lookup reads that one path; an id
|
||||
/// the cache does not place there (one that appears more than once, or a cache older than the
|
||||
/// tree) is looked up with [`Document::node`].
|
||||
pub struct NearestFinder<'a> {
|
||||
doc: &'a Document,
|
||||
cache: Option<Arc<Paths>>,
|
||||
/// The cache entries from the top-level layer down to the object.
|
||||
entries: Vec<u32>,
|
||||
/// The nodes at those entries.
|
||||
nodes: Vec<&'a Node>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// A [`NearestFinder`] for this document.
|
||||
pub fn nearest_finder(&self) -> NearestFinder<'_> {
|
||||
NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> NearestFinder<'a> {
|
||||
/// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred`
|
||||
/// holds; `None` when `id` is not in the tree or no node on its path passes.
|
||||
pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> {
|
||||
let doc = self.doc;
|
||||
let ids: Vec<NodeId> = if self.cached_path(id) {
|
||||
let cache = self.cache.as_deref()?;
|
||||
// The depth of the first id from the object up that the cache does not place there.
|
||||
let mut unplaced = None;
|
||||
for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() {
|
||||
if cache.entry(&node.id) != Some(Some(e)) {
|
||||
unplaced = Some(k);
|
||||
break;
|
||||
}
|
||||
if pred(node) {
|
||||
return Some(node);
|
||||
}
|
||||
}
|
||||
let k = unplaced?;
|
||||
self.nodes[..=k].iter().map(|n| n.id).collect()
|
||||
} else {
|
||||
doc.ancestry(id).unwrap_or_default()
|
||||
};
|
||||
let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n)));
|
||||
// Those lookups may have built the cache again.
|
||||
self.cache = doc.index.get();
|
||||
found
|
||||
}
|
||||
|
||||
/// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for
|
||||
/// it or the path no longer leads to it.
|
||||
fn cached_path(&mut self, id: NodeId) -> bool {
|
||||
self.entries.clear();
|
||||
self.nodes.clear();
|
||||
let Some(cache) = self.cache.as_deref() else { return false };
|
||||
let Some(Some(mut e)) = cache.entry(&id) else { return false };
|
||||
loop {
|
||||
let Some((parent, _)) = cache.place(e) else { return false };
|
||||
self.entries.push(e);
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
// A parent's entry is made before its children's, so the walk up ends.
|
||||
if parent >= e {
|
||||
return false;
|
||||
}
|
||||
e = parent;
|
||||
}
|
||||
self.entries.reverse();
|
||||
let mut siblings: &'a [Arc<Node>] = &self.doc.layers;
|
||||
for &e in &self.entries {
|
||||
let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false };
|
||||
self.nodes.push(&**n);
|
||||
siblings = n.children().map_or(&[], |c| c.as_slice());
|
||||
}
|
||||
self.nodes.last().is_some_and(|n| n.id == id)
|
||||
}
|
||||
}
|
||||
@@ -74,19 +74,32 @@ impl Node {
|
||||
/// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted
|
||||
/// over it (unclipped). Each part is this object keeping only those appearance items (type:
|
||||
/// also only its characters' fills or strokes); `None` where it paints nothing, as right after
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths.
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths, and so does
|
||||
/// a group of the pieces a clipping path's fills and strokes draw ([`crate::NodeExtras::clip_pieces`]),
|
||||
/// even after effects around it split or copy those pieces into groups: each part is then that
|
||||
/// group keeping only the pieces of those fills or strokes.
|
||||
pub fn clip_paint(&self) -> ClipPaint {
|
||||
use crate::appearance::AppearanceItem;
|
||||
let item = |fill: bool, i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
if matches!(self.kind, NodeKind::Group { clip: false, .. }) && self.extras().clip_pieces {
|
||||
let part = |fill: bool| {
|
||||
let mut paints = false;
|
||||
let mut n = pieces_of(self, fill, &|i| item(fill, i), &mut paints)?;
|
||||
n.extras_mut().clip_pieces = false;
|
||||
paints.then_some(n)
|
||||
};
|
||||
return ClipPaint { fill: part(true), stroke: part(false) };
|
||||
}
|
||||
let runs = match &self.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None,
|
||||
NodeKind::Text(t) => Some(&t.runs),
|
||||
_ => return ClipPaint::default(),
|
||||
};
|
||||
let paints = |fill: bool| {
|
||||
let item = |i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
let item = |i: &AppearanceItem| item(fill, i);
|
||||
let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 };
|
||||
self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run))
|
||||
};
|
||||
@@ -110,6 +123,30 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`, a group of a clipping path's pieces or one of them, keeping only the pieces of its fills
|
||||
/// (`fill`) or of its strokes, at every depth of the groups an effect put them in; `None` when it
|
||||
/// holds none. `paints` is set when one of the kept fills or strokes paints.
|
||||
fn pieces_of(n: &Node, fill: bool, paints_item: &dyn Fn(&crate::appearance::AppearanceItem) -> bool, paints: &mut bool) -> Option<Node> {
|
||||
use crate::appearance::AppearanceItem;
|
||||
if let NodeKind::Group { children, clip: false } = &n.kind {
|
||||
let kept: Vec<_> = children.iter().filter_map(|c| pieces_of(c, fill, paints_item, paints).map(std::sync::Arc::new)).collect();
|
||||
if kept.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
*ch = kept;
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let items = &n.appearance.items;
|
||||
if !items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) == fill) {
|
||||
return None;
|
||||
}
|
||||
*paints |= items.iter().any(paints_item);
|
||||
Some(n.clone())
|
||||
}
|
||||
|
||||
/// What a clipping path paints ([`Node::clip_paint`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ClipPaint {
|
||||
|
||||
@@ -41,6 +41,9 @@ pub struct NodeExtras {
|
||||
/// Dimension object: the live measurement it draws; its ordinary group children hold its
|
||||
/// exportable appearance (Object › Dimensions, the Dimension tool).
|
||||
pub dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
/// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group
|
||||
/// children hold its art.
|
||||
pub flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
|
||||
/// filled non-zero) where this object is drawn over the group's other members.
|
||||
pub intertwine: Option<Box<PathData>>,
|
||||
@@ -79,6 +82,10 @@ pub struct NodeExtras {
|
||||
/// knockout group its knockout shape is the whole area of its triangle, not only where the
|
||||
/// image is opaque ([`Node::knockout_outline`]).
|
||||
pub warp_piece: bool,
|
||||
/// A group of the pieces a clipping path's fills and strokes draw once their geometry effects
|
||||
/// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints
|
||||
/// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]).
|
||||
pub clip_pieces: bool,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -96,6 +103,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
slice: None,
|
||||
perspective: None,
|
||||
dimension: None,
|
||||
flare: None,
|
||||
intertwine: None,
|
||||
intertwine_tiers: Vec::new(),
|
||||
live_paint_gaps: None,
|
||||
@@ -108,6 +116,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
pixel_aligned: false,
|
||||
color_mask: None,
|
||||
warp_piece: false,
|
||||
clip_pieces: false,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
@@ -179,6 +179,48 @@ impl LiveShape {
|
||||
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
|
||||
}
|
||||
}
|
||||
/// A line's length in the document, from its first end to its second. None for other shapes.
|
||||
pub fn line_length(&self) -> Option<f64> {
|
||||
let LiveShape::Line { a, b } = self else { return None };
|
||||
Some((*b - *a).hypot())
|
||||
}
|
||||
/// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the
|
||||
/// direction from its first end to its second (the Rotate field's sense). 0 for a line whose
|
||||
/// ends meet. None for other shapes.
|
||||
pub fn line_angle(&self) -> Option<f64> {
|
||||
let LiveShape::Line { a, b } = self else { return None };
|
||||
if a == b {
|
||||
return Some(0.0);
|
||||
}
|
||||
// No −0° or 360° from rounding: a line drawn left to right reads 0°.
|
||||
let a = (-self.angle_deg()).rem_euclid(360.0);
|
||||
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
|
||||
}
|
||||
/// Make a line `len` long (0 or more), keeping its first end in place and its direction, or
|
||||
/// pointing it to the right when its ends meet.
|
||||
pub fn set_line_length(&mut self, len: f64) {
|
||||
let LiveShape::Line { a, b } = self else { return };
|
||||
if !len.is_finite() || len < 0.0 {
|
||||
return;
|
||||
}
|
||||
let now = (*b - *a).hypot();
|
||||
*b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) };
|
||||
}
|
||||
/// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line
|
||||
/// whose ends meet stays as it is.
|
||||
pub fn set_line_angle(&mut self, angle: f64) {
|
||||
let LiveShape::Line { a, b } = self else { return };
|
||||
let half = (*b - *a).hypot() / 2.0;
|
||||
if !angle.is_finite() || half <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mid = a.midpoint(*b);
|
||||
let t = angle.to_radians();
|
||||
// The page's y axis points down, so a counterclockwise angle goes up the page.
|
||||
let (dx, dy) = (half * t.cos(), -half * t.sin());
|
||||
*a = Point::new(mid.x - dx, mid.y - dy);
|
||||
*b = Point::new(mid.x + dx, mid.y + dy);
|
||||
}
|
||||
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
|
||||
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
|
||||
pub fn make_sides_equal(&mut self) {
|
||||
|
||||
+102
-12
@@ -90,6 +90,42 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// This object without the paths made into guides among the members of its groups, layers,
|
||||
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
|
||||
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
|
||||
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
|
||||
/// its structure. `None` when it holds no such guide.
|
||||
pub fn without_guides(&self) -> Option<Node> {
|
||||
let (NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Intertwine { children }
|
||||
| NodeKind::Compound { children, .. }) = &self.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
|
||||
let mut changed = false;
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
changed = true;
|
||||
} else if let Some(stripped) = c.without_guides() {
|
||||
changed = true;
|
||||
out.push(Arc::new(stripped));
|
||||
} else {
|
||||
out.push(c.clone());
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut n = self.clone();
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = out;
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
@@ -216,8 +252,10 @@ impl Node {
|
||||
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
|
||||
/// takes in where its spine can put its keys and steps.
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the
|
||||
/// shapes their art paints with the geometry effects of their own fill or stroke
|
||||
/// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys
|
||||
/// and steps.
|
||||
pub fn reach_bounds(&self) -> Option<Rect> {
|
||||
self.reach(None)
|
||||
}
|
||||
@@ -228,7 +266,11 @@ impl Node {
|
||||
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
|
||||
/// guides, that box also holds the art box placed by each cell's map
|
||||
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform. An
|
||||
/// instance whose art holds a clipping path with live geometry effects also takes in the region
|
||||
/// they give it ([`crate::hit::set_clip_region`]): moved with the instance when it only moves its
|
||||
/// art, otherwise placed by it and grown by as far as the region reaches past the art, times √2
|
||||
/// and the larger of 1 and the Frobenius norm of the transform's linear part.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
@@ -250,14 +292,8 @@ impl Node {
|
||||
.map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
|
||||
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
|
||||
// the farthest it can reach from its shape.
|
||||
NodeKind::Image(_) => {
|
||||
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
})
|
||||
}
|
||||
// The frame and each shape the image's own fills and strokes paint.
|
||||
NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols),
|
||||
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
|
||||
// keys and the spine.
|
||||
NodeKind::Blend { children, spec } => {
|
||||
@@ -268,10 +304,46 @@ impl Node {
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
// The live geometry effects of the clipping paths in the art can draw it past its box,
|
||||
// and the box takes in each shape the art paints with the geometry effects of the
|
||||
// instance's own fill or stroke.
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let Some((s, art, region)) = symbols.and_then(|s| {
|
||||
let a = s.art(symbol)?;
|
||||
Some((s, a, a.reshaped?))
|
||||
}) else {
|
||||
return self.with_own_paint(self.visual(symbols), symbols);
|
||||
};
|
||||
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
|
||||
let placed = if moves_only(*xf) && map.is_none() {
|
||||
xf.transform_rect_bbox(region)
|
||||
} else {
|
||||
// An effect can reach a fixed distance past the art or a distance in proportion
|
||||
// to its size, as `SymbolBoxes::effects_reach` estimates it.
|
||||
let g = art.geometric;
|
||||
let all = region.union(g);
|
||||
let past = [g.x0 - region.x0, region.x1 - g.x1, g.y0 - region.y0, region.y1 - g.y1].into_iter().fold(0.0_f64, f64::max);
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let grow = past * std::f64::consts::SQRT_2 * (a * a + b * b + c * c + d * d).sqrt().max(1.0);
|
||||
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
|
||||
};
|
||||
let o = self.appearance.outset();
|
||||
self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols)
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// `start` grown by each shape the node's own fills and strokes paint
|
||||
/// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its
|
||||
/// shape.
|
||||
fn with_own_paint(&self, start: Option<Rect>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
|
||||
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
|
||||
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
|
||||
@@ -369,7 +441,7 @@ impl Node {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints (see `clip_paint`) strokes over the clip edge.
|
||||
let clip = children.first()?;
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) {
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) || clip.extras().clip_pieces {
|
||||
clip.visual(symbols)
|
||||
} else {
|
||||
clip.geometric(symbols)
|
||||
@@ -448,6 +520,12 @@ impl Node {
|
||||
{
|
||||
dimension.transform(a);
|
||||
}
|
||||
// So does a flare's center and end point.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(flare) = &mut e.flare
|
||||
{
|
||||
flare.transform(a);
|
||||
}
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
if !self.is_layer() {
|
||||
@@ -580,6 +658,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;
|
||||
|
||||
@@ -24,6 +24,7 @@ fn extras_are_written_flat_in_order() {
|
||||
e.envelope_edit_margin = Some([0.5, 0.5, 0.25, 0.25]);
|
||||
e.pixel_aligned = true;
|
||||
e.warp_piece = true;
|
||||
e.clip_pieces = true;
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
@@ -71,11 +72,13 @@ fn extras_are_written_flat_in_order() {
|
||||
"envelope_edit_margin",
|
||||
"pixel_aligned",
|
||||
"warp_piece",
|
||||
"clip_pieces",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(v["shape_mode"], "exclude");
|
||||
assert_eq!(v["pixel_aligned"], true);
|
||||
assert_eq!(v["warp_piece"], true);
|
||||
assert_eq!(v["clip_pieces"], true);
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
@@ -802,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
|
||||
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
|
||||
assert_eq!(calls, 0);
|
||||
}
|
||||
|
||||
/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its
|
||||
/// children, its later siblings or its ancestors' later siblings.
|
||||
#[test]
|
||||
fn try_walk_ends_at_the_break() {
|
||||
use std::ops::ControlFlow;
|
||||
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
|
||||
let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]);
|
||||
let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]);
|
||||
let mut all = vec![];
|
||||
root.walk(&mut |n| all.push(n.id));
|
||||
let mut seen = vec![];
|
||||
assert_eq!(
|
||||
root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
ControlFlow::<()>::Continue(())
|
||||
}),
|
||||
ControlFlow::Continue(())
|
||||
);
|
||||
assert_eq!(seen, all, "without a break it visits what walk visits, in the same order");
|
||||
seen.clear();
|
||||
let flow = root.try_walk(&mut |n| {
|
||||
seen.push(n.id);
|
||||
if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) }
|
||||
});
|
||||
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
|
||||
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
|
||||
}
|
||||
@@ -45,6 +45,7 @@ impl Serialize for Node {
|
||||
is_default(&self.bbox_angle),
|
||||
e.perspective.is_none(),
|
||||
e.dimension.is_none(),
|
||||
e.flare.is_none(),
|
||||
e.intertwine.is_none(),
|
||||
e.intertwine_tiers.is_empty(),
|
||||
e.live_paint_gaps.is_none(),
|
||||
@@ -57,6 +58,7 @@ impl Serialize for Node {
|
||||
is_default(&e.pixel_aligned),
|
||||
e.color_mask.is_none(),
|
||||
is_default(&e.warp_piece),
|
||||
is_default(&e.clip_pieces),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -90,6 +92,7 @@ impl Serialize for Node {
|
||||
field!("bbox_angle", &self.bbox_angle);
|
||||
field!("perspective", &e.perspective);
|
||||
field!("dimension", &e.dimension);
|
||||
field!("flare", &e.flare);
|
||||
field!("intertwine", &e.intertwine);
|
||||
field!("intertwine_tiers", &e.intertwine_tiers);
|
||||
field!("live_paint_gaps", &e.live_paint_gaps);
|
||||
@@ -102,6 +105,7 @@ impl Serialize for Node {
|
||||
field!("pixel_aligned", &e.pixel_aligned);
|
||||
field!("color_mask", &e.color_mask);
|
||||
field!("warp_piece", &e.warp_piece);
|
||||
field!("clip_pieces", &e.clip_pieces);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -226,6 +230,8 @@ pub(super) struct NodeWire {
|
||||
#[serde(default)]
|
||||
dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
#[serde(default)]
|
||||
flare: Option<Box<crate::flare::FlareSpec>>,
|
||||
#[serde(default)]
|
||||
intertwine: Option<Box<PathData>>,
|
||||
#[serde(default, deserialize_with = "counted_list")]
|
||||
intertwine_tiers: Vec<PathData>,
|
||||
@@ -249,6 +255,8 @@ pub(super) struct NodeWire {
|
||||
color_mask: Option<Box<crate::color_mask::ColorMask>>,
|
||||
#[serde(default)]
|
||||
warp_piece: bool,
|
||||
#[serde(default)]
|
||||
clip_pieces: bool,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
@@ -267,6 +275,7 @@ impl From<NodeWire> for Node {
|
||||
slice: w.slice,
|
||||
perspective: w.perspective,
|
||||
dimension: w.dimension,
|
||||
flare: w.flare,
|
||||
intertwine: w.intertwine,
|
||||
intertwine_tiers: w.intertwine_tiers,
|
||||
live_paint_gaps: w.live_paint_gaps,
|
||||
@@ -279,6 +288,7 @@ impl From<NodeWire> for Node {
|
||||
pixel_aligned: w.pixel_aligned,
|
||||
color_mask: w.color_mask,
|
||||
warp_piece: w.warp_piece,
|
||||
clip_pieces: w.clip_pieces,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
+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);
|
||||
|
||||
@@ -173,6 +173,10 @@ pub struct PatternDef {
|
||||
/// Size Tile to Art: the tile is the art bounds grown by the spacing.
|
||||
#[serde(default)]
|
||||
pub size_tile_to_art: bool,
|
||||
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by
|
||||
/// the same offset.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub move_tile_with_art: bool,
|
||||
#[serde(default)]
|
||||
pub h_spacing: f64,
|
||||
#[serde(default)]
|
||||
@@ -202,6 +206,7 @@ impl PatternDef {
|
||||
art,
|
||||
overlap: Overlap::default(),
|
||||
size_tile_to_art: false,
|
||||
move_tile_with_art: false,
|
||||
h_spacing: 0.0,
|
||||
v_spacing: 0.0,
|
||||
copies: 5,
|
||||
|
||||
+126
-23
@@ -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 {
|
||||
|
||||
+119
-15
@@ -49,6 +49,13 @@ pub struct Selection {
|
||||
/// it when no object is selected to align to it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
|
||||
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
|
||||
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
|
||||
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
|
||||
/// point is no longer a selected anchor, or fewer than two points are selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_anchor: Option<(NodeId, AnchorRef)>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
@@ -98,6 +105,7 @@ impl Selection {
|
||||
self.slices.clear();
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.key_anchor = None;
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
}
|
||||
@@ -113,9 +121,15 @@ impl Selection {
|
||||
self.set([instance]);
|
||||
self.symbol_part = Some(SymbolPart { instance, path });
|
||||
}
|
||||
/// Is there a key for Align: an object or a guide?
|
||||
/// Is there a key for Align: an object, a guide or an anchor point?
|
||||
pub fn has_key(&self) -> bool {
|
||||
self.key.is_some() || self.key_guide.is_some()
|
||||
self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some()
|
||||
}
|
||||
/// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is
|
||||
/// gone from its path.
|
||||
pub fn key_anchor_point(&self, doc: &Document) -> Option<vectorcraft_geom::Point> {
|
||||
let (id, (si, ai)) = self.key_anchor?;
|
||||
Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p)
|
||||
}
|
||||
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
@@ -143,6 +157,9 @@ impl Selection {
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
|
||||
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
@@ -162,24 +179,73 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| ids.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
|
||||
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, false);
|
||||
}
|
||||
/// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id
|
||||
/// listed twice is removed and then added again at the end.
|
||||
pub fn toggle_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, true);
|
||||
}
|
||||
/// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot
|
||||
/// carries the number of the activation that made it; an id's slots are kept only when they
|
||||
/// carry its current activation, so a removal drops every slot of the id at once.
|
||||
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
|
||||
use std::collections::hash_map::{Entry, HashMap};
|
||||
let mut ids = ids.into_iter().peekable();
|
||||
if ids.peek().is_none() {
|
||||
return;
|
||||
}
|
||||
self.target = None;
|
||||
self.slices.clear();
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
|
||||
let mut added: Vec<(NodeId, usize)> = Vec::new();
|
||||
let mut removed = false;
|
||||
for id in ids {
|
||||
match live.entry(id) {
|
||||
Entry::Vacant(e) => {
|
||||
let activation = added.len() + 1;
|
||||
e.insert(activation);
|
||||
added.push((id, activation));
|
||||
}
|
||||
Entry::Occupied(e) if toggle => {
|
||||
e.remove();
|
||||
removed = true;
|
||||
self.anchors.remove(&id);
|
||||
self.segments.remove(&id);
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
Entry::Occupied(_) => {}
|
||||
}
|
||||
}
|
||||
if removed {
|
||||
self.objects.retain(|id| live.get(id) == Some(&0));
|
||||
}
|
||||
self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id));
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for id in ids {
|
||||
if !self.slices.contains(&id) {
|
||||
self.slices.push(id);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
|
||||
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
for i in ids {
|
||||
if !self.guides.contains(&i) {
|
||||
self.guides.push(i);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id)));
|
||||
}
|
||||
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
|
||||
/// Shift-click on a guide).
|
||||
@@ -271,6 +337,40 @@ impl Selection {
|
||||
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
|
||||
self.key_guide = None;
|
||||
}
|
||||
// A key anchor needs its point on its path and selected as an anchor point (not as a
|
||||
// selected segment's end), with another point selected too: another anchor, or a path
|
||||
// selected whole (Align and Distribute act on path points only). It takes the place of a
|
||||
// key object or key guide.
|
||||
let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data());
|
||||
let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some());
|
||||
// Selected anchor points that are on their paths, counted up to two.
|
||||
let points = || {
|
||||
self.anchors
|
||||
.iter()
|
||||
.flat_map(|(o, set)| {
|
||||
let path = path_of(o);
|
||||
set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())))
|
||||
})
|
||||
.take(2)
|
||||
.count()
|
||||
};
|
||||
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
|
||||
self.objects.contains(&id)
|
||||
&& !self.segments.contains_key(&id)
|
||||
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
|
||||
&& found
|
||||
.get(&id)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
.and_then(|n| n.path_data())
|
||||
.is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))
|
||||
&& (points() >= 2 || self.objects.iter().any(whole_path))
|
||||
});
|
||||
if anchor_kept {
|
||||
self.key = None;
|
||||
self.key_guide = None;
|
||||
} else {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
|
||||
// and the object still in the symbol's art as a path, compound path or type, where neither
|
||||
// it nor a group or layer around it is hidden, locked or a template.
|
||||
@@ -348,6 +448,9 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| gone.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
|
||||
/// (the art of its sublayers too), anything else is selected itself.
|
||||
@@ -369,10 +472,11 @@ impl Selection {
|
||||
};
|
||||
let locks = doc.locked_artboards();
|
||||
ids.retain(|i| !locks.holds_id(*i));
|
||||
if ids.iter().all(|i| self.contains(*i)) {
|
||||
ids.iter().for_each(|i| self.remove(*i));
|
||||
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
|
||||
if ids.iter().all(|i| selected.contains(i)) {
|
||||
self.remove_all(ids);
|
||||
} else {
|
||||
ids.into_iter().for_each(|i| self.add(i));
|
||||
self.add_all(ids);
|
||||
}
|
||||
self.target = None;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,174 @@ fn remove_all_does_what_removing_each_does() {
|
||||
assert_eq!(none, s);
|
||||
}
|
||||
|
||||
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
|
||||
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
|
||||
fn seeded() -> Selection {
|
||||
let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() };
|
||||
for i in [2, 3, 4, 5] {
|
||||
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
|
||||
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
|
||||
}
|
||||
s.key = Some(NodeId(4));
|
||||
s.key_anchor = Some((NodeId(5), (0, 1)));
|
||||
s.target = Some(NodeId(3));
|
||||
s.slices = vec![NodeId(9)];
|
||||
s.guides = vec![NodeId(10)];
|
||||
s.key_guide = Some(NodeId(10));
|
||||
s.new_art = Arc::new(HashSet::from([NodeId(2)]));
|
||||
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
|
||||
s.on_path_member = Some(NodeId(11));
|
||||
s
|
||||
}
|
||||
|
||||
/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list.
|
||||
fn id_streams() -> Vec<Vec<NodeId>> {
|
||||
let mut streams: Vec<Vec<NodeId>> = [
|
||||
vec![],
|
||||
vec![4],
|
||||
vec![7],
|
||||
vec![3],
|
||||
vec![4, 1, 4, 7],
|
||||
vec![7, 8, 7, 7, 3, 3, 5],
|
||||
vec![1, 2, 3, 4, 5, 6],
|
||||
vec![6, 5, 4, 3, 2, 1, 1, 2, 3],
|
||||
vec![8, 2, 8, 2, 9, 9, 9],
|
||||
]
|
||||
.into_iter()
|
||||
.map(|ids| ids.into_iter().map(NodeId).collect())
|
||||
.collect();
|
||||
// Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with.
|
||||
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
for len in [5, 17, 40, 120] {
|
||||
let ids = (0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
NodeId(x % 12 + 1)
|
||||
})
|
||||
.collect();
|
||||
streams.push(ids);
|
||||
}
|
||||
streams
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_all_does_what_adding_each_does() {
|
||||
for ids in id_streams() {
|
||||
let mut one_by_one = seeded();
|
||||
for id in &ids {
|
||||
one_by_one.add(*id);
|
||||
}
|
||||
let mut all = seeded();
|
||||
all.add_all(ids.iter().copied());
|
||||
assert_eq!(all, one_by_one, "add_all({ids:?})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_all_does_what_toggling_each_does() {
|
||||
for ids in id_streams() {
|
||||
let mut one_by_one = seeded();
|
||||
for id in &ids {
|
||||
one_by_one.toggle(*id);
|
||||
}
|
||||
let mut all = seeded();
|
||||
all.toggle_all(ids.iter().copied());
|
||||
assert_eq!(all, one_by_one, "toggle_all({ids:?})");
|
||||
}
|
||||
// An id toggled twice is selected again, at the end, without the anchors it had.
|
||||
let mut s = seeded();
|
||||
s.toggle_all([NodeId(2), NodeId(2)]);
|
||||
assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId));
|
||||
assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2)));
|
||||
// A removed key and key anchor stay cleared.
|
||||
let mut s = seeded();
|
||||
s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]);
|
||||
assert_eq!((s.key, s.key_anchor), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_slices_and_set_guides_keep_the_first_of_each_id() {
|
||||
let mut s = seeded();
|
||||
s.set_slices([3, 1, 3, 2, 1].map(NodeId));
|
||||
assert_eq!(s.slices, [3, 1, 2].map(NodeId));
|
||||
assert!(s.objects.is_empty() && s.guides.is_empty());
|
||||
s.set_guides([5, 5, 4, 6, 4].map(NodeId));
|
||||
assert_eq!(s.guides, [5, 4, 6].map(NodeId));
|
||||
assert!(s.slices.is_empty());
|
||||
}
|
||||
|
||||
/// Shift-clicking a target circle does what removing or adding each of its art one by one does,
|
||||
/// for a layer with art, an empty layer and an object.
|
||||
#[test]
|
||||
fn toggle_target_does_what_toggling_its_art_one_by_one_does() {
|
||||
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let art: Vec<NodeId> = (0..4).map(|_| d.alloc_id()).collect();
|
||||
for id in &art {
|
||||
d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap();
|
||||
}
|
||||
let empty = d.alloc_id();
|
||||
d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap();
|
||||
let one_by_one = |s: &Selection, id: NodeId| {
|
||||
let mut s = s.clone();
|
||||
let ids = match d.node(id) {
|
||||
Some(n) if n.is_layer() => n.layer_art(true),
|
||||
_ => vec![id],
|
||||
};
|
||||
if ids.iter().all(|i| s.contains(*i)) {
|
||||
ids.iter().for_each(|i| s.remove(*i));
|
||||
} else {
|
||||
ids.into_iter().for_each(|i| s.add(i));
|
||||
}
|
||||
s.target = None;
|
||||
s
|
||||
};
|
||||
let mut starts = vec![Selection::default()];
|
||||
for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] {
|
||||
let mut s = seeded();
|
||||
s.objects = objects;
|
||||
s.key = s.objects.first().copied();
|
||||
s.anchors.insert(art[1], BTreeSet::from([(0, 0)]));
|
||||
starts.push(s);
|
||||
}
|
||||
for start in &starts {
|
||||
for id in [l, empty, art[2], NodeId(99)] {
|
||||
let mut s = start.clone();
|
||||
s.toggle_target(&d, id);
|
||||
assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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).
|
||||
@@ -213,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
|
||||
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
|
||||
}
|
||||
|
||||
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
|
||||
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
|
||||
/// as in an exported file. `None` for a language not in the list.
|
||||
pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
|
||||
}
|
||||
|
||||
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
|
||||
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
|
||||
/// first entry); `Err` for a language not in the list.
|
||||
@@ -397,6 +411,16 @@ impl DocSetup {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A document's language is written by its tag, the default's included (#3644).
|
||||
#[test]
|
||||
fn document_languages_have_their_tags() {
|
||||
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
|
||||
assert_eq!(language_tag("French"), Some("fr"));
|
||||
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
|
||||
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
|
||||
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
|
||||
}
|
||||
|
||||
/// Characters store a language of the list by its tag, the default as none.
|
||||
#[test]
|
||||
fn char_languages_are_stored_by_tag() {
|
||||
@@ -420,6 +444,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 +472,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()));
|
||||
|
||||
@@ -162,6 +162,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
|
||||
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
|
||||
BuiltinStyleLibrary { id: "neon-glow", name: "Neon & Glow", make: neon_glow },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -619,6 +620,44 @@ fn status_effects() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Neon & Glow: original multi-layer procedural styles with neon tubes, laser beams, and glowing halos.
|
||||
fn neon_glow() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style(
|
||||
"Cyan Neon",
|
||||
vec![S(StrokeLayer { opacity: 0.7, ..round("#00e5ff", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "screen", "opacity": 85.0, "x": 0.0, "y": 0.0, "blur": 8.0, "color": "#00e5ff"}))],
|
||||
),
|
||||
GraphicStyle {
|
||||
blend: BlendMode::Screen,
|
||||
..style(
|
||||
"Magenta Laser",
|
||||
vec![S(StrokeLayer { blend: BlendMode::Screen, ..round("#ff007f", 5.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#ff007f"}))],
|
||||
)
|
||||
},
|
||||
style(
|
||||
"Amber Tube",
|
||||
vec![S(StrokeLayer { opacity: 0.8, ..round("#ff8c00", 6.0) }), S(round("#ffea00", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#ff8c00"}))],
|
||||
),
|
||||
style(
|
||||
"Electric Lime",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#39ff14", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#39ff14"}))],
|
||||
),
|
||||
style(
|
||||
"Pulse Violet",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#7b2cbf", 5.0) }), S(round("#e0aaff", 1.5))],
|
||||
vec![
|
||||
fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 75.0, "blur": 6.0, "color": "#c77dff", "source": "edge"})),
|
||||
fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#7b2cbf"})),
|
||||
],
|
||||
),
|
||||
style("Cobalt Phosphor", vec![S(round("#0047ab", 6.0)), S(round("#ffffff", 1.5))], vec![fx("blur.gaussian", json!({"radius": 2.0}))]),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -750,4 +789,36 @@ mod tests {
|
||||
let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") };
|
||||
assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_and_glow_styles_are_defined_with_multi_strokes_and_effects() {
|
||||
let lib = builtin_style_library("neon-glow").expect("neon-glow library exists");
|
||||
assert_eq!(lib.name, "Neon & Glow");
|
||||
assert_eq!(lib.len(), 6);
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]);
|
||||
for g in &lib.styles {
|
||||
let strokes = g.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
assert!(strokes >= 2, "{} has {} strokes, expected >= 2", g.name, strokes);
|
||||
assert!(!g.appearance.effects.is_empty(), "{} has effects", g.name);
|
||||
}
|
||||
let cyan = lib.style("Cyan Neon").unwrap();
|
||||
assert_eq!(cyan.appearance.effects[0].id, "stylize.dropShadow");
|
||||
let magenta = lib.style("Magenta Laser").unwrap();
|
||||
assert_eq!(magenta.blend, BlendMode::Screen);
|
||||
let pulse = lib.style("Pulse Violet").unwrap();
|
||||
let pulse_fx: Vec<&str> = pulse.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(pulse_fx, ["stylize.innerGlow", "stylize.outerGlow"]);
|
||||
let cobalt = lib.style("Cobalt Phosphor").unwrap();
|
||||
assert_eq!(cobalt.appearance.effects[0].id, "blur.gaussian");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_glow_round_trips_through_vcstyles() {
|
||||
let lib = builtin_style_library("neon-glow").unwrap();
|
||||
let text = write(&lib);
|
||||
assert!(sniff(&text));
|
||||
let read_back = read(&text, "Fallback").unwrap();
|
||||
assert_eq!(*lib, read_back);
|
||||
}
|
||||
}
|
||||
+329
-13
@@ -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;
|
||||
@@ -186,8 +187,9 @@ impl Document {
|
||||
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
|
||||
/// visited once even when an id is inside another).
|
||||
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
|
||||
let listed: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let roots: Vec<NodeId> =
|
||||
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
|
||||
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
|
||||
let mut n = 0;
|
||||
let mut g = relink(f);
|
||||
for id in roots {
|
||||
@@ -340,18 +342,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 +407,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 +423,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 +741,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 +756,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 +844,287 @@ 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)]);
|
||||
}
|
||||
|
||||
/// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
|
||||
fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
|
||||
let roots: Vec<NodeId> =
|
||||
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
|
||||
let mut n = 0;
|
||||
let mut g = relink(f);
|
||||
for id in roots {
|
||||
let Some(node) = d.node(id) else { continue };
|
||||
if let Some((new, count)) = map_node(node, &mut g)
|
||||
&& let Some(slot) = d.node_mut(id)
|
||||
{
|
||||
*slot = new;
|
||||
n += count;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_within_ids_matches_a_search_of_the_ids() {
|
||||
// Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
|
||||
// rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let first = d.layers[0].id;
|
||||
let second = d.alloc_id();
|
||||
d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
|
||||
let rect = |d: &mut Document, i: u8| {
|
||||
let id = d.alloc_id();
|
||||
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
|
||||
(id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
|
||||
};
|
||||
let (r1, n1) = rect(&mut d, 1);
|
||||
let (r2, n2) = rect(&mut d, 2);
|
||||
let (r3, n3) = rect(&mut d, 3);
|
||||
let (r4, n4) = rect(&mut d, 4);
|
||||
let (r5, n5) = rect(&mut d, 5);
|
||||
let (inner, outer) = (d.alloc_id(), d.alloc_id());
|
||||
let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
|
||||
d.insert(Some(first), usize::MAX, outer_node).unwrap();
|
||||
d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
|
||||
d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
|
||||
let missing = NodeId(u64::MAX);
|
||||
let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
|
||||
// Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
|
||||
let mut lists: Vec<Vec<NodeId>> = vec![vec![]];
|
||||
let mut shorter: Vec<Vec<NodeId>> = vec![vec![]];
|
||||
for _ in 0..3 {
|
||||
shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
|
||||
lists.extend(shorter.iter().cloned());
|
||||
}
|
||||
assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
|
||||
for ids in &lists {
|
||||
// A callback that changes every paint it visits, so a paint visited twice counts twice.
|
||||
let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
|
||||
let mut d = d.clone();
|
||||
let mut visits = vec![];
|
||||
let n = map(&mut d, ids, &mut |c, s, t| {
|
||||
visits.push((*c, s.clone(), *t));
|
||||
*s = Some(format!("{}", visits.len()));
|
||||
*t *= 0.5;
|
||||
true
|
||||
});
|
||||
(n, visits, d.layers)
|
||||
};
|
||||
let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
|
||||
let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
|
||||
assert_eq!(by_set, by_search, "{ids:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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());
|
||||
}
|
||||
}
|
||||
+472
-11
@@ -9,7 +9,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::symbol_nine_slice::transformed;
|
||||
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
|
||||
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol};
|
||||
|
||||
/// The box a symbol instance is measured by when its symbol's art has no box
|
||||
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
|
||||
@@ -47,6 +47,11 @@ pub(crate) struct ArtBox {
|
||||
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
|
||||
/// holds one at any depth.
|
||||
pub(crate) sliced: bool,
|
||||
/// The box of the regions that the live geometry effects of the clipping paths in the art give
|
||||
/// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such
|
||||
/// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has
|
||||
/// one.
|
||||
pub(crate) reshaped: Option<Rect>,
|
||||
}
|
||||
|
||||
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
|
||||
@@ -102,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<'_> {
|
||||
@@ -126,10 +259,60 @@ 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 {
|
||||
#[cfg(test)]
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
|
||||
let mut names = HashMap::with_capacity(self.symbols.len());
|
||||
for (i, s) in self.symbols.iter().enumerate() {
|
||||
@@ -139,10 +322,21 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
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) };
|
||||
}
|
||||
|
||||
/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests
|
||||
/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count`
|
||||
/// feature, dev-dependencies only).
|
||||
#[cfg(any(test, feature = "symbol-read-count"))]
|
||||
#[doc(hidden)]
|
||||
pub fn symbols_read() -> usize {
|
||||
SYMBOLS_READ.with(Cell::get)
|
||||
}
|
||||
|
||||
impl<'a> SymbolBoxes<'a> {
|
||||
@@ -151,6 +345,16 @@ impl<'a> SymbolBoxes<'a> {
|
||||
self.doc
|
||||
}
|
||||
|
||||
/// New boxes for the same document, none measured yet and with none of the options set, that
|
||||
/// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring
|
||||
/// objects one at a time in boxes of their own made this way measures them as boxes made by
|
||||
/// [`Document::symbol_boxes`] do, without reading the symbol list again.
|
||||
pub fn unmeasured(&self) -> SymbolBoxes<'a> {
|
||||
let doc: &'a Document = self.doc;
|
||||
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
|
||||
doc.symbol_boxes().with_names(names)
|
||||
}
|
||||
|
||||
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
|
||||
/// document's symbols while they had the names and order they have now.
|
||||
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
|
||||
@@ -158,19 +362,24 @@ impl<'a> SymbolBoxes<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The art of the first symbol of the document named `name`, found in time independent of the
|
||||
/// number of symbols after the first lookup.
|
||||
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
|
||||
/// The first symbol of the document named `name`, found in time independent of the number of
|
||||
/// symbols after the first lookup.
|
||||
pub fn symbol(&self, name: &str) -> Option<&'a Symbol> {
|
||||
let doc: &'a Document = self.doc;
|
||||
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
|
||||
let i = *names.get(name)?;
|
||||
match doc.symbols.get(i) {
|
||||
Some(s) if s.name == name => Some(&s.art),
|
||||
Some(s) if s.name == name => Some(s),
|
||||
// Names that no longer match the symbols: the first symbol of that name.
|
||||
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
|
||||
_ => doc.symbols.iter().find(|s| s.name == name),
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of the first symbol of the document named `name` ([`Self::symbol`]).
|
||||
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
|
||||
self.symbol(name).map(|s| &s.art)
|
||||
}
|
||||
|
||||
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
|
||||
/// art box alone. An instance that scales or turns stroked art then measures a little larger
|
||||
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
|
||||
@@ -213,6 +422,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
|
||||
@@ -562,16 +773,27 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
|
||||
}
|
||||
});
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
|
||||
let mut reshaped = None;
|
||||
if effects {
|
||||
art.walk(&mut |n| {
|
||||
let b = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)),
|
||||
_ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)),
|
||||
_ => None,
|
||||
};
|
||||
reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite));
|
||||
});
|
||||
}
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_geom::shapes;
|
||||
use vectorcraft_geom::{Point, shapes};
|
||||
|
||||
use super::*;
|
||||
use crate::{Appearance, Symbol};
|
||||
use crate::{Appearance, NodeId, Symbol};
|
||||
|
||||
/// A rectangle filled black, with a `stroke` pt black stroke (0: none).
|
||||
fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node {
|
||||
@@ -706,6 +928,57 @@ mod tests {
|
||||
assert_eq!(s.sliced_placed.get(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_are_found_by_name_reading_the_list_once() {
|
||||
// 2,000 symbols, then two named "Mark": a name finds the first.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
|
||||
symbol(&mut d, &format!("Filler {i}"), vec![r]);
|
||||
}
|
||||
let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0));
|
||||
symbol(&mut d, "Mark", vec![first]);
|
||||
symbol(&mut d, "Mark", vec![second]);
|
||||
let read = || SYMBOLS_READ.with(Cell::get);
|
||||
let before = read();
|
||||
let s = d.symbol_boxes();
|
||||
for _ in 0..1000 {
|
||||
assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000])));
|
||||
assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7])));
|
||||
assert!(s.symbol("Nowhere").is_none());
|
||||
}
|
||||
assert_eq!(read() - before, d.symbols.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmeasured_boxes_share_the_index_and_nothing_measured() {
|
||||
// 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend
|
||||
// the boxes' budget of placed objects.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
for i in 0..2000 {
|
||||
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
|
||||
symbol(&mut d, &format!("Filler {i}"), vec![r]);
|
||||
}
|
||||
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
|
||||
symbol(&mut d, "Panel", vec![frame]);
|
||||
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
|
||||
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
symbol(&mut d, "Holder", vec![wide]);
|
||||
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5));
|
||||
let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick());
|
||||
let read = || SYMBOLS_READ.with(Cell::get);
|
||||
let s = d.symbol_boxes().quick();
|
||||
assert_eq!(holder.visual_bounds_with(&s), fresh);
|
||||
assert!(s.sliced_placed.get() > 0);
|
||||
let before = read();
|
||||
let u = s.unmeasured();
|
||||
assert_eq!(read(), before, "the index is shared");
|
||||
assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty());
|
||||
assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false));
|
||||
assert_eq!(holder.visual_bounds_with(&u.quick()), fresh);
|
||||
assert_eq!(read(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
|
||||
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
|
||||
@@ -895,4 +1168,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);
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, by walking the tree.
|
||||
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
out.push(n as *const Node);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
|
||||
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
|
||||
/// walk).
|
||||
#[test]
|
||||
fn nodes_in_order_match_a_walk() {
|
||||
for seed in 1..40 {
|
||||
let (d, ids) = tree(seed);
|
||||
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
d.drop_lookup_cache();
|
||||
} else {
|
||||
d.node(ids[0]);
|
||||
}
|
||||
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
|
||||
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
|
||||
}
|
||||
}
|
||||
// An id that the tree repeats: every node with it.
|
||||
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
|
||||
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
|
||||
// A second node given an id once held once, after the cache was built: the lookup finds the
|
||||
// cached node, which has that id; with the cache built afresh, both.
|
||||
let mut d = d;
|
||||
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
|
||||
let Some(once) = once else { continue };
|
||||
d.node(once);
|
||||
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, copy);
|
||||
}
|
||||
let found = d.nodes_in_order([once]);
|
||||
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
|
||||
d.drop_lookup_cache();
|
||||
d.node(once);
|
||||
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
|
||||
/// node it is in, appears in the tree once.
|
||||
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
|
||||
@@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() {
|
||||
assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was");
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node`
|
||||
/// for each id finds it.
|
||||
fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> {
|
||||
d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node)
|
||||
}
|
||||
|
||||
/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone
|
||||
/// each, so both start from the same cache.
|
||||
fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) {
|
||||
type Pred = fn(&Node) -> bool;
|
||||
let preds: [(&str, Pred); 5] = [
|
||||
("group", |n| matches!(n.kind, NodeKind::Group { .. })),
|
||||
("layer", |n| n.is_layer()),
|
||||
("any", |_| true),
|
||||
("none", |_| false),
|
||||
("id divisible by 3", |n| n.id.0 % 3 == 0),
|
||||
];
|
||||
for (name, pred) in preds {
|
||||
let (a, b) = (d.clone(), d.clone());
|
||||
let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect();
|
||||
let mut find = b.nearest_finder();
|
||||
let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect();
|
||||
assert_eq!(got, want, "{what}: {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_finder_matches_the_ancestry_walk() {
|
||||
for seed in 1..30 {
|
||||
let (mut d, ids) = tree(seed);
|
||||
nearest_agrees(&d, &ids, "no cache");
|
||||
d.node(ids[0]);
|
||||
nearest_agrees(&d, &ids, "cached");
|
||||
// Every path in the first layer shifts: the cache is stale there.
|
||||
let extra = d.alloc_id();
|
||||
let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, leaf);
|
||||
}
|
||||
nearest_agrees(&d, &ids, "a stale cache");
|
||||
// A group with the id of a node in the last layer, earlier in tree order than it, put in
|
||||
// after the cache was built.
|
||||
d.drop_lookup_cache();
|
||||
d.node(ids[0]);
|
||||
let last = d.layers.len() - 1;
|
||||
let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id);
|
||||
if let Some(dup) = dup
|
||||
&& let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut()
|
||||
{
|
||||
ch.insert(0, Arc::new(Node::group(dup, vec![])));
|
||||
}
|
||||
nearest_agrees(&d, &ids, "a duplicate put in after the cache was built");
|
||||
d.drop_lookup_cache();
|
||||
nearest_agrees(&d, &ids, "a duplicate, cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// An id on the path that an earlier node of another kind also has: the earlier node is the one
|
||||
/// tested, as `node` gives it.
|
||||
#[test]
|
||||
fn nearest_finder_tests_the_first_node_with_a_repeated_id() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()));
|
||||
d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap();
|
||||
d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
|
||||
// A group that has the path's id, after the path in tree order.
|
||||
d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap();
|
||||
let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. });
|
||||
for cached in [false, true] {
|
||||
d.drop_lookup_cache();
|
||||
if cached {
|
||||
d.node(layer);
|
||||
}
|
||||
let mut find = d.nearest_finder();
|
||||
assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}");
|
||||
assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path");
|
||||
assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the cache built, finding the nearest group of every object of a large tree looks no id up
|
||||
/// and walks the tree no time.
|
||||
#[test]
|
||||
fn nearest_finder_reads_one_path_per_object() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut leaves = vec![];
|
||||
for g in 0..2_000 {
|
||||
let kids: Vec<Arc<Node>> = (0..3)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
leaves.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let gid = d.alloc_id();
|
||||
d.insert(Some(layer), g, Node::group(gid, kids)).unwrap();
|
||||
}
|
||||
d.drop_lookup_cache();
|
||||
d.node(layer);
|
||||
let (lookups, walks) = (path_lookups(), tree_walks());
|
||||
let mut find = d.nearest_finder();
|
||||
let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count();
|
||||
assert_eq!(found, leaves.len());
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
@@ -79,11 +79,74 @@ fn odd_text_reads_as_nothing_without_panicking() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing
|
||||
/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing.
|
||||
#[test]
|
||||
fn a_very_long_expression_reads_as_nothing() {
|
||||
let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1));
|
||||
assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0)));
|
||||
// Long text with no signs still reads.
|
||||
assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0));
|
||||
for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] {
|
||||
assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len());
|
||||
assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x`
|
||||
/// right after a `p` stays the `px` unit.
|
||||
#[test]
|
||||
fn x_is_a_multiplication_sign() {
|
||||
let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54);
|
||||
for (u, s, want) in [
|
||||
(Unit::Points, "10x2", 20.0),
|
||||
(Unit::Points, "10 x 2", 20.0),
|
||||
(Unit::Points, "10X2", 20.0),
|
||||
(Unit::Points, "10×2", 20.0),
|
||||
(Unit::Points, "10x-2", -20.0),
|
||||
(Unit::Points, "10/2x5", 25.0),
|
||||
(Unit::Points, "1+2x3", 7.0),
|
||||
(Unit::Millimeters, "2x3 mm", 6.0 * mm),
|
||||
(Unit::Points, "2x3mm", 6.0 * mm),
|
||||
(Unit::Points, "3mm x 2", 6.0 * mm),
|
||||
(Unit::Centimeters, "3cmx50%", 1.5 * cm),
|
||||
(Unit::Points, "2p x 2", 48.0),
|
||||
(Unit::Points, "10px", 10.0),
|
||||
(Unit::Points, "2px x 3", 6.0),
|
||||
(Unit::Points, "2pxx3", 6.0),
|
||||
(Unit::Millimeters, "4x3 px", 12.0),
|
||||
// Only a lowercase x after a p is the px suffix.
|
||||
(Unit::Points, "2pX3", 72.0),
|
||||
(Unit::Points, "2p×3", 72.0),
|
||||
// Text that used to be refused now reads as a product.
|
||||
(Unit::Points, "8.5x11 in", 93.5 * 72.0),
|
||||
(Unit::Points, "0x10", 0.0),
|
||||
] {
|
||||
let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`"));
|
||||
assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}");
|
||||
}
|
||||
for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
assert_eq!(crate::parse_number("45x2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0));
|
||||
assert_eq!(crate::parse_number("45×2"), Some(90.0));
|
||||
assert_eq!(crate::parse_number("90x-1"), Some(-90.0));
|
||||
assert_eq!(crate::parse_number("x"), None);
|
||||
// Each sign counts toward the 128-sign limit as a `*` would.
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None);
|
||||
assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None);
|
||||
assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7);
|
||||
assert_eq!(crate::arithmetic_signs("2px x 3"), 1);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
#[test]
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") {
|
||||
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") {
|
||||
for u in Unit::ALL {
|
||||
if let Some(v) = u.parse(&s) {
|
||||
prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}");
|
||||
|
||||
+14
-7
@@ -18,23 +18,24 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, 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, CharClass, CompositeFont, CompositePart,
|
||||
CompositeParts,
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
};
|
||||
pub use runs::PATH_LEAD_MAX;
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
|
||||
pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
TabStop,
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
|
||||
TabAlign, TabStop,
|
||||
};
|
||||
pub use wrap::{resolve_wrap, wrap_work};
|
||||
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
@@ -66,6 +67,12 @@ pub struct TextObject {
|
||||
/// it on a frame that leaves its thread and on a copy. Not saved.
|
||||
#[serde(skip)]
|
||||
pub first_para_continues: bool,
|
||||
/// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the
|
||||
/// last character of that paragraph in the frames before that a repeat mark could stand for
|
||||
/// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout
|
||||
/// reads it only while `first_para_continues` is on. Not saved.
|
||||
#[serde(skip)]
|
||||
pub first_para_lead: Option<char>,
|
||||
/// Area Type Options (area type only).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub area: AreaOptions,
|
||||
|
||||
@@ -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")]
|
||||
@@ -298,6 +312,15 @@ impl GlyphForm {
|
||||
GlyphForm::QuarterWidth => b"qwid",
|
||||
})
|
||||
}
|
||||
|
||||
/// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may
|
||||
/// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and
|
||||
/// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied
|
||||
/// with them.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
|
||||
pub fn is_width(self) -> bool {
|
||||
matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
@@ -544,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;
|
||||
|
||||
@@ -675,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,
|
||||
@@ -698,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 };
|
||||
@@ -714,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 =
|
||||
@@ -785,6 +818,15 @@ impl CharStyle {
|
||||
self.position = self.position.in_range();
|
||||
self.small_caps = self.small_caps.map(small_caps_in_range);
|
||||
}
|
||||
/// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default
|
||||
/// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would
|
||||
/// otherwise keep drawing its own glyph; the default form keeps it.
|
||||
pub fn set_glyph_form(&mut self, form: GlyphForm) {
|
||||
self.glyph_form = form;
|
||||
if form != GlyphForm::Default {
|
||||
self.glyph_alternate = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
|
||||
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
|
||||
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
|
||||
//! family; the layout sets each character in its class's font.
|
||||
//! of their own, sized, raised and scaled against it). Custom character sets give characters the
|
||||
//! user picks a font of their own too, ahead of their class; of two sets that list a character,
|
||||
//! the later one sets it. Type set in a composite font names it as its family; the layout sets each
|
||||
//! character in its set's or its class's font.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's
|
||||
//! own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -179,12 +184,76 @@ impl CompositeParts {
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom character set of a composite font: characters chosen by the user, set in a part of
|
||||
/// their own instead of their class's part.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CustomCharSet {
|
||||
/// The set's name, unique in its composite font in any case.
|
||||
pub name: String,
|
||||
/// The set's characters, each once, in the order they were added.
|
||||
#[serde(default)]
|
||||
pub characters: String,
|
||||
/// The font, style, size, baseline and scales its characters take.
|
||||
#[serde(flatten)]
|
||||
pub part: CompositePart,
|
||||
}
|
||||
|
||||
impl CustomCharSet {
|
||||
/// An empty set named `name`, its characters set in `part`.
|
||||
pub fn new(name: impl Into<String>, part: CompositePart) -> Self {
|
||||
Self { name: name.into(), characters: String::new(), part }
|
||||
}
|
||||
|
||||
/// Whether `c` can be in a custom character set: not a control character, and in the Basic
|
||||
/// Multilingual Plane (U+0000 to U+FFFF).
|
||||
pub fn takes(c: char) -> bool {
|
||||
!c.is_control() && (c as u32) <= 0xFFFF
|
||||
}
|
||||
|
||||
/// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x`
|
||||
/// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses.
|
||||
pub fn char_from_code(code: &str) -> Option<char> {
|
||||
let code = code.trim();
|
||||
let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code);
|
||||
if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a composite font sets a character: the part of one of its six classes, or the part of
|
||||
/// one of its custom character sets (an index into [`CompositeFont::custom`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum CompositeClass {
|
||||
Fixed(CharClass),
|
||||
Custom(usize),
|
||||
}
|
||||
|
||||
/// The custom character set each character of a composite font's sets falls in
|
||||
/// ([`CompositeFont::classes`]): the last set that lists it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CompositeClasses {
|
||||
custom: std::collections::HashMap<char, usize>,
|
||||
}
|
||||
|
||||
impl CompositeClasses {
|
||||
/// Where the composite font sets `c`: the last custom set that lists it, else its class.
|
||||
pub fn of(&self, c: char) -> CompositeClass {
|
||||
self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i))
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
|
||||
/// that type set in it names.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CompositeFont {
|
||||
pub name: String,
|
||||
pub parts: CompositeParts,
|
||||
/// Custom character sets, checked before the classes. A character two sets list is set in the
|
||||
/// later set's part.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub custom: Vec<CustomCharSet>,
|
||||
}
|
||||
|
||||
/// The size a part can take, in percent of the type's size.
|
||||
@@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
|
||||
pub const COMPOSITE_NAME_MAX: usize = 255;
|
||||
/// The most composite fonts a document or a file keeps.
|
||||
pub const COMPOSITE_FONTS_MAX: usize = 256;
|
||||
/// The most custom character sets a composite font keeps.
|
||||
pub const CUSTOM_SETS_MAX: usize = 64;
|
||||
/// The most characters a custom character set keeps.
|
||||
pub const CUSTOM_CHARS_MAX: usize = 8192;
|
||||
|
||||
impl CompositeFont {
|
||||
/// A composite font named `name` setting every class in `font` and `style`.
|
||||
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() }
|
||||
}
|
||||
|
||||
/// The part that sets the characters of `class`, `None` for a custom set the font doesn't have.
|
||||
pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> {
|
||||
match class {
|
||||
CompositeClass::Fixed(c) => Some(self.parts.get(c)),
|
||||
CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where this font sets character `c`: the last custom set that lists it, else its class. For
|
||||
/// many characters, [`Self::classes`] looks each up faster.
|
||||
pub fn class_of(&self, c: char) -> CompositeClass {
|
||||
self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom)
|
||||
}
|
||||
|
||||
/// The custom set each character of this font's sets falls in, to look up many characters.
|
||||
pub fn classes(&self) -> CompositeClasses {
|
||||
let mut custom = std::collections::HashMap::new();
|
||||
for (i, s) in self.custom.iter().enumerate() {
|
||||
for c in s.characters.chars() {
|
||||
custom.insert(c, i);
|
||||
}
|
||||
}
|
||||
CompositeClasses { custom }
|
||||
}
|
||||
|
||||
/// Do `a` and `b` name the same composite font: equal in any case?
|
||||
@@ -223,36 +321,50 @@ impl CompositeFont {
|
||||
}
|
||||
|
||||
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
|
||||
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
|
||||
/// that has none.
|
||||
/// part without a font, a value out of its range, a scale or Scale at Center on a class that
|
||||
/// has none, or a custom character set [`Self::check_custom`] refuses.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!("`{}` can't name a composite font", self.name));
|
||||
}
|
||||
for class in CharClass::ALL {
|
||||
let p = self.parts.get(class);
|
||||
let k = class.key();
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?;
|
||||
}
|
||||
self.check_custom()
|
||||
}
|
||||
|
||||
/// Why this font's custom character sets can't be used, if they can't: more than
|
||||
/// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a
|
||||
/// character [`CustomCharSet::takes`] refuses or a set lists twice, more than
|
||||
/// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's
|
||||
/// characters can be scaled across and up; only kana are scaled at the center.
|
||||
pub fn check_custom(&self) -> Result<(), String> {
|
||||
if self.custom.len() > CUSTOM_SETS_MAX {
|
||||
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for s in &self.custom {
|
||||
let name = &s.name;
|
||||
if Self::clean_name(name).as_deref() != Some(name.as_str()) {
|
||||
return Err(format!("`{name}` can't name a character set"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
if !names.insert(name.to_lowercase()) {
|
||||
return Err(format!("two character sets are named `{name}`"));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (n, c) in s.characters.chars().enumerate() {
|
||||
if n == CUSTOM_CHARS_MAX {
|
||||
return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"));
|
||||
}
|
||||
if v != 100.0 && !class.scales() {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
let code = c as u32;
|
||||
if !CustomCharSet::takes(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF"));
|
||||
}
|
||||
if !seen.insert(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is listed twice"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && class != CharClass::Kana {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
check_part(&s.part, name, true, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -264,9 +376,41 @@ impl CompositeFont {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
let mut kept: Vec<CompositeFont> =
|
||||
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
|
||||
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
|
||||
kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase())));
|
||||
(kept.len() != fonts.len()).then_some(kept)
|
||||
}
|
||||
|
||||
/// The fonts of the parts, each class's then each custom set's.
|
||||
pub fn part_fonts(&self) -> impl Iterator<Item = &str> {
|
||||
CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out
|
||||
/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false.
|
||||
fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> {
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
}
|
||||
if v != 100.0 && !scales {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && !center {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -341,4 +485,81 @@ mod tests {
|
||||
spaced.name = " Mixed".into();
|
||||
assert!(spaced.check().is_err());
|
||||
}
|
||||
|
||||
/// A character a custom set lists falls in that set ahead of its class, the later of two sets
|
||||
/// that list it wins, and the quick lookup agrees with the one-character one.
|
||||
#[test]
|
||||
fn custom_sets_take_their_characters_before_the_classes() {
|
||||
let mut f = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold"));
|
||||
a.characters = "※A".into();
|
||||
let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic"));
|
||||
b.characters = "AB".into();
|
||||
f.custom = vec![a, b];
|
||||
let classes = f.classes();
|
||||
for (c, want) in [
|
||||
('※', CompositeClass::Custom(0)),
|
||||
('A', CompositeClass::Custom(1)),
|
||||
('B', CompositeClass::Custom(1)),
|
||||
('C', CompositeClass::Fixed(CharClass::Roman)),
|
||||
('漢', CompositeClass::Fixed(CharClass::Kanji)),
|
||||
] {
|
||||
assert_eq!(f.class_of(c), want, "{c:?}");
|
||||
assert_eq!(classes.of(c), want, "{c:?}");
|
||||
}
|
||||
assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold"));
|
||||
assert_eq!(f.part(CompositeClass::Custom(2)), None);
|
||||
assert_eq!(f.check(), Ok(()));
|
||||
// Read and written with the part's fields beside the set's name and characters.
|
||||
let json = serde_json::to_value(&f).unwrap();
|
||||
assert_eq!(json["custom"][1]["characters"], "AB");
|
||||
assert_eq!(json["custom"][1]["style"], "Italic");
|
||||
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
|
||||
// A font without sets is written as before.
|
||||
assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none());
|
||||
}
|
||||
|
||||
/// Set names, characters and limits are checked; sets scale like Roman letters.
|
||||
#[test]
|
||||
fn custom_sets_check_their_names_and_characters() {
|
||||
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| {
|
||||
let mut f = ok.clone();
|
||||
for (name, chars) in sets {
|
||||
let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular"));
|
||||
s.characters = chars.into();
|
||||
edit(&mut s.part);
|
||||
f.custom.push(s);
|
||||
}
|
||||
f.check()
|
||||
};
|
||||
let none = |_: &mut CompositePart| {};
|
||||
assert_eq!(with(vec![("Empty", "")], none), Ok(()));
|
||||
assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(()));
|
||||
assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err());
|
||||
assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err());
|
||||
assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets"));
|
||||
assert!(with(vec![(" Pad", "A")], none).is_err());
|
||||
assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice"));
|
||||
assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009"));
|
||||
assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B"));
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect();
|
||||
let mut f = ok.clone();
|
||||
f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") });
|
||||
assert!(f.check().unwrap_err().contains("at most"));
|
||||
let mut f = ok.clone();
|
||||
f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect();
|
||||
assert!(f.check().is_err());
|
||||
}
|
||||
|
||||
/// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane.
|
||||
#[test]
|
||||
fn custom_set_codes_name_characters() {
|
||||
assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ'));
|
||||
assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※'));
|
||||
assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A'));
|
||||
for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] {
|
||||
assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,11 @@ impl TextObject {
|
||||
/// Character attributes as presented by controls (stored runs stay local for layout
|
||||
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
|
||||
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
|
||||
let scale = self.style_scale()?;
|
||||
Self::scaled_char_style(style, self.style_scale()?)
|
||||
}
|
||||
|
||||
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
|
||||
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
|
||||
let mut style = style.clone();
|
||||
style.size *= scale.points;
|
||||
style.leading = style.leading.map(|v| v * scale.points);
|
||||
@@ -57,19 +61,27 @@ impl TextObject {
|
||||
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
|
||||
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
|
||||
/// transform).
|
||||
///
|
||||
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
|
||||
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
|
||||
/// non-uniform scale of the path would move, and a uniform one keeps.
|
||||
pub fn scale_text_attributes(&mut self) -> bool {
|
||||
let Some(scale) = self.style_scale() else { return false };
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
let Some(mut scale) = self.style_scale() else { return false };
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
if matches!(self.kind, TextKind::OnPath { .. }) {
|
||||
scale.horizontal = 1.0;
|
||||
sx = sy;
|
||||
}
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let mut baked = Vec::with_capacity(self.runs.len());
|
||||
for run in &self.runs {
|
||||
let Some(eff) = self.effective_char_style(&run.style) else { return false };
|
||||
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
|
||||
baked.push(eff);
|
||||
}
|
||||
for (run, style) in self.runs.iter_mut().zip(baked) {
|
||||
@@ -78,6 +90,14 @@ impl TextObject {
|
||||
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
|
||||
self.scale_char_strokes(1.0 / sy);
|
||||
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
|
||||
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
|
||||
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
|
||||
let grow = Affine::scale_non_uniform(sx, sy);
|
||||
match &mut self.kind {
|
||||
TextKind::Area { frame } => frame.transform(grow),
|
||||
TextKind::OnPath { path, .. } => path.transform(grow),
|
||||
TextKind::Point => {}
|
||||
}
|
||||
self.cached_bounds = None;
|
||||
self.cached_baselines.clear();
|
||||
self.cached_ink = None;
|
||||
@@ -94,6 +114,7 @@ impl TextObject {
|
||||
para: ParaStyle::default(),
|
||||
paras: Vec::new(),
|
||||
first_para_continues: false,
|
||||
first_para_lead: None,
|
||||
area: AreaOptions::default(),
|
||||
path_effect: PathEffect::default(),
|
||||
path_align: PathAlign::default(),
|
||||
@@ -283,17 +304,40 @@ impl TextObject {
|
||||
/// Update the paragraph styles for replacing bytes `start..end` of the current plain text by
|
||||
/// `insert` (call before changing the runs). The paragraph the range starts in keeps its
|
||||
/// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that
|
||||
/// style too (Return continues the paragraph it splits); later paragraphs keep theirs.
|
||||
/// style too (Return continues the paragraph it splits), without the number its list gives it
|
||||
/// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new
|
||||
/// paragraphs is made at the start of a paragraph and some of that paragraph's text stays
|
||||
/// after it, that number moves with the text to the last paragraph the insertion starts.
|
||||
pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) {
|
||||
if self.paras.is_empty() {
|
||||
let added = insert.bytes().filter(|&b| b == b'\n').count();
|
||||
let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some());
|
||||
// With one style for every paragraph, the new paragraphs take it as it is unless its list
|
||||
// gives the paragraph a number.
|
||||
if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) {
|
||||
return;
|
||||
}
|
||||
let r = self.paragraphs_in(start, end);
|
||||
let v = self.paragraph_styles();
|
||||
let Some(keep) = v.get(r.start).cloned() else { return };
|
||||
let added = insert.bytes().filter(|&b| b == b'\n').count();
|
||||
let Some(mut keep) = v.get(r.start).cloned() else { return };
|
||||
let given = keep.list.and_then(|l| l.start);
|
||||
if let Some(l) = keep.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
let mut out: Vec<ParaStyle> = v.iter().take(r.start + 1).cloned().collect();
|
||||
out.extend(std::iter::repeat_n(keep, added));
|
||||
let text = self.plain_text();
|
||||
let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len()));
|
||||
let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n'));
|
||||
// The paragraph's text after the replaced bytes, which the last new paragraph then holds.
|
||||
let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n');
|
||||
if given.is_some() && added > 0 && at_para_start && text_kept {
|
||||
if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) {
|
||||
l.start = None;
|
||||
}
|
||||
if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) {
|
||||
l.start = given;
|
||||
}
|
||||
}
|
||||
out.extend(v.iter().skip(r.end).cloned());
|
||||
self.paras = out;
|
||||
if let Some(first) = self.paras.first() {
|
||||
@@ -352,7 +396,10 @@ impl TextObject {
|
||||
}
|
||||
/// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its
|
||||
/// centre bracket dragged across the path): the path runs the other way and the brackets swap
|
||||
/// ends, so the type keeps its stretch of the path. False, changing nothing, for other type.
|
||||
/// ends, so the type keeps its stretch of the path. Type that starts before an open path's start
|
||||
/// ([`TextKind::path_text_start`]) starts at its start bracket after the flip: the part of its
|
||||
/// span before the path's start would come after the path's end. False, changing nothing, for
|
||||
/// other type.
|
||||
pub fn flip_on_path(&mut self) -> bool {
|
||||
let Some((s, e)) = self.kind.path_span() else { return false };
|
||||
let TextKind::OnPath { path, start, end } = &mut self.kind else { return false };
|
||||
@@ -508,6 +555,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();
|
||||
@@ -534,6 +583,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 {
|
||||
|
||||
Loaded 100 of 1428 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user