Merge main into train/carry10603

This commit is contained in:
dotCooCoo
2026-12-05 07:21:23 -08:00
583 changed files with 59286 additions and 3928 deletions
+2 -1
View File
@@ -67,7 +67,8 @@ jobs:
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
# its shard builds), and `cache warm` puts their files into the one entry it saves.
warm-split: true
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# The dependency cache also keeps the compiled workspace crates and their library and binary
# test executables (not the integration tests' executables), so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
# cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores
+8
View File
@@ -83,11 +83,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/cursors/cursor-mark-ring.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-mark-star.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-move.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-not-allowed.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-convert.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-curvature.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-pen-new.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-reshape-segment.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-resize-h.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-resize-nesw.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-resize-nwse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-resize-v.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/cursors/cursor-type-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface, not product iconography or artwork |
@@ -248,6 +255,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-new-item.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-new-sublayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: a layer row with a new-item square nested under it | MIT OR Apache-2.0 | |
| `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | |
| `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-para-bullets.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three dots, each before a line | MIT OR Apache-2.0 | |
Generated
+230 -116
View File
File diff suppressed because it is too large Load Diff
+58 -51
View File
@@ -10,53 +10,57 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# Language packs: the Craft apps' shared font store installs them (#4936).
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] }
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["pcraft-pixels"] }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# DWG to DXF bytes, in a child process on desktop builds (acadrust 0.6.6, MPL-2.0, unmodified).
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# The metallic-roughness BRDF and environment light the 3D effects' Roughness and Metallic shade with.
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-pbr = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# The CPU rasterizer that draws a 3D effect's Render Settings › Rendered image: depth-buffered triangles, shadow maps.
craft-raster3d = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -196,22 +200,25 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da" }
# skrifa 0.44 (epaint, glifo, usvg) with the automatic hinter's long blue-zone exit (craft-libs vendor/skrifa).
# It stays at this rev until craft-libs#5222 merges.
skrifa = { git = "https://github.com/storytold/craft-libs", rev = "37d0532f42eb3421769c8a454e3e25a20fbcff97" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+6
View File
@@ -35,6 +35,12 @@ based in part on the work of the Independent JPEG Group.
WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is
under the Apache License 2.0 with the LLVM exception.
DWG drawings are read by the acadrust crate 0.6.6 (https://crates.io/crates/acadrust/0.6.6), through
craft-dwg from https://github.com/storytold/craft-libs. acadrust is used unmodified under the Mozilla
Public License 2.0; its source is available at that address. Its license text and its third-party
notices (code adapted from ACadSharp, Copyright (c) 2021 Albert Domenech, MIT License) are in
licenses/acadrust-0.6.6/.
The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification
coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach
Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part
+2
View File
@@ -316,6 +316,8 @@ RISC-V (riscv64) packages are `vectorcraft-<ver>-linux-riscv64.deb`,
### FreeBSD
Prebuilt FreeBSD release archives target FreeBSD 15.1 or newer; FreeBSD 14.x is not supported by these builds.
| Build | File |
|---|---|
| x86_64 | `vectorcraft-<ver>-freebsd-x86_64.tar.gz` |
+5 -1
View File
@@ -124,7 +124,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged.
- 2026-12-04: Raster Settings OK edits the objects selected when the dialog opened. It keeps the dialog open with the reason if its document is not active, was reverted or had an Undo, a Redo or a canceled edit that put back an earlier state, if a target was changed, deleted, locked or hidden, if another edit is in progress, or if the change is refused. Headline numbers unchanged.
- 2026-12-04: Paste from CAD apps: on Windows, Paste reads the enhanced metafile CAD and office apps copy as vector art, and a `.dxf`, `.dwg` or HP-GL plot file copied in a file manager pastes as its drawing through the new command `clipboard.importCad` (#10819). Headline numbers unchanged.
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged.
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
@@ -271,6 +274,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
| 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). |
+5
View File
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
vectorcraft-text = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
craft = { workspace = true, features = ["automation-agents"] }
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
@@ -47,11 +49,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
[dev-dependencies]
tempfile = "3"
vectorcraft-testkit = { workspace = true }
# DWG files for the `info` test, written from DXF by craft-dwg.
craft-dwg = { workspace = true }
serde_json = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"apps/vectorcraft/src/agent_settings.rs",
"apps/vectorcraft/src/mac_fonts.rs",
"apps/vectorcraft/src/prefs_dir.rs",
"apps/vectorcraft/src/profile.rs",
+74 -14
View File
@@ -2,7 +2,7 @@
//!
//! ```text
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
@@ -39,6 +39,10 @@ macro_rules! out {
}};
}
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
/// closed-app choice and the agent folders the app saved.
#[path = "../../vectorcraft/src/agent_settings.rs"]
mod agent_settings;
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
#[cfg(target_os = "macos")]
#[path = "../../vectorcraft/src/mac_fonts.rs"]
@@ -56,9 +60,11 @@ mod system_fonts;
#[path = "../../vectorcraft/src/windows_cores.rs"]
mod windows_cores;
use craft::automation::agents::WhenAppClosed;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
/// ripgrep does; any other write error is reported.
@@ -79,9 +85,18 @@ USAGE:
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
does not take --connect.
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
file the window publishes in the settings folder: no port or token to configure, and an app
opened after the session started is found too. Otherwise the call runs in a session without
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
agent_folders tool names them. --headless always runs without a window.
--connect ADDR (deprecated, removed in a later release) drives an app started with
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
--automation-read-root / --automation-write-root confine the files the agent's commands read
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
DIR, links followed; each may be given more than once, a path inside any of its folders being
@@ -181,8 +196,8 @@ USAGE:
/// The usage text plus the formats `document.open` reads and `document.export` writes.
fn usage() -> String {
use vectorcraft_engine::cmd::fileio::{OPEN_EXTS, export_extensions};
format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", OPEN_EXTS.join(", ."), export_extensions().join(", ."))
use vectorcraft_engine::cmd::fileio::{export_extensions, open_exts};
format!("{USAGE}\nReadable formats: .{}\nWritable formats: .{}\n", open_exts().join(", ."), export_extensions().join(", ."))
}
/// Does a subcommand's `args` ask for the usage? `--help` or `-h` counts where an option goes, not as
@@ -209,6 +224,12 @@ fn help() -> Result<(), String> {
}
fn main() -> ExitCode {
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits.
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
std::process::exit(code);
}
// DWG drawings open through that copy, so a damaged file can't end this process.
vectorcraft_engine::dwg::use_own_worker();
// Before the first render: the cores the process may run on.
#[cfg(windows)]
windows_cores::install();
@@ -280,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless {
h
}
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
/// the user's stores, or confined to the agent folders without them.
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
cfg.when_closed = when_closed;
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
cfg.headless = Box::new(|roots| match roots {
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
None => with_stores(Headless::with_document()),
});
cfg
}
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
if allow {
@@ -288,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
h
}
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
/// plug-ins, so `--connect` is refused and the default does not connect.
/// The stderr line `mcp --connect` prints: the flag works for one more release.
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
/// switch), found through its connection file on every tool call, otherwise a headless session
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
return help();
}
let mut connect: Option<String> = None;
let mut headless = false;
let mut when_closed: Option<String> = None;
let mut allow_grants = false;
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
let (flag, inline) = match a.split_once('=') {
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
_ => (a.as_str(), None),
};
match flag {
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
"--headless" => headless = true,
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
"--allow-plugin-grants" => allow_grants = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
@@ -328,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if safe_mode && connect.is_some() {
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
}
let when_closed = match when_closed.as_deref() {
None => None,
Some(choice) => {
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
}
Some(parsed)
}
};
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
let roots = AutomationRoots::new(&read, &write)?;
@@ -343,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
} else if headless || safe_mode || allow_grants {
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
} else if let Some(addr) = connect {
eprintln!("{CONNECT_DEPRECATED}");
// Explicit address: fail loudly if the app isn't there.
let token = vectorcraft_mcp::control_token()?;
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
} else {
// No token or no app listening: the headless session answers instead.
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
Some(r) => Box::new(r),
match prefs_dir::prefs_dir() {
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
// refuses rather than answering from a session the agent didn't ask for.
None if when_closed == Some(WhenAppClosed::Error) => {
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
}
None => Box::new(with_stores(Headless::with_document())),
}
};
@@ -616,6 +674,8 @@ fn thumbnail(args: &[String]) -> Result<(), String> {
}
}
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
// A DWG worker ends by then too, so the exit below leaves no conversion running.
vectorcraft_engine::dwg::use_own_worker_for(THUMBNAIL_TIME);
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
std::thread::spawn(|| {
std::thread::sleep(THUMBNAIL_TIME);
+17
View File
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
}
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
/// release but says it is deprecated before it connects.
#[test]
fn mcp_when_closed_and_the_deprecated_connect() {
let fails = |args: &[&str], why: &str| {
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
err.into_owned()
};
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
}
+67
View File
@@ -378,3 +378,70 @@ fn convert_and_run_write_ait_templates() {
assert!(!one.status.success());
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
}
/// A DWG drawing opens through a worker copy of the program, so a damaged one ends in an error from
/// `info`, never in a crash. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD on
/// aarch64.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn info_reads_a_dwg_and_a_damaged_one_is_an_error_not_a_crash() {
let dxf = tmp("plan.dxf");
make(&dxf, 120, 80);
craft_dwg::allow_in_process();
let dwg = craft_dwg::dxf_to_dwg_as(&std::fs::read(&dxf).unwrap(), "AC1018").unwrap();
let good = tmp("plan.dwg");
std::fs::write(&good, &dwg).unwrap();
// The DWG comes in as the DXF it was written from.
let (v, from) = (info(&good), info(&dxf));
assert!(v["kinds"]["Path"].as_u64().is_some_and(|n| n > 0), "{v}");
assert_eq!((&v["kinds"], &v["artboards"][0]["rect"]), (&from["kinds"], &from["artboards"][0]["rect"]), "{v}\n{from}");
let n = dwg.len();
let mut damaged = vec![dwg[..n / 3].to_vec(), dwg[..2 * n / 3].to_vec(), dwg[..16].to_vec()];
let mut overwritten = dwg.clone();
overwritten[n / 2..(n / 2 + 64).min(n)].fill(0xFF);
damaged.push(overwritten);
let mut flipped = dwg.clone();
flipped.iter_mut().skip(32).step_by(97).for_each(|b| *b ^= 0xA5);
damaged.push(flipped);
for (i, bytes) in damaged.iter().enumerate() {
let path = tmp(&format!("damaged-{i}.dwg"));
std::fs::write(&path, bytes).unwrap();
let out = Command::new(crate::bin()).args(["info", &path]).output().unwrap();
// A process ended by a signal has no exit code.
assert!(out.status.code().is_some(), "damaged file {i}: {:?}", out.status);
// The file cut to a third and the one cut to its header can't be read; the reader may
// recover the others.
if i == 0 || i == 2 {
assert!(!out.status.success(), "damaged file {i} is refused: {}", String::from_utf8_lossy(&out.stdout));
}
if !out.status.success() {
assert!(String::from_utf8_lossy(&out.stderr).contains("DWG"), "damaged file {i}: {}", String::from_utf8_lossy(&out.stderr));
}
}
}
/// A DWG worker started with a deadline (as `thumbnail` starts one) exits with code 1 once the
/// deadline passes, even while it still waits for its drawing, and at once when it has already
/// passed, so `thumbnail`'s exit leaves no conversion running.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn a_dwg_worker_with_a_time_limit_exits_when_the_time_is_up() {
let now = std::time::SystemTime::now();
for until in [now + std::time::Duration::from_secs(1), now - std::time::Duration::from_secs(1)] {
let millis = until.duration_since(std::time::UNIX_EPOCH).unwrap().as_millis().to_string();
let mut worker = Command::new(crate::bin())
.args(["--dwg-worker", "--dwg-worker-until", &millis])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
// Its input stays open, so the worker never gets the whole request.
let input = worker.stdin.take();
let out = worker.wait_with_output().unwrap();
drop(input);
assert_eq!(out.status.code(), Some(1), "{:?}", out.status);
// It stops without answering, so no partial drawing reaches the caller.
assert!(out.stdout.is_empty(), "{} bytes written", out.stdout.len());
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ egui_extras = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# 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 = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4f3e34d0dda2a6862f5ba5fc4cfe3e323602a2da", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+2 -1
View File
@@ -143,7 +143,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
let pen = host.pointers.borrow().pen();
let spec = InstallSpec::new(ShellInfo::current(), Arc::new(SystemWindows)).pen(pen);
// The interface faces the page serves are fetched by the stack as text needs them.
let fonts = vectorcraft_ui_egui::ui_fonts().fetcher(Arc::new(crate::fonts::BrowserFetcher));
let language = taken.borrow().as_ref().map_or_else(i18n::system_lang, VectorcraftApp::ui_language);
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, language, Some(Arc::new(crate::fonts::BrowserFetcher)));
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
let files = {
+77
View File
@@ -0,0 +1,77 @@
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
//! and the agent folders.
use std::io::Read as _;
use std::path::Path;
use craft::automation::agents::AgentSettings;
use serde_json::Value;
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
/// "allowAgentControl"}`, the framework's `AgentSettings`.
pub const SETTINGS_FILE: &str = "agents.json";
/// The largest settings file read; the settings are a few short strings.
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
pub fn read_settings(dir: &Path) -> AgentSettings {
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
let mut text = String::new();
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
return AgentSettings::default();
}
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
let mut settings = AgentSettings::default();
for (key, value) in saved {
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
if one.contains_key(&key) {
one.insert(key, value);
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
settings = next;
}
}
}
settings
}
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
#[allow(dead_code)]
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
std::fs::write(&partial, text)?;
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
let _ = std::fs::remove_file(&partial);
})
}
#[cfg(test)]
mod tests {
use super::*;
use craft::automation::agents::WhenAppClosed;
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
#[test]
fn saved_settings_read_back_and_bad_values_reset_alone() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
let mut settings = AgentSettings::default();
settings.read_root = "/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
write_settings(dir.path(), &settings).unwrap();
assert_eq!(read_settings(dir.path()), settings);
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
let read = read_settings(dir.path());
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
assert_eq!(read.read_root, "");
}
}
+85 -6
View File
@@ -2,8 +2,10 @@
//! (`Services::clipboard`).
//!
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! Paste reads each of them and EPS, the enhanced metafile that CAD and office apps copy as
//! vector art (`CF_ENHMETAFILE`; the system makes one of a `CF_METAFILEPICT`), a bitmap as PNG,
//! else as the device-independent bitmap that screenshots and most apps copy (`CF_DIBV5`,
//! `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
@@ -19,7 +21,8 @@
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A
//! a metafile, a DXF or DWG drawing, an HP-GL plot file or a bitmap), before the clipboard's
//! other formats (the files' paths as text). A
//! file of more than 64 MiB is skipped before it is read.
use std::io::{Cursor, Read};
@@ -303,6 +306,23 @@ fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<
copy().filter(|data| data.len() <= limit)
}
/// The records of an enhanced metafile, which the Windows clipboard holds as a handle
/// (`CF_ENHMETAFILE`) whose records `GetEnhMetaFileBits` copies: `bits` called without a buffer
/// gives their size, and with a buffer copies them and gives how many bytes it copied (0 when it
/// failed). Nothing is copied when the size is 0 or more than `limit` bytes ([`copy_within`]).
#[cfg_attr(not(windows), allow(dead_code))]
fn enhmetafile_bits(mut bits: impl FnMut(Option<&mut [u8]>) -> u32, limit: usize) -> Option<Vec<u8>> {
let size = usize::try_from(bits(None)).ok();
copy_within(size, limit, || {
let mut data = vec![0; size?];
let copied = usize::try_from(bits(Some(&mut data))).ok()?;
(copied > 0 && copied <= data.len()).then(|| {
data.truncate(copied);
data
})
})
}
/// 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))]
@@ -428,10 +448,12 @@ mod win {
use std::path::PathBuf;
use windows::Win32::Graphics::Gdi::{GetEnhMetaFileBits, HENHMETAFILE};
use super::{
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG, SVG,
TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, png_flavour, read_flavor, read_image_flavor, read_later_flavor,
utf8_most, windows_formats,
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Cursor, EMF, Flavor, Flavour, LaterFlavor, MAX_BYTES, MAX_URIS, PNG,
SVG, TEXT, copied_file, copy_within, decode_png, dib_image, drop_files_within, enhmetafile_bits, png_flavour, read_flavor, read_image_flavor,
read_later_flavor, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -533,6 +555,7 @@ mod win {
|| mimes.iter().any(|m| match *m {
TEXT => raw::is_format_avail(formats::CF_UNICODETEXT),
BITMAP => DIBS.into_iter().chain(formats_of(PNG)).any(raw::is_format_avail),
EMF => raw::is_format_avail(formats::CF_ENHMETAFILE),
m => formats_of(m).any(raw::is_format_avail),
})
}
@@ -571,6 +594,19 @@ mod win {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// The enhanced metafile the clipboard holds, while it is open, as the bytes of an EMF file; at
/// most [`MAX_BYTES`] of them ([`enhmetafile_bits`]).
#[allow(unsafe_code)]
fn read_enhmetafile() -> Option<Vec<u8>> {
if !raw::is_format_avail(formats::CF_ENHMETAFILE) {
return None;
}
let emf = HENHMETAFILE(raw::get_clipboard_data(formats::CF_ENHMETAFILE).ok()?.as_ptr());
// SAFETY: `emf` is the clipboard's metafile handle, which stays valid while the clipboard is
// open; the call writes at most the length of the buffer it is given.
enhmetafile_bits(|buffer| unsafe { GetEnhMetaFileBits(emf, buffer) }, MAX_BYTES)
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
@@ -607,6 +643,7 @@ mod win {
})?;
(TEXT, text)
}
EMF => (EMF, read_enhmetafile()?),
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
@@ -3545,6 +3582,48 @@ mod tests {
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
}
/// A DXF drawing or an HP-GL plot file copied in a file manager pastes as vector art.
#[test]
fn a_copied_cad_file_pastes() {
use vectorcraft_engine::cmd::clipboard::{DXF, HPGL};
let d = dir("cad");
let (dxf, plot) = (d.path().join("plan.dxf"), d.path().join("part.plt"));
std::fs::write(&dxf, "0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n0\n0\nENDSEC\n0\nEOF\n").unwrap();
std::fs::write(&plot, "IN;SP1;PA0,0;PD1016,0;PU;").unwrap();
assert_eq!(copied_file(vec![dxf.clone()], &PASTE_ORDER).map(|f| f.mime), Some(DXF));
assert_eq!(copied_file(vec![plot.clone()], &PASTE_ORDER).map(|f| f.mime), Some(HPGL));
assert!(copied_file(vec![dxf, plot], &[BITMAP, TEXT]).is_none());
}
/// The enhanced metafile the Windows clipboard holds is copied whole, into a buffer of the size
/// it gives; one of no records or of more than the limit is not copied, and a failed copy gives
/// nothing.
#[test]
fn an_enhanced_metafile_is_copied_within_the_limit() {
let records: Vec<u8> = (0..40).collect();
let read = |records: &[u8], fails: bool, limit: usize| {
let mut copies = 0;
let got = enhmetafile_bits(
|buffer| match buffer {
None => records.len() as u32,
Some(_) if fails => 0,
Some(buffer) => {
copies += 1;
assert_eq!(buffer.len(), records.len());
buffer.copy_from_slice(records);
records.len() as u32
}
},
limit,
);
(got, copies)
};
assert_eq!(read(&records, false, 40), (Some(records.clone()), 1));
assert_eq!(read(&records, false, 39), (None, 0));
assert_eq!(read(&[], false, 40), (None, 0));
assert_eq!(read(&records, true, 40), (None, 0));
}
#[test]
fn a_crlf_left_by_the_uri_list_is_ignored() {
let d = dir("crlf");
+47 -4
View File
@@ -27,6 +27,7 @@
//! how the window's frames reach the display (`presentation`).
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod agent_settings;
mod automation_args;
#[cfg(test)]
mod build_channel;
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
}
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
/// whole run and the link stays off. A nightly and a run without preferences have no link.
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
let dir = prefs_dir::prefs_dir()?;
remove_stale_connection(&dir);
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let save_dir = dir.clone();
let save: SaveFn = Box::new(move |settings| {
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
});
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
}
/// The control channel's port, and the token's notice with the token itself.
type ControlChannel = (Option<u16>, Option<(String, String)>);
@@ -573,10 +598,17 @@ fn finish_pending_update(nightly: bool) {
}
fn main() -> std::process::ExitCode {
// A copy of this program started with `--dwg-worker` alone converts one DWG drawing and exits,
// before the launch profile, the logger or any window.
if let Some(code) = vectorcraft_engine::dwg::serve_if_asked() {
std::process::exit(code);
}
// The launch profile first: a nightly build self-isolates or uses the Launcher's profile here,
// before the update helper, the logger, fonts or any saved state, and `--version` is answered
// here too.
let Some(arguments) = prepare_launch() else { return std::process::ExitCode::SUCCESS };
// DWG drawings open through that copy, so a damaged file can't end this process.
vectorcraft_engine::dwg::use_own_worker();
let nightly = launch_profile::current().is_nightly();
#[cfg(windows)]
finish_pending_update(nightly);
@@ -767,6 +799,10 @@ fn main() -> std::process::ExitCode {
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
#[cfg(target_os = "linux")]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
// Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the
// main window does (`window_frame`, #10797).
#[cfg(all(windows, feature = "wgpu"))]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options };
#[cfg(feature = "wgpu")]
let options = {
let mut options = options;
@@ -857,8 +893,6 @@ fn main() -> std::process::ExitCode {
Some(pen) => spec.pen(pen),
None => spec,
};
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
let folders = settings.lock().get().ui.last_folders.clone();
let wake = {
let ctx = ctx.clone();
@@ -875,7 +909,6 @@ fn main() -> std::process::ExitCode {
.settings(Arc::new(settings.clone()))
.files(files.clone())
.build();
host.clone().install(ctx);
let mut session = Session::new();
// The profiles loaded before come back before the preferences name any of them.
prefs_dir::attach_profile_store(&mut session);
@@ -900,12 +933,16 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_proof_setups(&mut session);
prefs_dir::attach_script_data(&mut session);
let mut app = VectorcraftApp::new(session, services(winit_window.clone()));
load_prefs(&mut app, &settings);
let fonts = vectorcraft_ui_egui::configure_ui_fonts(ctx, app.ui_language(), None);
embed::install(ctx, spec, &fonts).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
host.clone().install(ctx);
app.host = Arc::new(host);
app.adopt_context(&cc.egui_ctx);
// A nightly is updated by the Launcher: it never checks for a stable release, which
// would install this program's own updater over the nightly build.
app.set_startup_update_check(!nightly);
load_prefs(&mut app, &settings);
safe_mode::after_start(&mut app, stopped);
// Loads started later (a preference change, the end of Safe Mode) are waited for,
// after the launch's own.
@@ -1048,6 +1085,12 @@ fn main() -> std::process::ExitCode {
}
}
}
if !nightly
&& prefs_enabled()
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
{
app = app.with_agents(agents);
}
#[cfg(target_os = "macos")]
{
open_documents::set_ui(&cc.egui_ctx);
+68 -6
View File
@@ -180,7 +180,8 @@ mod system {
let sockets = local_sockets();
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
// so its sizes come from the server.
if scheduler_is_local(named.as_deref(), &sockets, real_path) {
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
if named_scheduler_is_local(named.as_deref(), port, |s| std::path::Path::new(s).exists(), &sockets, real_path) {
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
@@ -199,7 +200,6 @@ mod system {
return papers;
}
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path);
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
use std::io::Write as _;
@@ -286,10 +286,19 @@ mod system {
}
}
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
/// `/etc/cups/client.conf`; `None` when none is named, where CUPS uses its domain socket when one exists and
/// `localhost` on `IPP_PORT` otherwise ([`named_scheduler_is_local`] resolves that case). macOS does not read `ServerName`
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
/// A server named without a port gets the one `IPP_PORT` sets, so `localhost` with `IPP_PORT=8631` is a second
/// scheduler rather than the local one.
#[cfg(not(windows))]
fn cups_server() -> Option<String> {
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
named_cups_server().map(|server| vectorcraft_ui_egui::print::server_with_ipp_port(&server, port))
}
/// The scheduler `cups_server` names, as written.
#[cfg(not(windows))]
fn named_cups_server() -> Option<String> {
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
return Some(server.trim().to_string());
}
@@ -304,8 +313,26 @@ mod system {
client_conf_server_name(&text)
})
}
/// Whether the scheduler CUPS uses runs on this machine, given the server `cups_server` names, the `IPP_PORT`
/// port, whether a path exists, the local scheduler's domain `sockets` and a socket path's real path. With no
/// server named, CUPS uses its domain socket when one exists, which is local, and otherwise `localhost` on the
/// `IPP_PORT` port, which is local only on port 631.
#[cfg(not(windows))]
pub(super) fn named_scheduler_is_local(
named: Option<&str>,
port: Option<u16>,
exists: impl Fn(&str) -> bool,
sockets: &[String],
resolve: impl Fn(&str) -> Option<String>,
) -> bool {
match named {
Some(server) => scheduler_is_local(Some(server), sockets, resolve),
None if CUPS_SOCKETS.iter().any(|s| exists(s)) => true,
None => scheduler_is_local(Some(&vectorcraft_ui_egui::print::server_with_ipp_port("localhost", port)), sockets, resolve),
}
}
/// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain
/// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix.
/// `sockets`, or `localhost`, `127.0.0.1` or `[::1]` with no port or port 631, each with an optional `/version=` suffix.
/// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder
/// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket.
#[cfg(not(windows))]
@@ -320,6 +347,10 @@ mod system {
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
} else if server.matches(':').count() == 1 {
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
} else if let Some((host, port)) = server.rsplit_once(':').filter(|(_, port)| port.starts_with(|c: char| c.is_ascii_digit())) {
// CUPS (`cupsSetServer`) reads the digits after the last `:` of an unbracketed name as its port, so `::1` is
// host `:` on port 1.
(host, Some(port))
} else {
(server, None)
};
@@ -646,7 +677,21 @@ mod turn_tests {
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local};
use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, named_scheduler_is_local, scheduler_is_local};
#[test]
fn with_no_server_named_the_implicit_scheduler_decides_locality() {
let none = |_: &str| false;
let socket = |s: &str| s == "/run/cups/cups.sock";
let real = |_: &str| None;
let own = cupsd_listen_sockets("");
assert!(!named_scheduler_is_local(None, Some(8631), none, &own, real), "localhost:8631 is a second scheduler");
assert!(named_scheduler_is_local(None, Some(631), none, &own, real));
assert!(named_scheduler_is_local(None, None, none, &own, real));
assert!(named_scheduler_is_local(None, Some(8631), socket, &own, real), "CUPS's socket is the local scheduler");
assert!(!named_scheduler_is_local(Some("print.example.com"), None, socket, &own, real));
assert!(named_scheduler_is_local(Some("localhost:631"), Some(8631), none, &own, real));
}
#[test]
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
@@ -700,7 +745,6 @@ mod client_conf_tests {
Some("LocalHost:631"),
Some("localhost:631"),
Some("127.0.0.1:631"),
Some("::1"),
Some("[::1]:631"),
Some("[::1]"),
Some("localhost/version=1.1"),
@@ -714,6 +758,7 @@ mod client_conf_tests {
"192.0.2.7",
"[2001:db8::1]:631",
"2001:db8::1",
"::1",
"localhost.example.com",
"print.example.com:631/version=1.1",
"localhost:8631",
@@ -727,6 +772,23 @@ mod client_conf_tests {
}
}
#[test]
fn a_loopback_server_on_another_ipp_port_is_not_local() {
use vectorcraft_ui_egui::print::server_with_ipp_port;
let own = cupsd_listen_sockets("");
let real = |_: &str| None;
for named in ["localhost", "127.0.0.1", "[::1]", "localhost/version=1.1"] {
assert!(!scheduler_is_local(Some(&server_with_ipp_port(named, Some(8631))), &own, real), "{named}");
assert!(scheduler_is_local(Some(&server_with_ipp_port(named, Some(631))), &own, real), "{named}");
}
// CUPS reads an unbracketed `::1` as host `:` on port 1, so it is not the local scheduler on any `IPP_PORT`.
for port in [None, Some(631), Some(8631)] {
assert!(!scheduler_is_local(Some(&server_with_ipp_port("::1", port)), &own, real), "::1 with {port:?}");
}
assert!(scheduler_is_local(Some(&server_with_ipp_port("localhost:631", Some(8631))), &own, real), "a port in the server name wins");
assert!(scheduler_is_local(Some(&server_with_ipp_port("/run/cups/cups.sock", Some(8631))), &own, real));
}
#[test]
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
+203 -16
View File
@@ -22,10 +22,20 @@
//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge
//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window
//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878).
//!
//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel)
//! are undecorated winit windows as well, and on the same systems their content was drawn offset
//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and
//! runs the same guard on each one in each of its frames.
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, PoisonError};
/// Run once per frame; a no-op once the window is borderless.
pub type WindowFrameFn = Box<dyn FnMut()>;
#[cfg(all(windows, feature = "wgpu"))]
pub use platform::Hooks;
pub use platform::service;
#[cfg(all(windows, feature = "wgpu"))]
@@ -49,6 +59,33 @@ mod platform {
Some(Box::new(move || reapply(&hwnd)))
}
/// The undecorated windows of floating panels and dialogs, which [`Hooks`] records.
static SECONDARY: std::sync::LazyLock<super::Viewports<HWND>> = std::sync::LazyLock::new(super::Viewports::default);
/// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`]
/// keeps the main window: the guard runs when eframe makes such a window and before each of its
/// frames. Set as [`eframe::NativeOptions::viewport_hooks`].
pub struct Hooks;
impl eframe::ViewportHooks for Hooks {
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
let hwnd = match window.window_handle().map(|h| h.as_raw()) {
Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()),
_ => None,
};
SECONDARY.created(viewport, window.is_decorated(), hwnd);
SECONDARY.with(viewport, reapply);
}
fn window_destroyed(&self, viewport: egui::ViewportId) {
SECONDARY.destroyed(viewport);
}
fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
SECONDARY.with(raw_input.viewport_id, reapply);
}
}
/// One pass of the per-frame guard: the styles winit put back come off again, and a parked
/// maximize stays clear of the taskbar.
fn reapply(hwnd: &HWND) {
@@ -103,7 +140,8 @@ mod platform {
let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom));
// The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its
// whole monitor, which it no longer does once trimmed.
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| {
let frame = super::frame_limit(hwnd.GetDpiForWindow());
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work, frame).or_else(|| {
super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()
}) else {
return;
@@ -152,21 +190,78 @@ mod platform {
}
}
/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about
/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being
/// dragged or snapped, and is left alone.
const FRAME: i32 = 32;
/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds
/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so
/// it is tested everywhere.
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
struct Viewports<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>);
impl<H> Default for Viewports<H> {
fn default() -> Self {
Self(Mutex::new(HashMap::new()))
}
}
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
impl<H> Viewports<H> {
/// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated
/// window other than the main one, which [`service`] keeps; otherwise any earlier record of the
/// viewport is removed, so a window made again with the system title bar is left alone.
fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option<H>) {
let mut windows = self.lock();
match handle {
Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)),
_ => windows.remove(&viewport),
};
}
/// eframe dropped `viewport`'s window.
fn destroyed(&self, viewport: egui::ViewportId) {
self.lock().remove(&viewport);
}
/// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record
/// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait
/// on the lock. It goes back only if the record is still there and empty: a window dropped or
/// made again for the viewport in the meantime wins.
fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) {
let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else {
return;
};
f(&handle);
if let Some(slot @ None) = self.lock().get_mut(&viewport) {
*slot = Some(handle);
}
}
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, Option<H>>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// How far, in physical pixels at 96 DPI (100 %), a parked maximize reaches past a monitor or
/// work-area edge at most: the resize border is about 8 px at 100 %. Past that, a maximized
/// window's rect is not parked but being dragged or snapped, and is left alone.
const FRAME_AT_96_DPI: i32 = 32;
/// [`FRAME_AT_96_DPI`] for a window at `dpi`, which the resize border grows with; never less than
/// at 96 DPI, so an unknown DPI (0) counts as 100 %.
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
fn frame_limit(dpi: u32) -> i32 {
let scaled = i64::from(FRAME_AT_96_DPI) * i64::from(dpi) / 96;
i32::try_from(scaled).unwrap_or(i32::MAX).max(FRAME_AT_96_DPI)
}
/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize
/// border it was parked with, or `None` when it already does or `rect` (`left, top, right,
/// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The
/// border is read from the edges that have no taskbar, and every edge must sit that far outside
/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the
/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested
/// everywhere.
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates;
/// `frame` is the largest border a parked maximize has ([`frame_limit`]). The border is read from
/// the edges that have no taskbar, and every edge must sit that far outside either the monitor
/// (where Windows puts a caption-less maximize) or the work area (where the guard puts it), so a
/// rect it already moved is left alone. Platform-neutral so it is tested everywhere.
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32), frame: i32) -> Option<(i32, i32, i32, i32)> {
let (l, t, r, b) = rect;
let (ml, mt, mr, mb) = monitor;
let (wl, wt, wr, wb) = work;
@@ -183,7 +278,7 @@ fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work:
]
.into_iter()
.flatten()
.filter(|n| (0..=FRAME).contains(n))
.filter(|n| (0..=frame).contains(n))
.min()?;
let parked = |monitor: Option<i32>, work: Option<i32>| monitor == Some(border) || work == Some(border);
if !parked(ml.checked_sub(l), wl.checked_sub(l))
@@ -218,9 +313,11 @@ fn covers(rect: Rect, monitor: Rect) -> bool {
}
/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the
/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden
/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie
/// outside the monitor.
/// taskbar's center, or `None` when the taskbar is not this monitor's. A shown taskbar lies wholly
/// on its monitor. An auto-hidden taskbar is parked mostly past its edge with a sliver left on the
/// monitor, so its center can lie outside the monitor; the part past the edge can lie on a
/// neighboring monitor, which a taskbar that is neither wholly on the monitor nor mostly off it
/// belongs to.
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3));
@@ -228,6 +325,12 @@ fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb {
return None;
}
let inside = tl >= ml && tt >= mt && tr <= mr && tb <= mb;
let area = |l: i64, t: i64, r: i64, b: i64| i128::from(r - l) * i128::from(b - t);
let on_monitor = area(tl.max(ml), tt.max(mt), tr.min(mr), tb.min(mb));
if !inside && on_monitor * 2 >= area(tl, tt, tr, tb) {
return None;
}
// The center and the distances are doubled, so nothing is rounded.
let (cx, cy) = (tl + tr, tt + tb);
[(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)]
@@ -260,7 +363,69 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
#[cfg(test)]
mod tests {
use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
use super::{Edge, Viewports, frame_limit, short_of_autohide_taskbars, taskbar_edge};
/// [`super::clamped_rect`] for a window at 96 DPI (100 %).
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
super::clamped_rect(rect, monitor, work, frame_limit(96))
}
fn viewport(name: &str) -> egui::ViewportId {
egui::ViewportId::from_hash_of(name)
}
/// The windows `with` reaches for each viewport, in order.
fn reached(windows: &Viewports<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> {
viewports
.iter()
.map(|&id| {
let mut seen = None;
windows.with(id, |&h| seen = Some(h));
seen
})
.collect()
}
/// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main
/// window, which `service` keeps, and windows with the system title bar are not recorded.
#[test]
fn undecorated_floating_windows_are_recorded_until_dropped() {
let windows = Viewports::default();
let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding"));
windows.created(egui::ViewportId::ROOT, false, Some(1));
windows.created(prefs, false, Some(7));
windows.created(color, false, Some(9));
windows.created(hang, true, Some(11));
assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]);
// Each frame reaches the window again.
assert_eq!(reached(&windows, &[prefs]), [Some(7)]);
windows.destroyed(prefs);
assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]);
// A window made again with the system title bar, or without a handle, is left alone.
windows.created(color, true, Some(13));
assert_eq!(reached(&windows, &[color]), [None]);
windows.created(color, false, Some(15));
windows.created(color, false, None);
assert_eq!(reached(&windows, &[color]), [None]);
}
/// A window dropped or made again while the guard runs on the old one is not brought back.
#[test]
fn a_window_dropped_or_made_again_during_the_guard_wins() {
let windows = Viewports::default();
let prefs = viewport("Preferences");
windows.created(prefs, false, Some(7));
windows.with(prefs, |_| windows.destroyed(prefs));
assert_eq!(reached(&windows, &[prefs]), [None]);
windows.created(prefs, false, Some(7));
windows.with(prefs, |_| windows.created(prefs, false, Some(8)));
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
// The guard can reach the hooks again for the same viewport without waiting on itself.
let mut inner = None;
windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h)));
assert_eq!(inner, None);
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
}
#[test]
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
@@ -310,6 +475,22 @@ mod tests {
}
}
#[test]
fn the_frame_limit_grows_with_the_monitor_dpi() {
// At 500 % (480 DPI) the resize border is about 40 px, past the limit at 100 %.
let (monitor, work) = ((0, 0, 3840, 2160), (0, 0, 3840, 2000));
let rect = (-40, -40, 3880, 2200);
assert_eq!(clamped_rect(rect, monitor, work), None, "100 %");
let Some(clamped) = super::clamped_rect(rect, monitor, work, frame_limit(480)) else {
panic!("500 %: the maximized frame is not clamped");
};
assert_eq!((clamped.0, clamped.1, clamped.2), (rect.0, rect.1, rect.2), "500 %: only the bottom edge moves");
assert_eq!(clamped.3 - work.3, monitor.1 - rect.1, "500 %: the bottom border hangs below the work area as the top one above the monitor");
assert_eq!(super::clamped_rect((-8, -8, 1928 + 40, 1088), (0, 0, 1920, 1080), (0, 0, 1920, 1046), frame_limit(96)), None, "past the limit");
assert_eq!(frame_limit(0), frame_limit(96), "an unknown DPI counts as 100 %");
assert!(frame_limit(u32::MAX) > frame_limit(480), "no overflow");
}
#[test]
fn a_maximize_without_a_reserved_taskbar_is_left_alone() {
let monitor = (0, 0, 1920, 1080);
@@ -360,6 +541,12 @@ mod tests {
assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left));
assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right));
assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor");
// With monitors stacked, the part of the upper monitor's auto-hidden taskbar parked past its
// bottom edge lies on the monitor below, which it does not belong to.
let below = (0, 1080, 1920, 2160);
assert_eq!(taskbar_edge((0, 1078, 1920, 1126), below), None, "neighbor's auto-hidden taskbar");
assert_eq!(taskbar_edge((0, 2158, 1920, 2206), below), Some(Edge::Bottom), "its own auto-hidden taskbar");
assert_eq!(taskbar_edge((0, 1080, 1920, 1128), below), Some(Edge::Top), "its own shown top taskbar");
assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow");
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M11 5h2v14h-2Z"/><path d="M5 11h14v2H5Z"/><path d="M12 1.5L15.5 5.5H8.5Z"/><path d="M12 22.5L8.5 18.5H15.5Z"/><path d="M1.5 12L5.5 8.5V15.5Z"/><path d="M22.5 12L18.5 15.5V8.5Z"/></svg>

After

Width:  |  Height:  |  Size: 289 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path fill-rule="evenodd" d="M12 4a8 8 0 1 1 0 16a8 8 0 1 1 0-16ZM12 6a6 6 0 1 0 0 12a6 6 0 1 0 0-12Z"/><path d="M6.9 15.7L15.7 6.9L17.1 8.3L8.3 17.1Z"/></svg>

After

Width:  |  Height:  |  Size: 255 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M5 11h14v2H5Z"/><path d="M1.5 12L6 8V16Z"/><path d="M22.5 12L18 16V8Z"/></svg>

After

Width:  |  Height:  |  Size: 183 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M17.3 5.3L5.3 17.3L6.7 18.7L18.7 6.7Z"/><path d="M21.5 2.5L14.5 3.5L20.5 9.5Z"/><path d="M2.5 21.5L9.5 20.5L3.5 14.5Z"/></svg>

After

Width:  |  Height:  |  Size: 231 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M6.7 5.3L18.7 17.3L17.3 18.7L5.3 6.7Z"/><path d="M2.5 2.5L9.5 3.5L3.5 9.5Z"/><path d="M21.5 21.5L14.5 20.5L20.5 14.5Z"/></svg>

After

Width:  |  Height:  |  Size: 231 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M11 5h2v14h-2Z"/><path d="M12 1.5L16 6H8Z"/><path d="M12 22.5L8 18H16Z"/></svg>

After

Width:  |  Height:  |  Size: 184 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#000"><path d="M5 11.25h14v1.5H5Z"/><path d="M4.25 8.5h1.5v7h-1.5Z"/><path d="M18.25 8.5h1.5v7h-1.5Z"/></svg>

After

Width:  |  Height:  |  Size: 199 B

+1
View File
@@ -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="butt" stroke-linejoin="miter"><rect x="3" y="3" width="18" height="4.5" stroke-width="1.25" /><path d="M6 7.5V16H10" stroke-width="1.25" /><rect x="10" y="11" width="11" height="10" stroke-width="1.25" /><path d="M15.5 13.5V18.5M13 16H18" stroke-width="1.5" /></svg>

After

Width:  |  Height:  |  Size: 419 B

+3 -1
View File
@@ -3,13 +3,14 @@ name = "vectorcraft-cad"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
description = "VectorCraft CAD interchange: DXF export through craft-dxf, DXF and DWG import, and an HP-GL/2 plot file reader and writer"
[lints]
workspace = true
[dependencies]
craft-dxf = { workspace = true }
craft-dwg = { workspace = true }
craft-plotter = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
@@ -21,6 +22,7 @@ vectorcraft-text = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
web-time = "1"
[dev-dependencies]
serde_json = { workspace = true }
+115
View File
@@ -0,0 +1,115 @@
//! Block definitions and INSERT entities for the DXF writer.
//!
//! Temporary: `craft_dxf::drawing` at the pinned craft-libs revision writes only the model and
//! paper space blocks. storytold/craft-libs#5381 adds `Block`, `Drawing::blocks` and
//! `Codes::insert`; once it merges and the pin moves past it, this module is removed and
//! `scene.rs` uses those instead. Until then [`write`] adds the user blocks to the file that
//! `Drawing::write` returns, with the same group codes #5381 writes.
use craft_dxf::drawing::{Codes, Drawing, Handle, fixed};
/// A block definition: entities written once, which INSERT entities place ([`insert`]). Its base
/// point is the origin.
#[derive(Clone, Debug)]
pub struct Block {
pub name: String,
/// The handle of its BLOCK_RECORD (from R13), which owns its entities.
pub record: Handle,
/// The handles of its BLOCK and ENDBLK records.
pub begin: Handle,
pub end: Handle,
/// The entities' group codes, written with `record` as their owner.
pub entities: String,
}
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
fn object(c: &mut Codes, kind: &str, h: Handle, owner: Handle, subclass: &str) {
c.raw(0, kind);
if c.v.handles() {
c.handle(5, h);
c.handle(330, owner);
c.raw(100, subclass);
}
}
/// An INSERT entity owned by `owner` on `layer` that places block `block` at the origin, unscaled
/// and unrotated. It has no color of its own (ByLayer).
pub fn insert(c: &mut Codes, h: Handle, owner: Handle, layer: &str, block: &str) {
object(c, "INSERT", h, owner, "AcDbEntity");
c.str(8, layer);
if c.v.handles() {
c.raw(100, "AcDbBlockReference");
}
c.str(2, block);
c.xyz(10, 0.0, 0.0);
}
/// The whole file of `d` with `blocks` written after the model and paper space blocks.
pub fn write(d: Drawing, blocks: &[Block]) -> String {
let v = d.version;
let out = d.write();
if blocks.is_empty() {
return out;
}
let mut defs = Codes::new(v);
for b in blocks {
object(&mut defs, "BLOCK", b.begin, b.record, "AcDbEntity");
defs.raw(8, "0");
if v.handles() {
defs.raw(100, "AcDbBlockBegin");
}
defs.str(2, &b.name);
defs.int(70, 0);
defs.xyz(10, 0.0, 0.0);
defs.str(3, &b.name);
defs.raw(1, "");
defs.append(&b.entities);
object(&mut defs, "ENDBLK", b.end, b.record, "AcDbEntity");
defs.raw(8, "0");
if v.handles() {
defs.raw(100, "AcDbBlockEnd");
}
}
let defs = defs.into_string();
if !v.handles() {
// R12 has no model and paper space blocks: its BLOCKS section holds the user blocks only.
let at = " 0\nSECTION\n 2\nENTITIES\n";
return match out.find(at) {
Some(i) => format!("{} 0\nSECTION\n 2\nBLOCKS\n{defs} 0\nENDSEC\n{}", &out[..i], &out[i..]),
None => out,
};
}
let mut records = Codes::new(v);
for b in blocks {
object(&mut records, "BLOCK_RECORD", b.record, fixed::BLOCK_RECORD_TABLE, "AcDbSymbolTableRecord");
records.raw(100, "AcDbBlockTableRecord");
records.str(2, &b.name);
if v.r2000() {
records.handle(340, Handle(0));
records.int(70, 0);
records.int(280, 1);
records.int(281, 0);
}
}
let records = records.into_string();
let (Some(table), Some(blocks_at)) = (out.find(" 0\nTABLE\n 2\nBLOCK_RECORD\n"), out.find(" 0\nSECTION\n 2\nBLOCKS\n")) else {
return out;
};
let count = " 70\n2\n";
let (Some(c), Some(t_end), Some(b_end)) = (
out[table..].find(count).map(|i| table + i),
out[table..].find(" 0\nENDTAB\n").map(|i| table + i),
out[blocks_at..].find(" 0\nENDSEC\n").map(|i| blocks_at + i),
) else {
return out;
};
let mut s = String::with_capacity(out.len() + records.len() + defs.len());
s.push_str(&out[..c]);
s.push_str(&format!(" 70\n{}\n", 2 + blocks.len()));
s.push_str(&out[c + count.len()..t_end]);
s.push_str(&records);
s.push_str(&out[t_end..b_end]);
s.push_str(&defs);
s.push_str(&out[b_end..]);
s
}
+392
View File
@@ -0,0 +1,392 @@
//! DWG drawings, read as DXF: `craft_dwg` converts the bytes and the DXF reader reads the result.
//!
//! The conversion runs in a child process once the program has called [`use_own_worker`] (and
//! [`serve_if_asked`] first thing in `main`), so a damaged file that makes the DWG reader abort
//! ends that process, not VectorCraft. Without a worker the conversion is refused, unless
//! [`allow_in_process`] was called (tests). Web builds answer that DWG can't be read there.
use std::hash::BuildHasher;
use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
use std::time::Duration;
use web_time::Instant;
pub use craft_dwg::{WORKER_ARG, allow_in_process, use_own_worker};
/// Whether this build decodes DWG drawings. Web builds and FreeBSD on 64-bit ARM have no DWG decoder.
pub const DECODES: bool = !cfg!(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")));
/// The worker argument after [`WORKER_ARG`] that gives its deadline in milliseconds since the UNIX epoch
/// ([`use_own_worker_for`]).
const WORKER_UNTIL_ARG: &str = "--dwg-worker-until";
/// Serve one conversion and return the exit code if this process was started as a worker. A
/// worker started by [`use_own_worker_for`] exits with code 1 once its time is up, wherever the
/// conversion is.
pub fn serve_if_asked() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next()? != WORKER_ARG {
return None;
}
if args.next().is_some_and(|a| a == WORKER_UNTIL_ARG)
&& let Some(millis) = args.next().and_then(|s| s.to_str()?.parse::<u64>().ok())
&& let Some(until) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_millis(millis))
{
if until <= std::time::SystemTime::now() {
return Some(1);
}
std::thread::spawn(move || {
std::thread::sleep(until.duration_since(std::time::SystemTime::now()).unwrap_or_default());
std::process::exit(1);
});
}
craft_dwg::serve_if_asked()
}
/// [`use_own_worker`], each worker exiting once `limit` from this call is up (a deadline passed to it
/// in milliseconds since the UNIX epoch), however late it starts, so a program that ends after
/// `limit` leaves no conversion running. If this program's path can't be found, or the deadline
/// can't be written, the worker setting does not change. Web builds have no worker.
pub fn use_own_worker_for(limit: std::time::Duration) {
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
if let Ok(program) = std::env::current_exe()
&& let Some(until) = std::time::SystemTime::now().checked_add(limit).and_then(|until| until.duration_since(std::time::UNIX_EPOCH).ok())
&& let Ok(millis) = u64::try_from(until.as_millis())
{
craft_dwg::worker::use_worker(program, vec![WORKER_ARG.into(), WORKER_UNTIL_ARG.into(), millis.to_string().into()]);
}
#[cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))]
let _ = limit;
}
/// The largest DXF rendition kept for the next read of the same drawing (128 MiB).
const MAX_KEPT: usize = 128 << 20;
/// Is `bytes` a DWG drawing (an `AC10nn` or `AD10nn` version code first)?
pub fn is_dwg(bytes: &[u8]) -> bool {
craft_dwg::is_dwg(bytes) || craft_dwg::is_dwg(&ac_code(bytes))
}
/// The first six bytes of `bytes`, with an `AD10` start read as `AC10`.
fn ac_code(bytes: &[u8]) -> Vec<u8> {
let mut head = bytes.get(..bytes.len().min(7)).unwrap_or(bytes).to_vec();
if head.starts_with(b"AD10") {
head[1] = b'C';
}
head
}
/// The version codes of DWG drawings and the name of each version, oldest first
/// (<https://en.wikipedia.org/wiki/.dwg#Version_history>).
const VERSIONS: [(&str, &str); 21] = [
("MC0.0", "R1.0"),
("AC1.2", "R1.2"),
("AC1.40", "R1.40"),
("AC1.50", "R2.05"),
("AC2.10", "R2.10"),
("AC2.21", "R2.21"),
("AC2.22", "R2.22"),
("AC1001", "R2.22"),
("AC1002", "R2.50"),
("AC1003", "R2.60"),
("AC1004", "R9"),
("AC1006", "R10"),
("AC1009", "R11/12"),
("AC1012", "R13"),
("AC1014", "R14"),
("AC1015", "2000"),
("AC1018", "2004"),
("AC1021", "2007"),
("AC1024", "2010"),
("AC1027", "2013"),
("AC1032", "2018"),
];
/// The version codes the DWG reader reads, each also with `AD` in place of `AC` except `AC1006`.
const READS: [&str; 10] = ["AC1006", "AC1009", "AC1012", "AC1014", "AC1015", "AC1018", "AC1021", "AC1024", "AC1027", "AC1032"];
/// Why `bytes` can't be read when they start with a DWG version code that the DWG reader does
/// not read: the message names the version and says to save the drawing as DXF or as a DWG
/// version that is read. `None` for any other bytes, a DWG drawing of a version that is read
/// included.
pub fn unreadable(bytes: &[u8]) -> Option<String> {
let head = ac_code(bytes);
let numbered = head.starts_with(b"AC10");
if !numbered && ![&b"MC0."[..], b"AC1.", b"AC2."].iter().any(|m| head.starts_with(m)) {
return None;
}
if numbered && READS.iter().any(|c| head.starts_with(c.as_bytes())) && !bytes.starts_with(b"AD1006") {
return None;
}
let named = match VERSIONS.iter().find(|(c, _)| head.starts_with(c.as_bytes())) {
Some((code, name)) => format!("DWG {name} ({})", if bytes.starts_with(b"AD") { code.replacen("AC", "AD", 1) } else { code.to_string() }),
None => {
let shown: String = bytes.iter().take(6).take_while(|b| b.is_ascii_graphic()).map(|&b| char::from(b)).collect();
format!("DWG version {shown}")
}
};
Some(format!(
"this drawing is {named}, a DWG version VectorCraft can't read: save it from the CAD app as a DXF, or as a DWG from R10 to 2018, and open that"
))
}
/// A DWG drawing as DXF bytes, and what the conversion left out.
#[derive(Debug, PartialEq)]
pub(crate) struct Converted {
pub dxf: Vec<u8>,
pub notes: Vec<String>,
}
type Outcome = Result<Arc<Converted>, String>;
/// The outcome of the last drawing converted, by a hash of its bytes and its length, and the
/// conversions a [`Held`] keeps. Open reads a drawing's layouts, draws a preview of each in its
/// dialog and then opens it, and each of those reads the same file; a file the conversion refused
/// (or whose worker stopped) is refused again without another conversion for [`FAILURE_KEPT`],
/// after which the next read converts it again.
#[derive(Default)]
struct Kept {
hasher: std::collections::hash_map::RandomState,
/// The last outcome, by key, and when it was kept.
last: Option<((u64, usize), Outcome, Instant)>,
/// The conversions handed out by [`hold`], while a [`Held`] for each exists.
held: Vec<((u64, usize), Weak<Converted>)>,
}
impl Kept {
fn key(&self, bytes: &[u8]) -> (u64, usize) {
(self.hasher.hash_one(bytes), bytes.len())
}
fn get(&self, key: (u64, usize), now: Instant) -> Option<Outcome> {
let fresh = |outcome: &Outcome, at: &Instant| outcome.is_ok() || now.saturating_duration_since(*at) < FAILURE_KEPT;
if let Some((_, outcome, _)) = self.last.as_ref().filter(|(k, outcome, at)| *k == key && fresh(outcome, at)) {
return Some(outcome.clone());
}
self.held.iter().filter(|(k, _)| *k == key).find_map(|(_, c)| c.upgrade()).map(Ok)
}
fn hold(&mut self, key: (u64, usize), converted: &Arc<Converted>) {
self.held.retain(|(_, c)| c.strong_count() > 0);
self.held.push((key, Arc::downgrade(converted)));
}
fn keep(&mut self, key: (u64, usize), outcome: &Outcome, now: Instant) {
if outcome.as_ref().is_ok_and(|c| c.dxf.len() > MAX_KEPT) {
self.last = None;
} else {
self.last = Some((key, outcome.clone(), now));
}
}
}
/// How long a failed conversion is returned again for the same bytes. A worker can fail for a
/// passing cause (memory, its deadline, a failed start), so a later read converts the drawing again.
const FAILURE_KEPT: Duration = Duration::from_secs(10);
/// The conversion of `bytes` that `kept` holds, else `convert`'s, which `kept` then holds. The
/// lock is not held while `convert` runs, so another drawing can be converted at the same time.
fn through(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
through_at(kept, bytes, &Instant::now, convert)
}
/// [`through`] with the time read from `now`; an outcome is kept from when `convert` returned.
fn through_at(kept: &Mutex<Kept>, bytes: &[u8], now: &dyn Fn() -> Instant, convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Outcome {
let key = {
let kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
let key = kept.key(bytes);
if let Some(outcome) = kept.get(key, now()) {
return outcome;
}
key
};
let outcome = convert(bytes).map(Arc::new);
kept.lock().unwrap_or_else(PoisonError::into_inner).keep(key, &outcome, now());
outcome
}
/// [`through`], and the conversion stays where `kept` finds it while the [`Held`] lasts.
fn hold_in(kept: &Mutex<Kept>, bytes: &[u8], convert: impl FnOnce(&[u8]) -> Result<Converted, String>) -> Result<Held, String> {
let converted = through(kept, bytes, convert)?;
let mut kept = kept.lock().unwrap_or_else(PoisonError::into_inner);
let key = kept.key(bytes);
kept.hold(key, &converted);
Ok(Held { _converted: converted })
}
static KEPT: LazyLock<Mutex<Kept>> = LazyLock::new(Mutex::default);
/// `bytes` (a DWG drawing) as DXF, within craft-dwg's default limits (512 MiB of DWG, 1 GiB of DXF).
pub(crate) fn to_dxf(bytes: &[u8]) -> Outcome {
through(&KEPT, bytes, convert)
}
/// A DWG drawing's conversion, kept for every read of the same bytes ([`crate::info`],
/// [`crate::import`]) while this value exists, whatever other drawings are converted meanwhile and
/// however large its DXF is.
#[derive(Debug, Clone)]
pub struct Held {
_converted: Arc<Converted>,
}
/// Convert `bytes` (a DWG drawing), or take the conversion already kept, and keep it while the
/// returned [`Held`] exists → the conversion's error when it fails.
pub fn hold(bytes: &[u8]) -> Result<Held, String> {
hold_in(&KEPT, bytes, convert)
}
fn convert(bytes: &[u8]) -> Result<Converted, String> {
if let Some(why) = unreadable(bytes) {
return Err(why);
}
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(|e| worded(&e))?;
Ok(Converted { dxf, notes: notes.iter().map(|n| worded(n)).collect() })
}
/// craft-dwg's message or note in VectorCraft's words: VectorCraft opens a DWG and never saves one.
fn worded(message: &str) -> String {
message
.replace("accepted by this bridge", "VectorCraft opens")
.replace("types this bridge can't preserve", "types VectorCraft can't read")
.replace("; saving over the original file would lose them", "")
}
#[cfg(test)]
mod tests {
use super::*;
fn counting<'a>(calls: &'a std::cell::Cell<usize>, dxf: &'a [u8]) -> impl FnOnce(&[u8]) -> Result<Converted, String> + 'a {
move |_| {
calls.set(calls.get() + 1);
Ok(Converted { dxf: dxf.to_vec(), notes: vec![] })
}
}
#[test]
fn the_same_drawing_is_converted_once_and_another_drawing_again() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let a = through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
let again = through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
assert_eq!(calls.get(), 1);
assert_eq!(again.dxf, a.dxf);
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 2);
// The first drawing is no longer held.
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 3);
}
#[test]
fn a_refused_file_is_refused_again_without_converting_and_an_oversized_rendition_is_not_kept() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let start = Instant::now();
let at_start = move || start;
assert_eq!(through_at(&kept, b"AC1015 bad", &at_start, |_| Err("DWG: no".to_string())).unwrap_err(), "DWG: no");
let again = through_at(&kept, b"AC1015 bad", &at_start, counting(&calls, b"0\nEOF\n"));
assert_eq!((again.unwrap_err().as_str(), calls.get()), ("DWG: no", 0));
let big = vec![b' '; MAX_KEPT + 1];
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
assert_eq!(calls.get(), 2, "a rendition over MAX_KEPT is converted again");
}
#[test]
fn a_failed_conversion_is_tried_again_once_its_time_is_up() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let clock = std::cell::Cell::new(Instant::now());
let now = || clock.get();
// The worker fails after running for longer than FAILURE_KEPT: the failure is kept from then.
let slow_failure = |_: &[u8]| {
clock.set(clock.get() + FAILURE_KEPT * 2);
Err("DWG: stopped".to_string())
};
assert!(through_at(&kept, b"AC1015 bad", &now, slow_failure).is_err());
clock.set(clock.get() + FAILURE_KEPT / 2);
let within = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
assert_eq!((within.unwrap_err().as_str(), calls.get()), ("DWG: stopped", 0));
clock.set(clock.get() + FAILURE_KEPT / 2);
let later = through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"0\nEOF\n"));
assert_eq!((later.unwrap().dxf.as_slice(), calls.get()), (b"0\nEOF\n".as_slice(), 1));
// A conversion that worked is kept whatever the time.
clock.set(clock.get() + FAILURE_KEPT * 100);
through_at(&kept, b"AC1015 bad", &now, counting(&calls, b"other")).unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn a_held_drawing_is_not_converted_again_until_its_hold_is_dropped() {
let kept = Mutex::new(Kept::default());
let calls = std::cell::Cell::new(0);
let big = vec![b' '; MAX_KEPT + 1];
let one = hold_in(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
let large = hold_in(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
through(&kept, b"AC1015 two", counting(&calls, b"0\nEOF\n")).unwrap();
assert_eq!(calls.get(), 3);
// Another drawing converted since, and a rendition over MAX_KEPT, are still found.
through(&kept, b"AC1015 one", counting(&calls, b"other")).unwrap();
assert_eq!(through(&kept, b"AC1015 big", counting(&calls, b"other")).unwrap().dxf.len(), big.len());
assert_eq!(calls.get(), 3);
drop((one, large));
through(&kept, b"AC1015 one", counting(&calls, b"0\nEOF\n")).unwrap();
through(&kept, b"AC1015 big", counting(&calls, &big)).unwrap();
assert_eq!(calls.get(), 5, "a dropped hold no longer keeps its conversion");
let refused = hold_in(&kept, b"AC1015 bad", |_| Err("DWG: no".to_string()));
assert_eq!(refused.unwrap_err(), "DWG: no");
}
#[test]
fn messages_name_what_vectorcraft_does() {
let m = worded("DWG: the file is 9.9 MB, larger than the 1.0 MB accepted by this bridge");
assert_eq!(m, "DWG: the file is 9.9 MB, larger than the 1.0 MB VectorCraft opens");
let n = worded("DWG: 2 objects of types this bridge can't preserve were left out (X × 2); saving over the original file would lose them");
assert_eq!(n, "DWG: 2 objects of types VectorCraft can't read were left out (X × 2)");
}
#[test]
fn a_dwg_version_the_reader_skips_is_named_with_what_to_save_it_as() {
let named = [
(&b"AC1001\x00\x00\x00\x00"[..], "DWG R2.22 (AC1001)"),
(b"AD1006\x00\x00\x00\x00", "DWG R10 (AD1006)"),
(b"AD1004\x00\x00\x00\x00", "DWG R9 (AD1004)"),
(b"AC1.50\x00\x00\x00\x00", "DWG R2.05 (AC1.50)"),
(b"AC1.2\x00\x00\x00\x00", "DWG R1.2 (AC1.2)"),
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
(b"AC1033\x00\x00\x00\x00", "DWG version AC1033"),
(b"AC1010\x00\x00\x00\x00", "DWG version AC1010"),
(b"AC10\x00\x00\x00\x00", "DWG version AC10"),
];
for (bytes, name) in named {
let why = unreadable(bytes).unwrap_or_default();
assert!(why.starts_with(&format!("this drawing is {name},")), "{name}: {why}");
assert!(why.contains("as a DXF, or as a DWG from R10 to 2018"), "{why}");
}
for read in [
&b"AC1006\x00\x00"[..],
b"AC1009\x00\x00",
b"AD1009\x00\x00",
b"AC1018\x00\x00",
b"AC1032\x00\x00",
b"AD1015\x00\x00",
b"0\nSECTION\n",
b"AC",
b"",
] {
assert_eq!(unreadable(read), None, "{:?}", String::from_utf8_lossy(read));
}
}
#[test]
fn an_ad_version_code_is_a_dwg_drawing() {
assert!(is_dwg(b"AD1018\x00\x00") && is_dwg(b"AC1018\x00\x00"));
assert!(!is_dwg(b"AD10\x00\x00\x00") && !is_dwg(b"AD1018") && !is_dwg(b"0\nSECTION\n"));
}
#[test]
fn a_dwg_version_the_reader_skips_is_refused_before_converting() {
let e = hold(b"AC1004\x00\x00\x00\x00").unwrap_err();
assert!(e.starts_with("this drawing is DWG R9 (AC1004),"), "{e}");
}
}
+6
View File
@@ -76,6 +76,12 @@ pub fn is_hpgl(bytes: &[u8]) -> bool {
holds_instructions(bytes, true)
}
/// Does `bytes` start like a file named as an HP-GL plot file ([`import`] reads it)? As
/// [`is_hpgl`] checks, but any instruction may come first.
pub fn is_named_hpgl(bytes: &[u8]) -> bool {
holds_instructions(bytes, false)
}
/// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them
/// may come first: a file picked by its extension may start with one a plot file seldom starts
/// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader
+41 -12
View File
@@ -1,12 +1,15 @@
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document.
//! DXF import: a DXF drawing (ASCII or binary) of any version as a document. A DWG drawing comes
//! in the same way, converted to DXF first ([`crate::dwg`]).
//!
//! The drawing's model space (or a paper layout) comes in at a ratio (1 unit of the art = N
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
//! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art
//! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid
//! hatches and solids become paths; text and multiline text point type; named blocks symbols
//! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour),
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and
//! gradient hatches, pattern hatches' lines, solids and regions become paths; text and multiline
//! text point type; named blocks symbols
//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the
//! files they name, clipped by their clip boundaries. Colours (indexed and true colour),
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
//! them. What can't come in is listed in the warnings.
//!
@@ -14,12 +17,16 @@
//! blocks and layouts.
//! - `entity`: entities to items (geometry and properties).
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
//! - `hatch`: pattern hatches' lines and gradient hatches' fills.
//! - `text`: text values to plain text.
//! - `acis`: a region's solid-modeler data as its outline.
//! - `build`: items to the document.
mod acis;
mod build;
mod curve;
mod entity;
mod hatch;
mod reader;
mod text;
@@ -102,11 +109,27 @@ pub fn is_dxf(bytes: &[u8]) -> bool {
false
}
/// The tags of a DXF file and where it is damaged (DWG files are refused).
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if bytes.starts_with(b"AC10") || bytes.starts_with(b"AC1.") {
return Err("this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that".into());
/// The tags of a DXF file, or of a DWG file converted to DXF ([`crate::dwg`]), and what the read
/// left out: where the file is damaged, and what the DWG conversion couldn't read.
fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
if let Some(why) = crate::dwg::unreadable(bytes) {
return Err(why);
}
if crate::dwg::is_dwg(bytes) {
let converted = crate::dwg::to_dxf(bytes)?;
let (tags, mut notes) = dxf_tags(&converted.dxf)?;
notes.extend(converted.notes.iter().cloned());
return Ok((tags, notes));
}
// A DWG version code with nothing after it.
if [&b"AC10"[..], b"AD10"].iter().any(|magic| bytes.starts_with(magic)) {
return Err("DWG: the file is cut short".into());
}
dxf_tags(bytes)
}
/// The tags of a DXF file and where it is damaged.
fn dxf_tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Vec<String>), String> {
let (tags, damaged) = craft_dxf::parse_recovering(bytes).map_err(|e| match e {
craft_dxf::DxfError::TooLarge { .. } => "the drawing is too large to open".to_string(),
_ if bytes.starts_with(reader::BINARY_SENTINEL) => "this binary DXF file is damaged or cut short".to_string(),
@@ -115,7 +138,7 @@ fn tags(bytes: &[u8]) -> Result<(Vec<craft_dxf::Tag>, Option<String>), String> {
if tags.is_empty() {
return Err("not a DXF drawing".into());
}
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out"))))
Ok((tags, damaged.map(|line| format!("the file is damaged at line {line}: what follows is left out")).into_iter().collect()))
}
/// The unit of `$INSUNITS` code `code` and the scale that shows the drawing 1:1 in it.
@@ -182,7 +205,7 @@ pub fn info(bytes: &[u8]) -> Result<DxfInfo, String> {
})
}
/// Import a DXF drawing with `o`.
/// Import a DXF or DWG drawing with `o`.
pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
let (w, h) = o.fit_to;
if !(w > 0.0 && h > 0.0 && w.max(h) <= build::MAX_EXTENT) {
@@ -193,7 +216,7 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
{
return Err(format!("scale must be a number from {} to {}, not {s}", SCALE_RANGE.start(), SCALE_RANGE.end()));
}
let (tags, damaged) = tags(bytes)?;
let (tags, notes) = tags(bytes)?;
let d = reader::Drawing::read(craft_dxf::model::Document::read(&tags));
if d.sections == 0 {
return Err("not a DXF drawing".into());
@@ -214,10 +237,16 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result<Imported, String> {
};
let (mut document, mut warnings) = build::Build::new(&d, o).run(layout, natural, ratio)?;
document.units = if o.fit { unit } else { o.unit.unwrap_or(unit) };
warnings.extend(damaged);
warnings.extend(notes);
document.limit_depth_noting(&mut warnings);
Ok(Imported { document, warnings })
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_dwg;
#[cfg(test)]
mod tests_image;
#[cfg(test)]
mod tests_region;
+779
View File
@@ -0,0 +1,779 @@
//! The solid-modeler data of a REGION as a filled outline: each face's loops of edges, in world x
//! and y (drawing units). The data comes as text (DXF before 2013, ciphered or not) or binary
//! (DXF 2013 and later keep it in the ACDSDATA section).
//!
//! The model is a list of records pointing at each other: a body holds lumps, a lump shells, a
//! shell faces, a face loops, a loop a ring of coedges. Each coedge uses an edge (forward or
//! reversed), and each edge runs between two vertices along a line, an ellipse or a spline. A
//! curve of any other kind comes in as a straight line between its vertices.
//!
//! The REGION groups are in the DXF Reference
//! (<https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4>); which
//! DXF versions hold text and which binary data is in <https://ezdxf.mozman.at/docs/acis.html>.
use std::collections::HashMap;
use kurbo::{BezPath, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathSeg};
use vectorcraft_geom::{Affine, Point};
use super::curve;
/// The most bytes of one region's data read.
pub(crate) const MAX_BYTES: usize = 16 << 20;
/// The most records one region's outline may visit: bodies, lumps, shells, faces and coedges
/// (a loop counts as one at least).
const MAX_VISITS: usize = 1_000_000;
/// The first bytes of binary data: ACIS's, or ASM's (DXF 2018 writes either).
const BINARY_MAGIC: [&[u8]; 2] = [b"ACIS BinaryFile", b"ASM BinaryFile4"];
/// From this version on, every record starts with its attribute, a history number and one more
/// pointer; before it, with its attribute alone.
const LONG_HEADER_VERSION: u32 = 700;
type P3 = [f64; 3];
/// A B-spline: degree, knots, control points, weights (none: all 1).
type Spline = (usize, Vec<f64>, Vec<P3>, Option<Vec<f64>>);
/// One value of a record.
#[derive(Clone, Debug, PartialEq)]
enum Tok {
Ptr(i64),
Num(f64),
Word(String),
/// `forward` (false) or `reversed` (true).
Sense(bool),
Open,
Close,
}
/// A record: its type (`body`, `plane-surface`…) and its values after the ones every record
/// starts with.
#[derive(Debug)]
struct Rec {
kind: String,
toks: Vec<Tok>,
}
impl Rec {
/// The type `base` or one derived from it (`tedge-edge` is an edge).
fn is(&self, base: &str) -> bool {
self.kind == base || self.kind.strip_suffix(base).is_some_and(|k| k.ends_with('-'))
}
/// The `n`th pointer (-1: none).
fn ptr(&self, n: usize) -> i64 {
self.toks.iter().filter_map(|t| if let Tok::Ptr(p) = t { Some(*p) } else { None }).nth(n).unwrap_or(-1)
}
/// The sense right after the `n`th pointer: true when reversed (old files write 1).
fn sense_after(&self, n: usize) -> Option<bool> {
let mut ptrs = 0;
for t in &self.toks {
if ptrs > n {
return match t {
Tok::Sense(r) => Some(*r),
Tok::Num(v) if v.is_finite() => Some(*v != 0.0),
_ => None,
};
}
if matches!(t, Tok::Ptr(_)) {
ptrs += 1;
}
}
None
}
/// The numbers, in order.
fn nums(&self) -> Vec<f64> {
self.toks.iter().filter_map(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect()
}
}
/// The records of one body, and how pointers find them.
struct Model {
recs: Vec<Rec>,
/// Record number by index, when the records carry their own.
at: HashMap<i64, usize>,
}
impl Model {
fn get(&self, p: i64) -> Option<&Rec> {
if p < 0 {
return None;
}
if self.at.is_empty() { self.recs.get(usize::try_from(p).ok()?) } else { self.recs.get(*self.at.get(&p)?) }
}
/// The record `p` points at when it is of type `base`.
fn get_is(&self, p: i64, base: &str) -> Option<&Rec> {
self.get(p).filter(|r| r.is(base))
}
/// The records of type `base` from `first` along their `next` pointer (pointer `next`), each
/// once. Missing records, wrong types and cycles outside coedge rings set `broken`.
fn chain(&self, first: i64, base: &str, next: usize, broken: &mut bool) -> Vec<&Rec> {
let mut out = vec![];
let mut seen = std::collections::HashSet::new();
let mut p = first;
while p >= 0 {
if !seen.insert(p) {
*broken |= base != "coedge";
break;
}
let Some(r) = self.get_is(p, base) else {
*broken = true;
break;
};
out.push(r);
p = r.ptr(next);
}
out
}
}
/// A region's outline: its faces' loops, closed; `approximated` when an edge of a curve type
/// this reader doesn't draw came in as a straight line; `broken` when a topology chain breaks
/// off or a loop's ring of coedges doesn't come back to its first; `ambiguous` when an edge's
/// endpoint lies on separate parts of its curve.
#[derive(Debug)]
pub(crate) struct Outline {
pub path: BezPath,
pub approximated: bool,
pub broken: bool,
pub ambiguous: bool,
}
/// Text data, ciphered as DXF writes it or not.
pub(crate) fn from_text(text: &str) -> Option<Outline> {
if text.len() > MAX_BYTES {
return None;
}
let plain;
let text = if text.trim_start().starts_with(|c: char| c.is_ascii_digit()) {
text
} else {
plain = decipher(text);
&plain
};
outline(&sat_model(text)?)
}
/// Binary data.
pub(crate) fn from_binary(bytes: &[u8]) -> Option<Outline> {
if bytes.len() > MAX_BYTES {
return None;
}
outline(&sab_model(bytes)?)
}
/// DXF's cipher of text data undone: each printable character is mapped back, and the space
/// written after a mapped `A` (a caret, which DXF reads as a control code) is dropped.
fn decipher(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
out.push(match c {
' ' | '\n' | '\r' | '\t' => c,
'@'..='_' => char::from(159 - c as u8),
c if c.is_ascii() && !c.is_ascii_control() => char::from(c as u8 ^ 0x5F),
c => c,
});
if c == '^' && chars.peek() == Some(&' ') {
chars.next();
}
}
out
}
/// How many values every record starts with in data of `version`.
fn header_len(version: u32) -> usize {
if version >= LONG_HEADER_VERSION { 3 } else { 1 }
}
/// A text value as a value.
fn sat_tok(w: &str) -> Tok {
match w {
"{" => Tok::Open,
"}" => Tok::Close,
"forward" | "forward_v" => Tok::Sense(false),
"reversed" | "reversed_v" => Tok::Sense(true),
_ => {
if let Some(p) = w.strip_prefix('$').and_then(|p| p.parse::<i64>().ok()) {
return Tok::Ptr(p);
}
match w.parse::<f64>() {
Ok(v) if v.is_finite() => Tok::Num(v),
_ => Tok::Word(w.to_string()),
}
}
}
}
/// Does this line start a record (`[-<index>] <type> $<attribute> …`)?
fn starts_record(line: &str) -> bool {
let mut words = line.split_whitespace();
let first = words.next().unwrap_or_default();
let (kind, next) = if first.starts_with('-') && first[1..].parse::<u64>().is_ok() {
(words.next().unwrap_or_default(), words.next().unwrap_or_default())
} else {
(first, words.next().unwrap_or_default())
};
kind.starts_with(|c: char| c.is_ascii_alphabetic()) && next.starts_with('$')
}
/// Text data's records: a version line, product and tolerance lines, then records ending in `#`.
fn sat_model(text: &str) -> Option<Model> {
let version = text.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite() && *v >= 0.0)? as u32;
let skip = header_len(version);
let mut offset = text.find('\n')? + 1;
let start = loop {
let rest = text.get(offset..)?;
let line = rest.split('\n').next().unwrap_or_default();
if starts_record(line) {
break offset;
}
offset += line.len() + 1;
};
let body = text.get(start..)?;
let (mut recs, mut at) = (Vec::new(), HashMap::new());
let mut cur: Vec<Tok> = vec![];
let (mut kind, mut index): (Option<String>, Option<i64>) = (None, None);
let mut i = 0;
let b = body.as_bytes();
while i < b.len() {
if b[i].is_ascii_whitespace() {
i += 1;
continue;
}
let end = b[i..].iter().position(u8::is_ascii_whitespace).map_or(b.len(), |n| i + n);
let word = body.get(i..end)?;
i = end;
// A counted string: `@<n>`, a space, then n bytes.
if let Some(n) = word.strip_prefix('@').and_then(|n| n.parse::<usize>().ok()) {
let from = (i + 1).min(b.len());
let to = from.checked_add(n)?.min(b.len());
cur.push(Tok::Word(body.get(from..to)?.to_string()));
i = to;
continue;
}
let (word, ends) = match word.strip_suffix('#') {
Some(w) => (w, true),
None => (word, false),
};
if !word.is_empty() {
match &kind {
None if index.is_none() && word.starts_with('-') && word[1..].parse::<i64>().is_ok() => {
index = word[1..].parse().ok();
}
None => {
if word.starts_with("End-of-") || word.starts_with("Begin-of-") {
break;
}
kind = Some(word.to_string());
}
Some(_) => cur.push(sat_tok(word)),
}
}
if ends {
let toks = cur.split_off(skip.min(cur.len()));
cur.clear();
if let Some(n) = index.take() {
at.insert(n, recs.len());
}
recs.push(Rec { kind: kind.take().unwrap_or_default(), toks });
}
}
Some(Model { recs, at })
}
/// Reads binary data's little-endian values.
struct Bytes<'b> {
b: &'b [u8],
i: usize,
}
impl Bytes<'_> {
fn take(&mut self, n: usize) -> Option<&[u8]> {
let s = self.b.get(self.i..self.i.checked_add(n)?)?;
self.i += n;
Some(s)
}
fn u8(&mut self) -> Option<u8> {
self.take(1).map(|s| s[0])
}
fn i16(&mut self) -> Option<f64> {
self.take(2).map(|s| f64::from(i16::from_le_bytes([s[0], s[1]])))
}
fn u16(&mut self) -> Option<usize> {
self.take(2).map(|s| usize::from(u16::from_le_bytes([s[0], s[1]])))
}
fn i32(&mut self) -> Option<i32> {
self.take(4).map(|s| i32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn u32(&mut self) -> Option<u32> {
self.take(4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn f64(&mut self) -> Option<f64> {
let s = self.take(8)?;
Some(f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
}
fn text(&mut self, n: usize) -> Option<String> {
self.take(n).map(|s| String::from_utf8_lossy(s).into_owned())
}
}
/// Binary data's records: the magic, four numbers (version first), product and tolerance values,
/// then records of tagged values, each type name made of its parts.
fn sab_model(b: &[u8]) -> Option<Model> {
let mut r = Bytes { b: BINARY_MAGIC.iter().find_map(|m| b.strip_prefix(*m))?, i: 0 };
let version = r.u32()?;
r.take(12)?;
let skip = header_len(version);
let mut recs = vec![];
let (mut parts, mut kind, mut cur): (Vec<String>, Option<String>, Vec<Tok>) = (vec![], None, vec![]);
while r.i < r.b.len() {
let tag = r.u8()?;
let tok = match tag {
0x02 => Tok::Num(f64::from(i8::from_le_bytes([r.u8()?]))),
0x03 => Tok::Num(r.i16()?),
0x04 | 0x15 => Tok::Num(f64::from(r.i32()?)),
0x05 => Tok::Num(f64::from(f32::from_le_bytes(r.take(4)?.try_into().ok()?))),
0x06 | 0x17 => Tok::Num(r.f64()?),
0x07 => {
let n = usize::from(r.u8()?);
Tok::Word(r.text(n)?)
}
0x08 => {
let n = r.u16()?;
Tok::Word(r.text(n)?)
}
0x09 | 0x12 => {
let n = usize::try_from(r.u32()?).ok()?;
Tok::Word(r.text(n)?)
}
0x0A => Tok::Sense(true),
0x0B => Tok::Sense(false),
0x0C => Tok::Ptr(i64::from(r.i32()?)),
0x0D | 0x0E => {
let n = usize::from(r.u8()?);
let name = r.text(n)?;
if kind.is_some() {
Tok::Word(name)
} else {
parts.push(name);
if tag == 0x0D {
let k = parts.join("-");
parts.clear();
if k.starts_with("End-of-") || k.starts_with("Begin-of-") {
break;
}
kind = Some(k);
}
continue;
}
}
0x0F => Tok::Open,
0x10 => Tok::Close,
0x11 => {
if let Some(k) = kind.take() {
let toks = cur.split_off(skip.min(cur.len()));
recs.push(Rec { kind: k, toks });
}
cur.clear();
continue;
}
0x13 | 0x14 => {
for _ in 0..3 {
cur.push(Tok::Num(r.f64()?));
}
continue;
}
0x16 => {
for _ in 0..2 {
cur.push(Tok::Num(r.f64()?));
}
continue;
}
_ => return None,
};
// Values before the first record are the header's.
if kind.is_some() {
cur.push(tok);
}
}
Some(Model { recs, at: HashMap::new() })
}
/// A body's placement: `p · m · scale + t`.
#[derive(Clone, Copy)]
struct Xf {
m: [P3; 3],
scale: f64,
t: P3,
}
impl Xf {
const IDENTITY: Xf = Xf { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], scale: 1.0, t: [0.0; 3] };
/// A `transform` record's: nine matrix numbers row by row, the translation, the scale.
fn read(r: &Rec) -> Option<Xf> {
let n: Vec<f64> = r.toks.iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
if n.iter().any(|v| !v.is_finite()) {
return None;
}
let v = |i: usize| n.get(i).copied();
let row = |i: usize| Some([v(i)?, v(i + 1)?, v(i + 2)?]);
let scale = v(12)?;
Some(Xf { m: [row(0)?, row(3)?, row(6)?], t: row(9)?, scale })
}
fn vector(&self, p: P3) -> P3 {
let [a, b, c] = self.m;
std::array::from_fn(|i| (p[0] * a[i] + p[1] * b[i] + p[2] * c[i]) * self.scale)
}
fn point(&self, p: P3) -> P3 {
let v = self.vector(p);
std::array::from_fn(|i| v[i] + self.t[i])
}
}
/// Seen from above: x and y.
fn flat(p: P3) -> Point {
Point::new(p[0], p[1])
}
fn sub(a: P3, b: P3) -> P3 {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn dot(a: P3, b: P3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: P3, b: P3) -> P3 {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn p3(n: &[f64], i: usize) -> Option<P3> {
Some([*n.get(i)?, *n.get(i + 1)?, *n.get(i + 2)?])
}
/// Endpoints farther apart than rounding at their coordinate size allows.
fn endpoints_apart(a: Point, b: Point) -> bool {
a.distance(b) > 1e-6 * (1.0 + a.x.hypot(a.y).max(b.x.hypot(b.y)))
}
/// Every face's loops of every body, as one path (filled even-odd).
fn outline(m: &Model) -> Option<Outline> {
let mut o = Outline { path: BezPath::new(), approximated: false, broken: false, ambiguous: false };
// Records visited at every level together: chains shared between records are walked again
// each time.
let mut visits = 0usize;
let mut spend = |n: usize| {
visits = visits.saturating_add(n.max(1));
(visits <= MAX_VISITS).then_some(())
};
for body in m.recs.iter().filter(|r| r.is("body")) {
spend(1)?;
let xf = if body.ptr(2) == -1 { Xf::IDENTITY } else { Xf::read(m.get_is(body.ptr(2), "transform")?)? };
for lump in m.chain(body.ptr(0), "lump", 0, &mut o.broken) {
spend(1)?;
for shell in m.chain(lump.ptr(1), "shell", 0, &mut o.broken) {
spend(1)?;
for face in m.chain(shell.ptr(2), "face", 0, &mut o.broken) {
spend(1)?;
for lp in m.chain(face.ptr(1), "loop", 0, &mut o.broken) {
let ring = m.chain(lp.ptr(1), "coedge", 0, &mut o.broken);
spend(ring.len())?;
let complete = ring.last().is_some_and(|c| c.ptr(0) == lp.ptr(1));
o.broken |= !complete;
let mut bp = BezPath::new();
for c in ring {
let edge = m.get_is(c.ptr(3), "edge")?;
let (seg, ambiguous) = edge_path(m, edge, c.sense_after(3)?, &xf, &mut o.approximated)?;
o.ambiguous |= ambiguous;
if let (Some(end), Some(start)) =
(bp.elements().last().and_then(|e| e.end_point()), seg.elements().first().and_then(|e| e.end_point()))
{
o.broken |= endpoints_apart(end, start);
}
super::entity::append(&mut bp, &seg);
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
return None;
}
}
if !bp.elements().is_empty() {
if complete
&& let (Some(end), Some(start)) =
(bp.elements().last().and_then(|e| e.end_point()), bp.elements().first().and_then(|e| e.end_point()))
{
o.broken |= endpoints_apart(end, start);
}
// A loop of one curve ending where it starts is split in two: as one
// segment, its start and end would become one anchor.
if let [seg] = bp.segments().collect::<Vec<_>>()[..]
&& !matches!(seg, PathSeg::Line(_))
{
let (a, b) = seg.subdivide();
bp = BezPath::from_path_segments([a, b].into_iter());
}
bp.close_path();
if o.path.elements().len().saturating_add(bp.elements().len()) > super::build::MAX_ELEMENTS {
return None;
}
o.path.extend(bp);
}
}
}
}
}
}
let ok = !o.path.elements().is_empty() && curve::bounds(&o.path).is_some();
ok.then_some(o)
}
/// A vertex's position.
fn vertex(m: &Model, p: i64) -> Option<P3> {
let v = m.get_is(p, "vertex")?;
let n = m.get_is(v.ptr(1), "point")?.nums();
p3(&n, 0).filter(|p| p.iter().all(|c| c.is_finite()))
}
/// The edge as a coedge runs it (`reversed`: from its end vertex to its start), from the first
/// point.
fn edge_path(m: &Model, edge: &Rec, reversed: bool, xf: &Xf, approximated: &mut bool) -> Option<(BezPath, bool)> {
let (sv, ev) = (vertex(m, edge.ptr(0))?, vertex(m, edge.ptr(1))?);
let closed = edge.ptr(0) == edge.ptr(1);
let (from, to) = if reversed { (ev, sv) } else { (sv, ev) };
// Against the curve's own direction?
let back = edge.sense_after(3)? != reversed;
let drawn = match m.get(edge.ptr(3)) {
// Only -1 means the edge has no curve.
None => {
*approximated |= edge.ptr(3) != -1;
None
}
Some(c) if c.is("straight-curve") => None,
Some(c) => {
let bp = if c.is("ellipse-curve") {
ellipse(c, from, to, closed, back, xf).map(|bp| (bp, false))
} else if c.is("intcurve-curve") {
spline(c, from, to, closed, back, xf)
} else {
None
};
*approximated |= bp.is_none();
bp
}
};
if let Some(bp) = drawn {
return Some(bp);
}
let mut bp = BezPath::new();
bp.move_to(flat(xf.point(from)));
bp.line_to(flat(xf.point(to)));
Some((bp, false))
}
/// An `ellipse-curve` (centre, normal, major axis, ratio) from `from` to `to`; the whole curve
/// when the edge starts and ends at one vertex. It runs counter-clockwise about its normal,
/// clockwise when `back`.
fn ellipse(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<BezPath> {
let n = c.nums();
let (centre, normal, major, ratio) = (p3(&n, 0)?, p3(&n, 3)?, p3(&n, 6)?, *n.get(9)?);
let len = dot(normal, normal).sqrt();
if !(len > 1e-12 && ratio > 0.0 && ratio.is_finite() && dot(major, major) > 1e-24) {
return None;
}
let minor = cross(normal, major).map(|v| v / len * ratio);
let angle = |p: P3| {
let d = sub(p, centre);
(dot(d, minor) / dot(minor, minor)).atan2(dot(d, major) / dot(major, major))
};
let (a, b) = (angle(from), angle(to));
let tau = std::f64::consts::TAU;
let sweep = match (closed, back) {
(true, false) => tau,
(true, true) => -tau,
(false, false) => (b - a).rem_euclid(tau),
(false, true) => -(a - b).rem_euclid(tau),
};
let (o, u, v) = (flat(xf.point(centre)), flat(xf.vector(major)), flat(xf.vector(minor)));
curve::ellipse(Affine::new([u.x, u.y, v.x, v.y, o.x, o.y]), a, sweep)
}
/// An `intcurve-curve`'s B-spline (`nubs`, or `nurbs` with weights): degree, form, the knots
/// with their multiplicities (without the end knots, or with them), the control points.
fn bspline(toks: &[Tok]) -> Option<Spline> {
let at = toks.iter().position(|t| matches!(t, Tok::Word(w) if matches!(w.as_str(), "nubs" | "nurbs" | "nullbs")))?;
let rational = match &toks[at] {
Tok::Word(w) if w == "nurbs" => true,
Tok::Word(w) if w == "nubs" => false,
_ => return None,
};
let num = |i: usize| if let Some(Tok::Num(v)) = toks.get(i) { Some(*v) } else { None };
let degree = num(at + 1).filter(|d| (1.0..=32.0).contains(d))? as usize;
let count = num(at + 3).filter(|n| *n >= 1.0 && *n <= toks.len() as f64)? as usize;
let mut knots = vec![];
let mut i = at + 4;
for _ in 0..count {
let (k, mult) = (num(i)?, num(i + 1)?);
if !(mult >= 1.0 && mult <= (degree + 1) as f64) {
return None;
}
knots.extend(std::iter::repeat_n(k, mult as usize));
i += 2;
}
let stride = if rational { 4 } else { 3 };
let values: Vec<f64> = toks[i.min(toks.len())..].iter().map_while(|t| if let Tok::Num(v) = t { Some(*v) } else { None }).collect();
let available = values.len() / stride;
// The data leaves out the first and last knots; data that keeps them has two points fewer.
let short = (knots.len() + 1).checked_sub(degree)?;
let n = if available >= short {
let (first, last) = (*knots.first()?, *knots.last()?);
knots.insert(0, first);
knots.push(last);
short
} else {
knots.len().checked_sub(degree + 1)?
};
if n == 0 || n > available {
return None;
}
let pts = values.chunks(stride).take(n).map(|c| [c[0], c[1], c[2]]).collect();
let weights = rational.then(|| values.chunks(stride).take(n).map(|c| c[3]).collect());
Some((degree, knots, pts, weights))
}
/// The distinct parameters of a cubic's self-intersection, when both lie on the curve.
fn cubic_crossing(cubic: kurbo::CubicBez) -> Option<(f64, f64)> {
let b = (cubic.p1 - cubic.p0) * 3.0;
let c = (cubic.p2 - cubic.p1) * 3.0 - b;
let d = (cubic.p3 - cubic.p0) - b - c;
let det = c.cross(d);
if det == 0.0 {
return None;
}
// Dividing P(s) - P(t) by s - t gives b + c*u + d*(u*u - v) = 0,
// where u = s + t and v = s*t.
let u = -b.cross(d) / det;
let v = u * u - b.cross(c) / det;
let discriminant = u * u - 4.0 * v;
if !discriminant.is_finite() || discriminant <= 0.0 {
return None;
}
let root = discriminant.sqrt();
let (s, t) = ((u - root) * 0.5, (u + root) * 0.5);
(0.0 <= s && s < t && t <= 1.0).then_some((s, t))
}
/// An `intcurve-curve` from `from` to `to` (the part of its spline between them), the whole
/// ring when the edge starts and ends at one vertex; also whether trimming is ambiguous.
fn spline(c: &Rec, from: P3, to: P3, closed: bool, back: bool, xf: &Xf) -> Option<(BezPath, bool)> {
// The curve's own sense comes before its data.
let open = c.toks.iter().position(|t| *t == Tok::Open)?;
let curve_back = c.toks[..open].contains(&Tok::Sense(true));
let (degree, knots, pts, weights) = bspline(&c.toks[open..])?;
let ctrl: Vec<Point> = pts.into_iter().map(|p| flat(xf.point(p))).collect();
let full = curve::nurbs(degree, &knots, &ctrl, weights.as_deref())?;
let back = back != curve_back;
let segs: Vec<PathSeg> = full.segments().collect();
let (first, last) = (segs.first()?.start(), segs.last()?.end());
let ring = first.distance(last) <= 1e-9 * (1.0 + first.to_vec2().hypot());
let mut lengths = vec![0.0];
for s in &segs {
lengths.push(lengths.last()? + s.arclen(1e-9));
}
let total = *lengths.last()?;
let at = |p: P3| {
let p = flat(xf.point(p));
let near: Vec<_> = segs.iter().enumerate().map(|(i, s)| (s.nearest(p, 1e-9), i)).collect();
let (n, i) = near.iter().min_by(|a, b| a.0.distance_sq.total_cmp(&b.0.distance_sq))?;
let along = |i: usize, t: f64| lengths[i] + segs[i].subsegment(0.0..t).arclen(1e-9);
let tolerance = 1e-6 * (1.0 + p.x.hypot(p.y));
let mut locations: Vec<_> =
near.iter().filter(|(n, i)| !endpoints_apart(p, segs[*i].eval(n.t))).map(|(n, i)| (*i as f64 + n.t, along(*i, n.t))).collect();
for (i, s) in segs.iter().enumerate() {
if let PathSeg::Cubic(cubic) = s
&& let Some((a, b)) = cubic_crossing(*cubic)
&& !endpoints_apart(p, cubic.eval(a))
{
locations.extend([a, b].map(|t| (i as f64 + t, along(i, t))));
}
}
// Nearby ends at a segment joint, or at a closed curve's seam, are one location.
locations.sort_by(|a, b| a.0.total_cmp(&b.0));
locations.dedup_by(|a, b| (a.1 - b.1).abs() <= 4.0 * tolerance);
if ring && locations.len() > 1 && (total - (locations.last()?.1 - locations.first()?.1)).abs() <= 4.0 * tolerance {
locations.pop();
}
Some((*i as f64 + n.t, locations))
};
let mut ambiguous = false;
let part = if closed && ring {
let (_, locations) = at(from)?;
ambiguous = locations.len() > 1;
full
} else {
let bounds = if closed {
let (_, locations) = at(from)?;
if let [a, b] = locations.as_slice() {
Some((a.0, b.0))
} else {
ambiguous = true;
None
}
} else {
let ((ga, a), (gb, b)) = (at(from)?, at(to)?);
ambiguous = a.len() > 1 || b.len() > 1;
Some((ga, gb))
};
if let Some((ga, gb)) = bounds {
let (lo, hi) = if back { (gb, ga) } else { (ga, gb) };
let pieces = if lo <= hi || !ring {
piece(&segs, lo.min(hi), hi.max(lo))
} else {
[piece(&segs, lo, segs.len() as f64), piece(&segs, 0.0, hi)].concat()
};
if pieces.is_empty() {
return None;
}
BezPath::from_path_segments(pieces.into_iter())
} else {
full
}
};
Some((if back { part.reverse_subpaths() } else { part }, ambiguous))
}
/// The parts of `segs` from `lo` to `hi`, counted in segments (2.5: halfway along the third).
fn piece(segs: &[PathSeg], lo: f64, hi: f64) -> Vec<PathSeg> {
let mut out = vec![];
for (i, s) in segs.iter().enumerate() {
let (t0, t1) = ((lo - i as f64).max(0.0), (hi - i as f64).min(1.0));
if t1 > t0 {
out.push(s.subsegment(t0..t1));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cubic_crossings_have_two_distinct_parameters() {
let cubic = kurbo::CubicBez::new((36.0, -18.0), (-28.0, 26.0), (-28.0, -26.0), (36.0, 18.0));
let (s, t) = cubic_crossing(cubic).unwrap();
assert!((s - 0.25).abs() < 1e-12 && (t - 0.75).abs() < 1e-12, "{s}, {t}");
let plain = kurbo::CubicBez::new((0.0, 0.0), (30.0, 50.0), (70.0, -50.0), (100.0, 0.0));
assert!(cubic_crossing(plain).is_none());
}
#[test]
fn deciphering_maps_each_character_back_and_drops_the_caret_space() {
// "Ab@_ 7#" ciphered: A→^ (and a space), b→=, @→_, _→@, 7→h, #→|.
assert_eq!(decipher("^ =_@ h|"), "Ab@_ 7#");
}
}
+580 -29
View File
@@ -7,13 +7,17 @@ use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use kurbo::BezPath;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject};
use kurbo::{BezPath, PathEl};
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{
Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind,
Symbol, TextObject,
};
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect};
use super::ImportOptions;
use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem};
use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Shade, Span, TextItem};
use super::hatch::{Grad, Second};
use super::reader::{Drawing, LayoutDef};
use crate::{CAP_HEIGHT, MAX_NEST};
@@ -22,12 +26,12 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
/// The stroke weight of lineweight 0 (CAD apps draw it one device pixel wide), in points.
const THINNEST: f64 = 0.25;
/// The most objects an import makes.
const MAX_NODES: usize = 2_000_000;
const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 };
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
/// per item of the block looked at for it (art on hidden layers too).
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
/// The most path elements an import makes (blocks drawn as art are copied for every placement).
const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
pub(crate) const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern).
const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 };
/// The most bytes of text, font names and symbol names an import copies into objects (a block's
@@ -38,6 +42,9 @@ const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
const MAX_FAMILY_BYTES: usize = 256;
/// How far from the origin art may lie (points): the canvas.
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
/// How far from a symbol's origin its image clip points may lie (points): as far as an insert at
/// the smallest scale it accepts (1e-12) still brings back onto the canvas.
const MAX_SYMBOL_EXTENT: f64 = MAX_EXTENT * 1e12;
const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out";
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
@@ -46,6 +53,27 @@ const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points:
const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out";
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
const NO_IMAGE_FILE: &str = "images that name no image file are left out";
const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out";
const IMAGE_SIZE: &str = "images with no size in pixels, or more than 1,048,576 pixels a side, are left out";
/// The most pixels an image may have a side.
const MAX_IMAGE_SIDE: f64 = 1_048_576.0;
/// The key of the image data of the images showing the file at a path: the placeholder, until
/// the file is read.
const IMAGE_KEY: &str = "dxf-image-";
/// How a path paints.
#[derive(Clone, Copy)]
enum Look<'g> {
/// Stroked at its width or lineweight, in its linetype.
Line,
/// Filled with its color.
Fill,
/// Filled with a gradient hatch's gradient.
Gradient(&'g Grad),
/// Pattern hatch lines: stroked without the linetype; `dots` take round caps.
Pattern { dots: bool },
}
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
/// and opacity where the art says "by block", and its layer for art on layer 0.
@@ -58,6 +86,35 @@ struct Inherit {
layer: Option<String>,
}
/// Objects, path elements, dash lengths and text bytes taken from the import's limits.
#[derive(Clone, Copy, Debug, Default)]
struct Cost {
nodes: usize,
elements: usize,
dash_values: usize,
text_bytes: usize,
}
impl Cost {
fn minus(self, o: Cost) -> Cost {
Cost {
nodes: self.nodes.saturating_sub(o.nodes),
elements: self.elements.saturating_sub(o.elements),
dash_values: self.dash_values.saturating_sub(o.dash_values),
text_bytes: self.text_bytes.saturating_sub(o.text_bytes),
}
}
fn plus(self, o: Cost) -> Cost {
Cost {
nodes: self.nodes.saturating_add(o.nodes),
elements: self.elements.saturating_add(o.elements),
dash_values: self.dash_values.saturating_add(o.dash_values),
text_bytes: self.text_bytes.saturating_add(o.text_bytes),
}
}
}
pub(crate) struct Build<'d, 'a> {
d: &'d Drawing<'a>,
o: &'d ImportOptions,
@@ -74,6 +131,21 @@ pub(crate) struct Build<'d, 'a> {
next_suffix: HashMap<String, usize>,
/// Blocks being drawn, outermost first.
stack: Vec<String>,
/// How many symbols' art is being drawn: above 0, art is in a symbol's own space.
in_symbol: u32,
/// The box of the image clip points in the symbol being drawn, in its own space, and of each
/// symbol made (none: its art has no clips).
clip_reach: Option<Rect>,
symbol_reach: HashMap<String, Rect>,
/// What each symbol's own art took from the limits (not the symbols made while drawing it),
/// how many instances place each symbol, and what the symbols made inside the one being
/// drawn took.
symbol_cost: HashMap<String, Cost>,
uses: HashMap<String, usize>,
nested: Cost,
/// Each symbol's place in the document's symbols, and the symbols whose art was taken out.
symbol_slot: HashMap<String, usize>,
empty: HashSet<String>,
/// Document space per drawing unit, and its symbols' (no translation).
map: Affine,
symbol_map: Affine,
@@ -128,7 +200,7 @@ impl<'d, 'a> Build<'d, 'a> {
Self {
d,
o,
conv: Converter::default(),
conv: Converter::new(d.regions.clone()),
doc: Document::new(1.0, 1.0),
blocks: HashMap::new(),
bounds: HashMap::new(),
@@ -137,6 +209,14 @@ impl<'d, 'a> Build<'d, 'a> {
symbol_names: HashSet::new(),
next_suffix: HashMap::new(),
stack: vec![],
in_symbol: 0,
clip_reach: None,
symbol_reach: HashMap::new(),
symbol_cost: HashMap::new(),
uses: HashMap::new(),
symbol_slot: HashMap::new(),
empty: HashSet::new(),
nested: Cost::default(),
map: Affine::IDENTITY,
symbol_map: Affine::IDENTITY,
lw_scale: 1.0,
@@ -169,6 +249,72 @@ impl<'d, 'a> Build<'d, 'a> {
}
}
/// What the import has taken from its limits so far.
fn cost(&self) -> Cost {
Cost { nodes: self.nodes, elements: self.elements, dash_values: self.dash_values, text_bytes: self.text_bytes }
}
fn set_cost(&mut self, c: Cost) {
self.nodes = c.nodes;
self.elements = c.elements;
self.dash_values = c.dash_values;
self.text_bytes = c.text_bytes;
}
/// Take symbol `name`'s art out when no instance places it, giving back its share of the limits
/// and its art's instances of other symbols (and in turn those that no instance places any
/// more); the art, when it was taken. The symbol stays empty until [`Self::restore`] puts the
/// art back or [`Self::symbol`] draws it again, and is dropped at the end if still empty.
fn take_unused(&mut self, name: &str) -> Option<Arc<Node>> {
let first = self.take_art(name)?;
// A worklist, not recursion: chains of symbols can be long.
let mut todo = placed_symbols(&first);
while let Some(s) = todo.pop() {
if let Some(n) = self.uses.get_mut(&s) {
*n = n.saturating_sub(1);
}
if let Some(art) = self.take_art(&s) {
todo.extend(placed_symbols(&art));
}
}
Some(first)
}
/// Symbol `name`'s art, taken out with its share of the limits when no instance places it.
fn take_art(&mut self, name: &str) -> Option<Arc<Node>> {
if self.uses.get(name).is_some_and(|n| *n > 0) || self.empty.contains(name) {
return None;
}
let i = *self.symbol_slot.get(name)?;
let id = self.doc.alloc_id();
let art = std::mem::replace(&mut self.doc.symbols.get_mut(i)?.art, Arc::new(Node::group(id, vec![])));
self.set_cost(self.cost().minus(self.symbol_cost.get(name).copied().unwrap_or_default()));
self.empty.insert(name.to_string());
Some(art)
}
/// Put `art`, taken from symbol `name` by [`Self::take_unused`], back, charging its share of
/// the limits again; false (nothing changed) when that share no longer fits.
fn restore(&mut self, name: &str, art: Arc<Node>) -> bool {
let t = self.cost().plus(self.symbol_cost.get(name).copied().unwrap_or_default());
let inner = placed_symbols(&art);
// Its instances of symbols that are empty now need those drawn again.
let fits = t.nodes < MAX_NODES && t.elements <= MAX_ELEMENTS && t.dash_values <= MAX_DASH_VALUES && t.text_bytes <= MAX_TEXT_BYTES;
if !fits || inner.iter().any(|s| self.empty.contains(s)) {
return false;
}
let Some(slot) = self.symbol_slot.get(name).and_then(|i| self.doc.symbols.get_mut(*i)) else {
return false;
};
slot.art = art;
self.set_cost(t);
self.empty.remove(name);
for s in inner {
*self.uses.entry(s).or_default() += 1;
}
true
}
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
/// unit and at the scale asked for (fitting computes its own).
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
@@ -183,6 +329,7 @@ impl<'d, 'a> Build<'d, 'a> {
if !layers.is_empty() {
doc.layers = layers;
}
drop_unplaced_symbols(&mut doc);
if let Some(a) = doc.artboards.first_mut() {
a.rect = Rect::from_origin_size(Point::ZERO, size);
}
@@ -291,7 +438,7 @@ impl<'d, 'a> Build<'d, 'a> {
/// An item's bounds in world coordinates (type: an estimate from its height and length).
fn item_bounds(&mut self, it: &Item, depth: u32) -> Option<Rect> {
match &it.geom {
Geom::Path { bp, .. } => super::curve::bounds(bp),
Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp),
Geom::Text(t) => {
let lines = t.text.lines().count().max(1) as f64;
let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64;
@@ -314,6 +461,14 @@ impl<'d, 'a> Build<'d, 'a> {
let attribs: Vec<Option<Rect>> = ins.attribs.iter().map(|a| self.item_bounds(a, depth)).collect();
cells.map(Some).chain(attribs).fold(None, vectorcraft_geom::union_opt)
}
Geom::Image(im) => {
self.image_file(im)?;
let (w, h) = self.image_size(im)?;
let place = im.placement(h);
let whole = place.transform_rect_bbox(Rect::new(0.0, 0.0, w, h));
let clip = im.clip.as_ref().and_then(|c| c.iter().map(|p| place * *p).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b)));
Some(clip.map_or(whole, |c| c.intersect(whole)))
}
}
.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()))
}
@@ -331,8 +486,17 @@ impl<'d, 'a> Build<'d, 'a> {
for it in items.iter() {
let p = &it.props;
let on_zero = p.layer == "0";
s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock;
s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER");
// Fills draw no stroke, and pattern lines carry their own dashes.
let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. });
let stroked = !filled;
let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. });
s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock;
s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK");
s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER"));
if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom {
let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer);
s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c));
}
if let Geom::Insert(ins) = &it.geom {
s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1);
}
@@ -391,6 +555,23 @@ impl<'d, 'a> Build<'d, 'a> {
}
}
/// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be.
fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint {
let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh);
let first = rgb(g.first);
let second = match g.second {
Second::Col(c) => rgb(c),
Second::Tint(t) => Grad::tinted(first, t),
};
let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect();
let mut geom = g.geom;
geom.transform(map, g.kind);
let mut paint = GradientPaint::new(Gradient::new(g.kind, stops));
paint.angle = geom.angle_deg();
paint.geom = Some(geom);
Paint::Gradient(Box::new(paint))
}
/// What a block placed by an insert with `p` inherits.
fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit {
Inherit {
@@ -479,16 +660,75 @@ impl<'d, 'a> Build<'d, 'a> {
return None;
}
let mut node = match &it.geom {
Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?,
Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?,
Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?,
Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?,
Geom::Text(t) => self.text(t, &it.props, map, inh)?,
Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth),
Geom::Image(im) => self.image(im, map)?,
};
node.opacity = self.opacity(&it.props, inh);
self.nodes += 1;
Some(node)
}
fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
/// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no
/// length go on a path of their own with round caps, grouped with the dashes, which keep
/// butt caps and their lengths.
fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
if !dots {
return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh);
}
let (mut dashes, mut points) = (BezPath::new(), BezPath::new());
let (mut dash_count, mut dot_count) = (0usize, 0usize);
let mut from = None;
for el in bp.elements() {
match *el {
PathEl::MoveTo(a) => from = Some(a),
PathEl::LineTo(b) => {
if let Some(a) = from {
let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) };
out.move_to(a);
out.line_to(b);
*count += 1;
}
}
_ => {}
}
}
if dashes.elements().is_empty() {
return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh);
}
if points.elements().is_empty() {
return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
}
// Every object the split makes: the group (`item` counts it), the two paths, and each
// piece of a path with more than one (`path` counts those).
let loops = |count: usize| if count > 1 { count } else { 0 };
if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) {
self.warn(TOO_MANY);
return None;
}
if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) {
self.warn(TOO_MANY_POINTS);
return None;
}
// A split that loses either path is left out whole, and charges nothing.
let (nodes, elements) = (self.nodes, self.elements);
let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh));
let (Some(lines), Some(dots)) = (lines, dots) else {
(self.nodes, self.elements) = (nodes, elements);
return None;
};
self.nodes += 2;
Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)]))
}
/// A path painted as `look` says; `width`: a line's width in drawing units (0: the
/// lineweight).
fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
let fill = matches!(look, Look::Fill | Look::Gradient(_));
let n = bp.elements().len();
if self.elements.saturating_add(n) > MAX_ELEMENTS {
self.warn(TOO_MANY_POINTS);
@@ -498,7 +738,14 @@ impl<'d, 'a> Build<'d, 'a> {
let mut bp = bp.clone();
bp.apply_affine(map);
super::curve::bounds(&bp)?;
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
let paint = match look {
Look::Gradient(g) => self.gradient(g, p, map, inh),
_ => Paint::solid(rgb_color(self.rgb(p, inh))),
};
let pattern = match look {
Look::Pattern { dots } => Some(dots),
_ => None,
};
let scale = map.determinant().abs().sqrt();
let path = PathData::from_bezpath(&bp);
// A compound path's loops each keep a copy of its appearance, beside its own.
@@ -515,7 +762,14 @@ impl<'d, 'a> Build<'d, 'a> {
f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale
};
let mut ap = Appearance::basic(Paint::None, paint, w);
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
// Pattern lines carry their own dashes; dots of no length show with round caps.
if let Some(dots) = pattern {
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
&& dots
{
s.cap = LineCap::Round;
}
} else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
{
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
@@ -590,6 +844,92 @@ impl<'d, 'a> Build<'d, 'a> {
Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj))))
}
/// The non-empty, trimmed file path that image `im`'s IMAGEDEF names.
fn image_file(&self, im: &ImageItem) -> Option<String> {
im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty())
}
/// The size in pixels of image `im`: its own, else its file's as its IMAGEDEF gives it.
fn image_size(&self, im: &ImageItem) -> Option<(f64, f64)> {
let def = im.def.and_then(|h| self.d.images.get(&h)).map_or([0.0; 2], |f| f.size);
let size = if im.size.iter().all(|v| *v >= 1.0) { im.size } else { def };
let [w, h] = size.map(f64::round);
[w, h].iter().all(|v| (1.0..=MAX_IMAGE_SIDE).contains(v)).then_some((w, h))
}
/// A raster image, linked to the file its IMAGEDEF names (the path as the drawing stores it,
/// found from the drawing's folder when the document opens): until the file is read it shows
/// a placeholder over its pixels. A clip boundary makes it a clip group.
fn image(&mut self, im: &ImageItem, map: Affine) -> Option<Node> {
let Some(path) = self.image_file(im) else {
self.warn(NO_IMAGE_FILE);
return None;
};
let Some((w, h)) = self.image_size(im) else {
self.warn(IMAGE_SIZE);
return None;
};
let xf = map * im.placement(h);
if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) {
return None;
}
// The clip boundary, unless it shows the whole image. Its path and the image are objects of
// their own (`item` counts the group), and its points and the close are path elements: both
// are checked against the limits before the points are read.
let clip = im.clip.as_ref().filter(|c| !covers(c, w, h));
let elements = clip.map_or(0, |c| c.len().saturating_add(1));
if clip.is_some() && self.nodes.saturating_add(2) >= MAX_NODES {
self.warn(TOO_MANY);
return None;
}
if self.elements.saturating_add(elements) > MAX_ELEMENTS {
self.warn(TOO_MANY_POINTS);
return None;
}
// In document space, or in a symbol's own space, where each instance places it.
let clip: Option<Vec<Point>> = clip.map(|c| c.iter().map(|p| xf * *p).collect());
let local = self.in_symbol > 0;
let limit = if local { MAX_SYMBOL_EXTENT } else { MAX_EXTENT };
let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= limit && p.y.abs() <= limit;
if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) {
self.warn(FAR_CLIPS);
return None;
}
// Each image keeps its own copy of the path.
if !self.charge_text(path.len()) {
return None;
}
let key = format!("{IMAGE_KEY}{}", vectorcraft_doc::links::hash_bytes(path.as_bytes()));
if !self.doc.images.contains_key(&key) {
let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder()?);
let blob = ImageBlob {
mime: vectorcraft_doc::links::PROXY_MIME.into(),
bytes: bytes.clone(),
proxy: Some(bytes),
file_font: Default::default(),
};
self.doc.images.insert(key.clone(), blob);
}
let (w_px, h_px) = (w as u32, h as u32);
let image = ImageObject { key, width: w_px, height: h_px, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None };
let image = Node::new(self.doc.alloc_id(), NodeKind::Image(Box::new(image)));
let Some(clip) = clip else { return Some(image) };
// A symbol's clips are checked where each of its instances places them.
if local && let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) {
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
}
self.nodes += 2;
self.elements += elements;
let mut bp = BezPath::new();
for (i, p) in clip.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
}
bp.close_path();
let path = PathData::from_bezpath(&bp);
let clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false });
Some(Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }))
}
/// An insert: a symbol instance per copy (anonymous blocks: a group of their art), grouped
/// with its attributes.
fn insert(&mut self, ins: &InsertItem, p: &Props, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
@@ -597,11 +937,53 @@ impl<'d, 'a> Build<'d, 'a> {
let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base);
let unbase = Affine::translate(-base.to_vec2());
let anonymous = ins.block.starts_with('*');
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth) };
// An empty symbol is drawn again only for a cell that places an instance of it.
let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) };
// The symbol's art when this insert took it out.
let mut taken = None;
let mut parts = vec![];
for cell in &ins.cells {
let node = match &symbol {
Some(name) => {
let xf = map * *cell * self.symbol_map.inverse();
// Its image clips where this instance places them: inside another symbol, their
// box joins that symbol's; else, when it may leave the canvas, this placement
// draws the block's art, which checks each clip where it lands.
let reach_of = |b: &Self| b.symbol_reach.get(name).map(|r| placed_reach(xf, *r));
let leaves =
|r: Option<Rect>| r.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT));
let mut reach = reach_of(self);
// An empty symbol is drawn again (or its taken art put back) unless this placement
// draws the art anyway; the art drawn again may reach further.
if self.empty.contains(name) && (self.in_symbol > 0 || !leaves(reach)) {
if self.nodes >= MAX_NODES {
self.warn(TOO_MANY);
break;
}
let back = taken.take().is_some_and(|art| self.restore(name, art));
if !back && self.symbol(&ins.block, &child, depth, true).is_none() {
continue;
}
reach = reach_of(self);
}
// Joins the enclosing symbol's box once the instance is kept.
let inside = reach.filter(|_| self.in_symbol > 0);
if inside.is_none() && leaves(reach) {
// This placement draws the art instead of the symbol. The art of a symbol
// no instance places yet is taken out, so that it isn't kept and charged
// as well; an instance in a later cell puts it back.
if taken.is_none() {
taken = self.take_unused(name);
}
if self.nodes >= MAX_NODES {
self.warn(TOO_MANY);
break;
}
parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth));
continue;
}
// Checked here, after the art drawn in its place: that art gets back the
// share of an unused symbol.
if self.nodes >= MAX_NODES {
self.warn(TOO_MANY);
break;
@@ -609,7 +991,10 @@ impl<'d, 'a> Build<'d, 'a> {
if !self.charge_text(name.len()) {
break;
}
let xf = map * *cell * self.symbol_map.inverse();
if let Some(b) = inside {
self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b)));
}
*self.uses.entry(name.clone()).or_default() += 1;
self.nodes += 1;
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
}
@@ -664,30 +1049,124 @@ impl<'d, 'a> Build<'d, 'a> {
}
}
/// The symbol for block `name` placed with `inh` (made once per look).
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32) -> Option<String> {
/// The symbol for block `name` placed with `inh` (made once per look). One whose art was
/// taken out is drawn again when `draw` is set, and else returned empty.
fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option<String> {
let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() };
let key = (name.to_string(), inh);
if let Some(s) = self.symbols.get(&key) {
return s.clone();
}
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
let map = self.symbol_map * Affine::translate(-base.to_vec2());
let art = self.art(name, map, &key.1, depth);
let made = art.and_then(|art| {
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
// The symbol keeps its name: text, as its instances' copies of it are.
if !self.charge_text(label.len()) {
return None;
let s = s.clone()?;
if !draw || !self.empty.contains(&s) {
return Some(s);
}
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i));
return match (art, slot) {
(Some(art), Some(slot)) => {
slot.art = Arc::new(art);
self.symbol_cost.insert(s.clone(), cost);
match reach {
Some(b) => self.symbol_reach.insert(s.clone(), b),
None => self.symbol_reach.remove(&s),
};
self.empty.remove(&s);
Some(s)
}
// Nothing of it fits now: what it took goes back, and it stays empty.
_ => {
self.set_cost(self.cost().minus(cost));
self.nested = self.nested.minus(cost);
None
}
};
}
let (art, reach, cost) = self.symbol_art(name, &key.1, depth);
let made = art.map(|art| {
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
self.symbol_names.insert(symbol.clone());
if let Some(b) = reach {
self.symbol_reach.insert(symbol.clone(), b);
}
self.symbol_slot.insert(symbol.clone(), self.doc.symbols.len());
self.symbol_cost.insert(symbol.clone(), cost);
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
Some(symbol)
symbol
});
self.symbols.insert(key, made.clone());
made
}
/// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and
/// what it took from the limits itself (not the symbols made while drawing it, which other
/// instances may use).
fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option<Node>, Option<Rect>, Cost) {
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
let map = self.symbol_map * Affine::translate(-base.to_vec2());
let outer = self.clip_reach.take();
let before = self.cost();
let outer_nested = std::mem::take(&mut self.nested);
self.in_symbol += 1;
let art = self.art(name, map, inh, depth);
self.in_symbol -= 1;
let reach = std::mem::replace(&mut self.clip_reach, outer);
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()).len();
// The symbol keeps its name: text, as its instances' copies of it are.
let art = art.filter(|_| self.charge_text(label));
let total = self.cost().minus(before);
let own = total.minus(self.nested);
self.nested = outer_nested.plus(total);
(art, reach, own)
}
}
/// The box of `r` placed by `xf`. A box that is not finite, or whose placed corners are not (an
/// overflow, which a union or a bounding box would drop as NaN), is the whole plane, so every
/// placement of it is out of range.
pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|p| xf * p);
match corners.iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
true => corners.iter().fold(Rect::from_points(corners[0], corners[0]), |b, p| b.union_pt(*p)),
false => Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY),
}
}
/// The symbol of each instance in `art`, once per instance.
fn placed_symbols(art: &Node) -> Vec<String> {
let mut out = vec![];
art.walk(&mut |n: &Node| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
out.push(symbol.clone());
}
});
out
}
/// Every symbol of `doc` that no instance on its layers places, directly or through other
/// symbols, removed.
fn drop_unplaced_symbols(doc: &mut Document) {
let index: HashMap<&str, usize> = doc.symbols.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect();
let mut placed = vec![false; doc.symbols.len()];
let mut todo: Vec<usize> = vec![];
// Each symbol is queued once, however many instances place it.
let note = |n: &Node, placed: &mut Vec<bool>, todo: &mut Vec<usize>| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& let Some(&i) = index.get(symbol.as_str())
&& let Some(seen) = placed.get_mut(i)
&& !*seen
{
*seen = true;
todo.push(i);
}
};
doc.walk(|n| note(n, &mut placed, &mut todo));
while let Some(i) = todo.pop() {
if let Some(s) = doc.symbols.get(i) {
s.art.walk(&mut |n: &Node| note(n, &mut placed, &mut todo));
}
}
let mut keep = placed.into_iter();
doc.symbols.retain(|_| keep.next().unwrap_or(false));
}
/// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span
@@ -704,6 +1183,22 @@ fn fill_span(obj: &mut TextObject, span: Span, s: f64) {
}
}
/// Does clip boundary `clip` (pixel space) show the whole `w` × `h` image: is it a rectangle
/// square to the image that holds it?
fn covers(clip: &[Point], w: f64, h: f64) -> bool {
if clip.len() != 4 || clip.iter().enumerate().any(|(i, p)| clip[..i].contains(p)) {
return false;
}
let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { return false };
let corner = |p: &Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1);
// Each point a distinct corner, and each edge along one side: the four corners in order around.
let side = |i: usize| {
let (p, q) = (clip[i], clip[(i + 1) % clip.len()]);
(p.x == q.x) != (p.y == q.y)
};
clip.len() == 4 && clip.iter().all(corner) && (0..4).all(side) && b.x0 <= 0.0 && b.y0 <= 0.0 && b.x1 >= w && b.y1 >= h
}
fn rgb_color([r, g, b]: [u8; 3]) -> Color {
Color::rgb8(r, g, b)
}
@@ -735,3 +1230,59 @@ fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n";
fn props() -> Props {
Props {
layer: "0".into(),
color: Col::Rgb([0, 0, 0]),
lineweight: Lw::Default,
linetype: "CONTINUOUS".into(),
ltscale: 1.0,
alpha: Alpha::Opacity(1.0),
}
}
/// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements.
fn mixed() -> BezPath {
let mut bp = BezPath::new();
for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] {
bp.move_to(a);
bp.line_to(b);
}
bp
}
#[test]
fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() {
let (tags, _) = super::super::tags(EMPTY).unwrap();
let d = Drawing::read(craft_dxf::model::Document::read(&tags));
let o = ImportOptions::default();
let (p, inh) = (props(), Inherit::default());
// Seven objects with six slots free: refused; with seven: drawn, the group left to `item`.
let mut b = Build::new(&d, &o);
b.nodes = MAX_NODES - 6;
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
assert_eq!(b.nodes, MAX_NODES - 6);
b.nodes = MAX_NODES - 7;
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some());
assert_eq!(b.nodes, MAX_NODES - 1);
// Eight points with seven left: refused without charging them, so a 4-point path that
// follows still fits.
let mut b = Build::new(&d, &o);
b.elements = MAX_ELEMENTS - 7;
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
assert_eq!(b.elements, MAX_ELEMENTS - 7);
let mut line = BezPath::new();
line.move_to((0.0, 0.0));
line.line_to((1.0, 0.0));
line.line_to((1.0, 1.0));
line.line_to((0.0, 1.0));
assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some());
}
}
+406 -24
View File
@@ -1,15 +1,18 @@
//! Entities to drawing items: their geometry in world coordinates (drawing units, y up) and the
//! properties they take from their layer or block (resolved when the items become art).
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use kurbo::{BezPath, PathEl};
use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape};
use vectorcraft_doc::Justify;
use vectorcraft_geom::{Affine, Point, Vec2};
use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
use super::acis;
use super::curve::{self, Vertex};
use super::hatch::{self, Grad, NoPattern};
use super::reader::{aci_paper, point};
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
@@ -20,6 +23,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0;
const MAX_CELLS: i64 = 10_000;
/// The most copies all the array inserts of a file make together.
const MAX_TOTAL_CELLS: i64 = 2_000_000;
/// The most winding steps for island nesting: loops times boundary elements times samples.
const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 };
/// The most segment midpoints sampled just inside each loop for island nesting.
const MAX_ISLAND_SAMPLES: usize = 16;
/// Art farther than this from the origin (drawing units) is damaged data, left out.
const MAX_COORD: f64 = 1e12;
/// How far fit and aligned text may be squeezed or stretched to span their two points: at width
@@ -146,6 +153,31 @@ pub(crate) struct InsertItem {
pub attribs: Vec<Item>,
}
/// A raster image: the file its IMAGEDEF names, shown on a parallelogram.
#[derive(Clone, Debug)]
pub(crate) struct ImageItem {
/// The handle of its IMAGEDEF.
pub def: Option<u64>,
/// The lower-left corner, and one pixel along the width and up the height (world
/// coordinates, drawing units).
pub insert: Point,
pub u: Vec2,
pub v: Vec2,
/// Its size in pixels (0: its IMAGEDEF's).
pub size: [f64; 2],
/// The clip boundary in pixel space ([`ImageItem::placement`]); `None`: the whole image.
pub clip: Option<Vec<Point>>,
}
impl ImageItem {
/// Pixel space (the top-left corner at the origin, x right, y down, one unit a pixel) to world
/// coordinates, for an image `height` pixels high.
pub fn placement(&self, height: f64) -> Affine {
let top = self.insert + self.v * height;
Affine::new([self.u.x, self.u.y, -self.v.x, -self.v.y, top.x, top.y])
}
}
#[derive(Clone, Debug)]
pub(crate) enum Geom {
/// A path in world coordinates; `fill`: a filled area (hatch, solid), else a line of
@@ -155,8 +187,24 @@ pub(crate) enum Geom {
fill: bool,
width: f64,
},
/// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates).
Shaded {
bp: BezPath,
shade: Shade,
},
Text(TextItem),
Insert(InsertItem),
Image(ImageItem),
}
/// How a [`Geom::Shaded`] path paints.
#[derive(Clone, Debug)]
pub(crate) enum Shade {
/// The area filled with a gradient.
Gradient(Box<Grad>),
/// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no
/// length and need round caps to show.
Pattern { dots: bool },
}
/// An entity as art: its geometry and its properties.
@@ -174,16 +222,36 @@ pub(crate) struct Converter {
pub warnings: Vec<String>,
/// Array insert copies made so far, against [`MAX_TOTAL_CELLS`].
cells: i64,
/// The pattern budget shared by entity sections and blocks.
patterns: hatch::Budget,
/// The binary solid-modeler data of regions, by handle (DXF 2013 and later).
regions: Rc<HashMap<u64, Vec<u8>>>,
}
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
const MESHES: &str = "3D polygon meshes and polyface meshes are left out";
const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries";
const DENSE_PATTERN: &str =
"pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries";
const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries";
const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries";
const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary";
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
const FLAT_IMAGES: &str = "images with no width or height are left out";
const IMAGE_ADJUSTMENTS: &str = "the brightness, contrast and fade of images are left out";
const OPAQUE_IMAGES: &str = "images set to show opaque keep their file's transparency";
const INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole";
const REGION_CURVES: &str = "region edges of some curve types come in as straight lines";
const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines";
const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve";
impl Converter {
/// A converter reading regions' binary data from `regions`.
pub fn new(regions: Rc<HashMap<u64, Vec<u8>>>) -> Self {
Self { regions, ..Self::default() }
}
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
@@ -203,7 +271,7 @@ impl Converter {
if !m.common.visible {
continue;
}
match self.geom(e, &m) {
match self.geom(e, &m).map(usable_paint) {
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
None if is_known(e.kind) => {}
@@ -233,15 +301,21 @@ impl Converter {
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
}
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs),
model::EntityKind::Spline(s) => path(spline(s)?),
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
let [a, b, c, d] = corners.map(point);
// The corners zigzag: the outline runs 1, 2, 4, 3.
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
}
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
model::EntityKind::Face3d { corners, hidden_edges } => {
// Bit n of group 70 hides the edge from corner n.
let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect();
let mut bp = BezPath::new();
face(&mut bp, &corners);
(!bp.elements().is_empty()).then_some(bp).and_then(path)
}
model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color),
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
@@ -249,15 +323,45 @@ impl Converter {
model::EntityKind::Dimension(d) => {
Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] }))
}
// Group 70 without its Show Image bit: a hidden image (an IMAGE without group 70 shows).
model::EntityKind::Image(_) if g.i(70).is_some_and(|flags| flags & 1 == 0) => None,
model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()),
_ if e.kind == "REGION" => self.region(e),
_ => None,
}
}
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
if p.is_mesh() || p.is_polyface() {
self.warn(MESHES);
/// An IMAGE (its points are in world coordinates).
fn image(&mut self, im: &model::Image, has_display: bool) -> Option<Geom> {
let (u, v) = (point(im.u).to_vec2(), point(im.v).to_vec2());
let area = u.cross(v);
if !(area.is_finite() && area != 0.0) {
self.warn(FLAT_IMAGES);
return None;
}
if (im.brightness, im.contrast, im.fade) != (50, 50, 0) {
self.warn(IMAGE_ADJUSTMENTS);
}
if has_display && im.display & 8 == 0 {
self.warn(OPAQUE_IMAGES);
}
let clip = if !im.clipping || (has_display && im.display & 4 == 0) {
None
} else if im.clip_inverted {
self.warn(INVERTED_CLIPS);
None
} else {
image_clip(im)
};
Some(Geom::Image(ImageItem { def: im.image_def, insert: point(im.insert), u, v, size: im.size, clip }))
}
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
// Meshes are in world coordinates, seen from above.
if p.is_polyface() || p.is_mesh() {
let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?;
return Some(Geom::Path { bp, fill: false, width: 0.0 });
}
// Spline frame control points and polyface faces aren't on the line.
let verts: Vec<Vertex> =
p.vertices.iter().filter(|v| v.flags & (16 | 128) == 0).map(|v| Vertex { p: point(v.location), bulge: v.bulge }).collect();
@@ -267,6 +371,60 @@ impl Converter {
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
}
/// A polyface mesh's faces: each one's visible edges, closed when all of them are.
fn polyface(&mut self, p: &model::Polyline) -> Option<BezPath> {
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect();
let mut bp = BezPath::new();
for f in p.vertices.iter().filter(|v| v.is_face()) {
// Vertex numbers count from 1, negative when the edge from that vertex is hidden;
// 0 ends a triangle's list.
let corners: Option<Vec<(Point, bool)>> = f
.face
.iter()
.take_while(|n| **n != 0)
.map(|n| {
let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?;
Some((*points.get(i)?, *n > 0))
})
.collect();
match corners {
Some(corners) => face(&mut bp, &corners),
None => self.warn(MESH_VERTICES),
}
}
(!bp.elements().is_empty()).then_some(bp)
}
/// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a
/// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame.
fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option<BezPath> {
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect();
let size = |m: i64, n: i64| {
let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?);
(m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n))
};
let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0)));
// Without the frame's vertices only the surface's counts describe the grid.
let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) {
size(surface.0, surface.1)
} else {
size(frame.0, frame.1).or_else(|| size(surface.0, surface.1))
};
let Some((m, n)) = dims else {
self.warn(MESH_VERTICES);
return None;
};
let mut bp = BezPath::new();
for row in points.chunks(n) {
line(&mut bp, row, p.flags & 32 != 0);
}
for col in 0..n {
let pts: Vec<Point> = (0..m).map(|r| points[r * n + col]).collect();
line(&mut bp, &pts, p.closed());
}
(!bp.elements().is_empty()).then_some(bp)
}
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
let [sx, sy, _] = ins.scale;
@@ -317,27 +475,188 @@ impl Converter {
out
}
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
let mut bp = BezPath::new();
/// A region as a filled path: its solid-modeler data as text in groups 1 (a line each) and 3
/// (the rest of a long line), or, from DXF 2013 on, binary data kept by handle.
fn region(&mut self, e: &EntityRecord<'_>) -> Option<Geom> {
let g = e.groups();
let own = g.subclass("AcDbModelerGeometry");
let tags = if own.0.is_empty() { g.0 } else { own.0 };
let mut text = String::new();
for t in tags {
match t.code {
1 => {
if !text.is_empty() {
text.push('\n');
}
text.push_str(t.str_ref().unwrap_or_default());
}
3 => text.push_str(t.str_ref().unwrap_or_default()),
_ => {}
}
if text.len() > acis::MAX_BYTES {
return None;
}
}
let outline = if text.trim().is_empty() { acis::from_binary(self.regions.get(&e.record().handle()?)?) } else { acis::from_text(&text) }?;
if outline.approximated {
self.warn(REGION_CURVES);
}
if outline.broken {
self.warn(REGION_BROKEN);
}
if outline.ambiguous {
self.warn(REGION_AMBIGUOUS);
}
Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 })
}
/// A hatch's art; `own`: its color, which a gradient without color records takes.
fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> {
let mut loops = Vec::new();
for l in &h.loops {
let Some(path) = boundary(&l.path) else { break };
bp.extend(path);
loops.push(path);
}
let mut max_depth = match h.style {
1 => Some(1),
2 => Some(0),
_ => None,
};
if max_depth.is_some() {
let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len()));
// Count each loop's samples against every loop, including its own containment checks.
if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK {
self.warn(MUCH_ISLAND_WORK);
max_depth = None;
}
}
let nesting: Vec<_> = if max_depth.is_some() {
loops
.iter()
.map(|path| {
let bounds = path.bounding_box();
// Center each loop independently so distant loops do not erase small geometry.
let center = bounds.center();
let local = transformed(path.clone(), Affine::translate(-center.to_vec2()));
let area = local.area();
// Area divided by perimeter measures thickness independently of the loop's rotation.
let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3);
let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 };
let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1);
let mut samples: Vec<_> = local
.segments()
.step_by(step)
.filter_map(|segment| {
let tangent = match segment {
PathSeg::Line(line) => line.deriv().eval(0.5),
PathSeg::Quad(quad) => quad.deriv().eval(0.5),
PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5),
}
.to_vec2();
let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() };
let length = tangent.hypot();
if length == 0.0 {
return None;
}
// Positive area puts the interior to the left of the tangent in y-up coordinates.
Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length))
})
.take(MAX_ISLAND_SAMPLES)
.filter(|sample| local.winding(*sample) != 0)
.collect();
if samples.is_empty()
&& let Some(PathEl::MoveTo(first)) = local.elements().first()
{
samples.push(*first);
}
(bounds, center, local, area.abs(), samples)
})
.collect()
} else {
Vec::new()
};
let mut bp = BezPath::new();
for (i, path) in loops.iter().enumerate() {
if let Some(limit) = max_depth {
let (bounds, center, _, area, samples) = &nesting[i];
// Require geometric containment and a majority of samples so a shared
// edge or a single vertex on the boundary does not decide nesting.
let depth = nesting
.iter()
.enumerate()
.filter(|(j, _)| {
let (other_bounds, other_center, other, other_area, _) = &nesting[*j];
let offset = *center - *other_center;
*j != i
&& area < other_area
&& bounds.x0 >= other_bounds.x0
&& bounds.y0 >= other_bounds.y0
&& bounds.x1 <= other_bounds.x1
&& bounds.y1 <= other_bounds.y1
&& samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2
})
.count();
if depth > limit {
continue;
}
}
bp.extend(path.iter());
}
if bp.elements().is_empty() {
return None;
}
let bp = transformed(bp, ocs);
if h.gradient.is_some() {
self.warn(GRADIENT_HATCH);
} else if !h.solid {
self.warn(PATTERN_HATCH);
return Some(Geom::Path { bp, fill: false, width: 0.0 });
if let Some(g) = &h.gradient {
let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g)));
let bp = transformed(bp, ocs);
return Some(match shade {
Some(shade) => Geom::Shaded { bp, shade },
None => Geom::Path { bp, fill: true, width: 0.0 },
});
}
if h.solid {
return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 });
}
// The pattern lines are in the hatch's plane, as its boundary is.
let doubled;
let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 {
doubled = hatch::doubled(&h.pattern_lines);
&doubled
} else {
&h.pattern_lines
};
match hatch::pattern(lines, &bp, &mut self.patterns) {
Ok((lines, _)) if lines.elements().is_empty() => None,
Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }),
Err(why) => {
self.warn(match why {
NoPattern::Undefined => PATTERN_HATCH,
NoPattern::TooDense => DENSE_PATTERN,
NoPattern::DrawingPieces => MANY_PATTERNS,
NoPattern::DrawingWork => MUCH_PATTERN_WORK,
});
Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 })
}
}
Some(Geom::Path { bp, fill: true, width: 0.0 })
}
}
/// Is the geometry within [`MAX_COORD`] of the origin?
/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill.
fn usable_paint(g: Geom) -> Geom {
match g {
Geom::Shaded { bp, shade: Shade::Gradient(grad) } => {
let geom = &grad.geom;
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) {
Geom::Shaded { bp, shade: Shade::Gradient(grad) }
} else {
Geom::Path { bp, fill: true, width: 0.0 }
}
}
g => g,
}
}
/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it.
fn in_range(g: &Geom) -> bool {
let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD;
let origin = |m: &Affine| near(m.translation().to_point());
@@ -345,8 +664,30 @@ fn in_range(g: &Geom) -> bool {
Geom::Path { bp, width, .. } => {
curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD
}
Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))),
Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD,
Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)),
Geom::Image(i) => {
let [w, h] = i.size;
let far = i.insert + i.u * w + i.v * h;
near(i.insert) && near(far) && [i.u.x, i.u.y, i.v.x, i.v.y, w, h].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
}
}
}
/// The clip boundary of IMAGE `im` in pixel space ([`ImageItem::placement`]): two opposite corners
/// of a rectangle, or a polygon of three points or more. The boundary's points are pixel centres
/// counted from the top-left pixel, so the image's own corners are at (−0.5, −0.5) and
/// (width − 0.5, height − 0.5). `None` when it has too few points.
fn image_clip(im: &model::Image) -> Option<Vec<Point>> {
let pts: Vec<Point> = im.clip.iter().map(|[x, y]| Point::new(x + 0.5, y + 0.5)).collect();
match pts.as_slice() {
[a, b] if im.clip_type == 1 => {
let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y));
Some(vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
}
p if p.len() >= 3 => Some(p.to_vec()),
_ => None,
}
}
@@ -370,6 +711,7 @@ fn is_known(kind: &str) -> bool {
| "MTEXT"
| "INSERT"
| "DIMENSION"
| "IMAGE"
| "ATTDEF"
| "SEQEND"
| "VERTEX"
@@ -398,6 +740,46 @@ fn polygon(pts: &[Point]) -> BezPath {
bp
}
/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points).
fn line(bp: &mut BezPath, pts: &[Point], closed: bool) {
if pts.len() < 2 {
return;
}
for (i, p) in pts.iter().enumerate() {
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
}
if closed {
bp.close_path();
}
}
/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is
/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open
/// line.
fn face(bp: &mut BezPath, corners: &[(Point, bool)]) {
let pts: Vec<Point> = corners.iter().map(|c| c.0).collect();
let Some(hidden) = corners.iter().position(|c| !c.1) else {
line(bp, &pts, true);
return;
};
// Start after a hidden edge, so that no run is split where the list wraps.
let n = corners.len();
let mut run: Vec<Point> = Vec::new();
for k in 1..=n {
let i = (hidden + k) % n;
if corners[i].1 {
if run.is_empty() {
run.push(pts[i]);
}
run.push(pts[(i + 1) % n]);
} else {
line(bp, &run, false);
run.clear();
}
}
line(bp, &run, false);
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
@@ -500,7 +882,7 @@ fn boundary(path: &HatchPath) -> Option<BezPath> {
}
/// `seg` continuing `bp`: joined by a line when it starts elsewhere.
fn append(bp: &mut BezPath, seg: &BezPath) {
pub(super) fn append(bp: &mut BezPath, seg: &BezPath) {
for el in seg.elements() {
match *el {
PathEl::MoveTo(p) => {
+847
View File
@@ -0,0 +1,847 @@
//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut
//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own
//! plane (its object coordinate system), where the boundary and the pattern lines are given.
use kurbo::{BezPath, PathEl};
use vectorcraft_color::{GradientGeom, GradientKind};
use vectorcraft_geom::{Affine, Point, Vec2};
use craft_dxf::model::{self, PatternLine};
use super::entity::Col;
use super::reader::aci_paper;
/// The most dashes and dots one pattern hatch draws.
pub(crate) const MAX_PIECES: usize = 20_000;
/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened.
const MAX_EDGES: usize = 200_000;
/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary
/// edge, and each dash, gap or dot looked at one more.
const MAX_WORK: usize = 20_000_000;
/// The most dashes and dots all pattern hatches draw together.
pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 };
/// The most clipping and dash steps all pattern hatches take together.
pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 };
/// How far flattened boundary curves may stray, as a fraction of their loop's larger side.
const FLATNESS: f64 = 1e-4;
/// Spans, line spacings and dash periods shorter than this many units of the last place of their
/// coordinates count as none.
const LOCAL_TINY: f64 = 64.0 * f64::EPSILON;
/// Why a pattern hatch is not drawn as its pattern.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum NoPattern {
/// The hatch holds no pattern lines.
Undefined,
/// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or
/// [`MAX_WORK`] steps.
TooDense,
/// The drawing reaches its total piece limit.
DrawingPieces,
/// The drawing reaches its total work limit.
DrawingWork,
}
/// The remaining pattern budget; discarded patterns also use it.
pub(crate) struct Budget {
pieces: usize,
work: usize,
stopped: Option<NoPattern>,
}
impl Default for Budget {
fn default() -> Self {
Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None }
}
}
impl Budget {
fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> {
if *pieces >= MAX_PIECES {
return Err(NoPattern::TooDense);
}
if self.pieces == 0 {
self.stopped = Some(NoPattern::DrawingPieces);
return Err(NoPattern::DrawingPieces);
}
*pieces += 1;
self.pieces -= 1;
Ok(())
}
fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> {
if steps > MAX_WORK - *work {
return Err(NoPattern::TooDense);
}
if steps > self.work {
self.stopped = Some(NoPattern::DrawingWork);
return Err(NoPattern::DrawingWork);
}
*work += steps;
self.work -= steps;
Ok(())
}
}
/// Adds a perpendicular family when the pattern holds only one family.
pub(crate) fn doubled(lines: &[PatternLine]) -> Vec<PatternLine> {
let mut out = lines.to_vec();
if let [line] = lines {
out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() });
}
out
}
/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill):
/// each family's lines, cut into dashes and dots that start from the line's own base point.
/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot.
pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> {
if lines.is_empty() {
return Err(NoPattern::Undefined);
}
let exhausted = if budget.pieces == 0 {
Some(NoPattern::DrawingPieces)
} else if budget.work == 0 {
Some(NoPattern::DrawingWork)
} else {
None
};
if let Some(why) = budget.stopped.or(exhausted) {
budget.stopped = Some(why);
return Err(why);
}
let mut out = BezPath::new();
let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) };
let size = b.width().max(b.height());
if !(size > 0.0 && size.is_finite()) {
return Ok((out, false));
}
let edges = edges(boundary)?;
if edges.is_empty() {
return Ok((out, false));
}
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
let center = b.center();
// The precision of the boundary's coordinates: spacings and periods below it draw nothing apart.
let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size);
let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false);
for l in lines {
let a = l.angle.to_radians();
let d = Vec2::new(a.cos(), a.sin());
let n = Vec2::new(-d.y, d.x);
let base = Point::new(l.base[0], l.base[1]);
let offset = Vec2::new(l.offset[0], l.offset[1]);
let step = offset.dot(n);
// A family with numbers out of range is damaged: the others still draw.
if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) {
continue;
}
usable = true;
// Lines no distance apart, or closer than the coordinates can tell apart, fill the area
// past what can be drawn.
if step.abs() <= tiny {
return Err(NoPattern::TooDense);
}
let period: f64 = l.dashes.iter().map(|v| v.abs()).sum();
if !l.dashes.is_empty() && period <= tiny {
return Err(NoPattern::TooDense);
}
// The same family from the line nearest the boundary's center, a whole number of offsets
// away. The base and the center are each measured from the line through the origin
// first, so a base far away keeps the fraction of the center's position.
let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n));
let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round());
let across = (bn + to_origin * step) + (to_center * step - cn);
let last = -(across / step).round();
let across = across + last * step;
// Where the dashes start on that line, from its point nearest the center. Each line is
// measured from its own point nearest the center, so its spans stay near the boundary
// however long the dash period is. Each term is reduced to within half a period before
// the terms are added, so a distant base or a large offset count keeps its remainder.
let od = offset.dot(d);
let along = if l.dashes.is_empty() {
0.0
} else {
let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od));
sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period)
};
if !(across.is_finite() && along.is_finite()) {
continue;
}
// The dash start nearest a line's point nearest the center, as a signed distance.
let phase = |k: f64| {
let [p, e] = product_parts(k, od);
sum_rem(&[along, p, e], period)
};
let base = center + n * across;
// The lines crossing the boundary's box: base + k * step along the normal for whole k.
let h = corners.map(|c| (c - base).dot(n) / step);
let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil();
let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor();
if hi < lo {
continue;
}
let count = hi - lo + 1.0;
if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 {
return Err(NoPattern::TooDense);
}
let mut t = Vec::new();
for k in (lo as i64)..=(hi as i64) {
budget.work(&mut work, edges.len())?;
let q = base + n * (step * k as f64);
crossings(&edges, q, d, n, &mut t);
for &[ta, tb] in t.as_chunks::<2>().0 {
// Spans of no length at the precision of their own coordinates are dropped.
if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) {
continue;
}
let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> {
budget.piece(&mut pieces)?;
out.move_to(q + d * s0);
out.line_to(q + d * s1);
Ok(())
};
if l.dashes.is_empty() {
emit(ta, tb, budget)?;
continue;
}
// The dashes run from the line's dash start, element by element, from the period
// the span starts in.
let start = phase(k as f64);
let mut at = start + ((ta - start) / period).floor() * period;
// Periods too short to move along the span, or more dashes than one hatch may
// look at, are refused before any of them is looked at.
let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64;
if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 {
return Err(NoPattern::TooDense);
}
// An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero.
let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> {
budget.work(&mut work, 1)?;
if v > 0.0 {
let (s0, s1) = (s.max(ta), e.min(tb));
if s1 > s0 {
emit(s0, s1, budget)?;
}
} else if v == 0.0 && s >= ta {
emit(s, s, budget)?;
dots = true;
}
Ok(())
};
// When that period starts on the span's start, or past it, the elements that end
// the period before are measured back from its end, so a dot there is kept and a
// long period does not move them. Each element's start and end are the distances
// summed back from that end, so a long element does not move its known end.
if at >= ta {
let (mut back, mut first) = (vec![0.0], l.dashes.len());
while first > 0 && at - back[back.len() - 1] >= ta {
first -= 1;
back.push(back[back.len() - 1] + l.dashes[first].abs());
}
for (i, v) in l.dashes[first..].iter().enumerate() {
let rest = back.len() - 1 - i;
element(at - back[rest], at - back[rest - 1], *v, budget)?;
}
}
'span: loop {
for v in &l.dashes {
if at > tb {
break 'span;
}
element(at, at + v.abs(), *v, budget)?;
at += v.abs();
}
}
}
}
}
if !usable {
return Err(NoPattern::Undefined);
}
Ok((out, dots))
}
/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps
/// are exact: the remainder of a division, then one period added or taken away.
fn near_rem(x: f64, period: f64) -> f64 {
let r = x % period;
if r > period / 2.0 {
r - period
} else if r < -period / 2.0 {
r + period
} else {
r
}
}
/// `a * b` as the rounded product and its rounding error, which add up to it exactly.
fn product_parts(a: f64, b: f64) -> [f64; 2] {
let p = a * b;
[p, a.mul_add(b, -p)]
}
/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term
/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so
/// a small term is kept when larger ones cancel.
fn sum_rem(terms: &[f64], period: f64) -> f64 {
let (mut hi, mut lo) = (0.0, 0.0);
for &t in terms {
let t = near_rem(t, period);
let s = hi + t;
let v = s - hi;
lo += (hi - (s - v)) + (t - v);
hi = s;
}
near_rem(near_rem(hi, period) + near_rem(lo, period), period)
}
/// The boundary's edges as straight segments, each loop closed and its curves flattened to
/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out.
fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> {
let mut loops: Vec<BezPath> = Vec::new();
for el in boundary.elements() {
if matches!(el, PathEl::MoveTo(_)) {
loops.push(BezPath::new());
}
if let Some(l) = loops.last_mut() {
l.push(*el);
}
}
let mut out = Vec::new();
let mut over = false;
let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| {
if out.len() >= MAX_EDGES {
over = true;
} else if a != b {
out.push((a, b));
}
};
for lp in &loops {
let Some(b) = super::curve::bounds(lp) else { continue };
let tolerance = b.width().max(b.height()) * FLATNESS;
if !(tolerance > 0.0 && tolerance.is_finite()) {
continue;
}
let (mut start, mut last) = (None::<Point>, None::<Point>);
kurbo::flatten(lp.iter(), tolerance, |el| match el {
PathEl::MoveTo(p) => {
start = Some(p);
last = Some(p);
}
PathEl::LineTo(p) => {
if let Some(l) = last {
push(l, p, &mut out);
}
last = Some(p);
}
PathEl::ClosePath => {
if let (Some(s), Some(l)) = (start, last) {
push(l, s, &mut out);
}
last = start;
}
_ => {}
});
if let (Some(s), Some(l)) = (start, last) {
push(l, s, &mut out);
}
}
if over { Err(NoPattern::TooDense) } else { Ok(out) }
}
/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances
/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves
/// the side the previous one came from.
fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec<f64>) {
t.clear();
for (p0, p1) in edges {
let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n));
if (h0 > 0.0) != (h1 > 0.0) {
let p = p0.lerp(*p1, h0 / (h0 - h1));
t.push((p - q).dot(d));
}
}
t.sort_by(f64::total_cmp);
}
/// The second color of a gradient: a color of its own, or for a one-color gradient the first
/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Second {
Col(Col),
Tint(f64),
}
/// A gradient hatch's fill, placed in world coordinates (drawing units, y up).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Grad {
pub kind: GradientKind,
/// Linear: where the first stop sits and the last; radial: the center, a point on the outer
/// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen
/// at a slant).
pub geom: GradientGeom,
pub first: Col,
pub second: Second,
/// Each stop's position and whether it takes the second color (else the first).
pub stops: Vec<(f32, bool)>,
}
impl Grad {
/// `first` shaded or tinted by `tint` (see [`Second::Tint`]).
pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] {
let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 };
let mix = |c: u8| {
let c = f64::from(c);
let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 };
v.round().clamp(0.0, 255.0) as u8
};
[mix(r), mix(g), mix(b)]
}
}
fn col(c: model::Color) -> Col {
match c {
model::Color::Rgb(rgb) => Col::Rgb(rgb),
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
model::Color::ByBlock => Col::ByBlock,
model::Color::ByLayer => Col::ByLayer,
}
}
/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world
/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle
/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way:
/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first;
/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same
/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the
/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift
/// moves the center up and left by up to a quarter of the extent.
pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option<Grad> {
let angle = if g.angle.is_finite() { g.angle } else { 0.0 };
let mut frame = boundary.clone();
frame.apply_affine(Affine::rotate(-angle));
let r = super::curve::bounds(&frame)?;
let (w, h) = (r.width(), r.height());
let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 };
let c = r.center() + Vec2::new(-w, h) * (shift / 4.0);
// How far the shift moves the center left and up.
let (dx, dy) = (c.x - r.center().x, c.y - r.center().y);
let name = g.name.trim().to_uppercase();
let (inverse, name) = match name.strip_prefix("INV") {
Some(rest) => (true, rest),
None => (false, name.as_str()),
};
let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::<Vec<_>>();
let (kind, start, end, stops) = match name {
"CYLINDER" => {
(GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)]))
}
"SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])),
"HEMISPHERICAL" => {
let center = Point::new(c.x, r.y0 + dy);
(GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)]))
}
"CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])),
_ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])),
};
let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None };
geom.transform(ocs * Affine::rotate(angle), kind);
let first = g.colors.first().map_or(own, |c| col(*c));
let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) };
Some(Grad { kind, geom, first, second, stops })
}
#[cfg(test)]
mod tests {
use super::*;
fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> {
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
super::pattern(lines, boundary, &mut budget)
}
#[test]
fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() {
let lines = [line(0.0, [0.0, 1.0], &[])];
let boundary = square(10.0);
let mut budget = Budget { pieces: 3, work: 100, stopped: None };
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
assert_eq!(budget.pieces, 0);
assert!(budget.work < 100);
let work = budget.work;
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
assert_eq!(budget.work, work, "later hatches do no clipping");
let mut budget = Budget { pieces: 100, work: 9, stopped: None };
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
assert_eq!(budget.work, 1, "two lines cost four edges each");
let pieces = budget.pieces;
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
assert_eq!((budget.work, budget.pieces), (1, pieces));
let gaps = [line(0.0, [0.0, 1.0], &[-0.01])];
let mut budget = Budget { pieces: 100, work: 20, stopped: None };
assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork));
assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces");
}
fn square(side: f64) -> BezPath {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((side, 0.0));
bp.line_to((side, side));
bp.line_to((0.0, side));
bp.close_path();
bp
}
fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine {
PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() }
}
#[test]
fn doubling_adds_a_perpendicular_family_only_when_one_is_present() {
let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]);
level.base = [2.0, 5.0];
let lines = doubled(&[level.clone()]);
let [first, second] = &lines[..] else { panic!("two families") };
assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes));
assert_eq!(second.angle, level.angle + 90.0);
assert_eq!(second.offset, [-level.offset[1], level.offset[0]]);
assert_eq!((second.base, &second.dashes), (level.base, &level.dashes));
let kept = doubled(&lines);
assert_eq!(kept.len(), lines.len());
for (a, b) in kept.iter().zip(&lines) {
assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes));
}
}
/// The pieces as (start, end) pairs.
fn pieces(bp: &BezPath) -> Vec<(Point, Point)> {
let mut out = vec![];
let mut from = Point::ZERO;
for el in bp.elements() {
match el {
PathEl::MoveTo(p) => from = *p,
PathEl::LineTo(p) => out.push((from, *p)),
_ => {}
}
}
out
}
#[test]
fn pattern_lines_stop_at_the_boundary_and_skip_holes() {
// Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square
// hole in the middle.
let mut boundary = square(100.0);
let mut hole = square(20.0);
hole.apply_affine(Affine::translate((40.0, 40.0)));
boundary.extend(hole);
let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] };
let (bp, dots) = pattern(&[l], &boundary).unwrap();
assert!(!dots);
let p = pieces(&bp);
// Ten lines, the two through the hole (y 45 and 55) each cut in two.
assert_eq!(p.len(), 12, "{p:?}");
for (a, b) in &p {
assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9);
}
let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect();
assert_eq!(middle.len(), 2);
assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}");
}
#[test]
fn dashes_start_at_each_lines_base_point() {
// Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them.
let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] };
let (bp, dots) = pattern(&[l], &square(100.0)).unwrap();
assert!(dots);
let p = pieces(&bp);
let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>();
let first = row(50.0);
assert!(first.len() > 4, "{first:?}");
// The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary.
assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]);
assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0));
}
#[test]
fn a_dash_across_the_boundary_is_cut_there() {
let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap();
let p = pieces(&bp);
assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9));
// The second dash, 40 to 70, crosses the boundary at 50 and stops there.
assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}");
assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}");
}
#[test]
fn short_spans_far_apart_keep_their_pieces_and_curves() {
// Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its
// one-unit spans.
let strip = |x: f64| {
let mut s = square(1.0);
s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0));
s
};
let mut boundary = strip(0.0);
boundary.extend(strip(1e10));
let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] };
let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap();
let p = pieces(&bp);
assert_eq!(p.len(), 4, "{p:?}");
assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}");
// Unit circles as far apart keep their round outlines: the line through y 0.5 spans
// 2 * sqrt(0.75) of each.
let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1);
let mut boundary = circle(0.0);
boundary.extend(circle(1e10));
let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] };
let (bp, _) = pattern(&[l], &boundary).unwrap();
let p = pieces(&bp);
assert_eq!(p.len(), 2, "{p:?}");
let chord = 2.0 * 0.75f64.sqrt();
assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}");
}
#[test]
fn close_lines_across_squares_far_apart_are_drawn() {
// Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square.
let mut boundary = square(1.0);
let mut far = square(1.0);
far.apply_affine(Affine::translate((1e10, 0.0)));
boundary.extend(far);
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap();
assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp));
// Dashes 0.25 long with 0.25 gaps: two per line in each square.
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap();
assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp));
}
#[test]
fn families_based_far_away_draw_the_same_lines() {
// Lines one apart from a base 1e19 up are the lines one apart from the origin.
let mut far = line(0.0, [0.0, 1.0], &[]);
far.base = [0.0, 1e19];
let (bp, _) = pattern(&[far], &square(100.0)).unwrap();
let p = pieces(&bp);
assert_eq!(p.len(), 100, "{p:?}");
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}");
// A staggered family based 100 lines away keeps each line's dash phase.
let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]);
near.base = [-497.0, 0.0];
let mut away = near.clone();
away.base = [3.0, 1000.0];
let sorted = |l: PatternLine| {
let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0);
p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal));
p
};
let (a, b) = (sorted(near), sorted(away));
assert_eq!(a.len(), b.len());
assert!(!a.is_empty());
assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}");
}
#[test]
fn families_based_far_away_keep_lines_off_a_fractional_center() {
// A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not
// through the center.
let mut far = line(0.0, [0.0, 1.0], &[]);
far.base = [0.0, 1e19];
let (bp, _) = pattern(&[far], &square(3.0)).unwrap();
let p = pieces(&bp);
assert!(p.len() >= 2, "{p:?}");
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}");
}
#[test]
fn dash_periods_far_longer_than_the_boundary_still_draw() {
// Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a
// dash, so every row is drawn across the square.
for x in [0.0, -7.5e15] {
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
l.base = [x, 0.0];
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
let p = pieces(&bp);
let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect();
assert_eq!(rows.len(), 9, "base x {x}: {p:?}");
assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}");
}
// From x 5e15 the square lies in a gap: nothing is drawn.
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
l.base = [5e15, 0.0];
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
}
#[test]
fn large_offset_counts_that_cancel_keep_the_dash_start() {
// A 100 square 2^40 up, its family based on the row through its middle with offsets
// 2^30 along: the row's dashes start at x 0, so it draws 0 to 30.
let b = 2f64.powi(40);
let mut boundary = square(100.0);
boundary.apply_affine(Affine::translate((0.0, b)));
let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]);
l.base = [0.0, b + 50.0];
let p = pieces(&pattern(&[l], &boundary).unwrap().0);
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect();
assert_eq!(row.len(), 1, "{p:?}");
assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}");
}
#[test]
fn large_phase_terms_that_cancel_keep_a_small_one() {
// Based and offset by 2^54 along and 10 up: the line one offset back runs along the
// bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1.
let big = 2f64.powi(54);
let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]);
l.base = [big, 10.0];
let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0);
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect();
assert_eq!(row, [(0.0, 1.0)], "{p:?}");
}
#[test]
fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() {
// A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square
// lies in the gap, so nothing is drawn.
let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]);
l.base = [0.0, 0.5];
let (bp, _) = pattern(&[l], &square(1.0)).unwrap();
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
}
#[test]
fn distant_bases_keep_their_dash_remainder() {
// Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the
// dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x.
for side in [96.0, 98.0] {
let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]);
l.base = [1e19, 0.0];
let p = pieces(&pattern(&[l], &square(side)).unwrap().0);
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect();
assert_eq!(row.len(), 16, "side {side}: {row:?}");
assert!(
row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9),
"side {side}: {row:?}"
);
}
}
#[test]
fn a_dot_on_the_start_of_a_span_is_kept() {
// A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom.
let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap();
assert!(dots);
let xs: Vec<f64> = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect();
assert_eq!(xs, [0.0, 5.0, 10.0]);
}
#[test]
fn slanted_lines_fill_a_square_evenly() {
// 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one
// side of the square to another.
let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()];
let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap();
let p = pieces(&bp);
assert!((14..=15).contains(&p.len()), "{} lines", p.len());
let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6);
assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b)));
}
#[test]
fn too_dense_patterns_and_missing_ones_are_reported() {
assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined));
// Lines 0.001 apart across a 1,000 square: a million lines.
assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense));
// Few lines, but dashes far shorter than the square: more pieces than allowed.
assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense));
// A tiny nonempty dash period is too dense; only an empty list draws continuous lines.
// It is refused once the first line is clipped, before any of its dashes is looked at.
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at");
// A period below the coordinates' precision is refused before any line is clipped.
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
assert_eq!(budget.work, usize::MAX, "no work done");
let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap();
assert!(!pieces(&bp).is_empty());
// Lines on top of each other, or as good as, are as dense as can be.
assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense));
assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense));
// Only damaged families: no pattern to draw.
assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined));
}
fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient {
model::Gradient {
name: name.into(),
angle,
shift,
single: false,
tint: 0.0,
colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])],
}
}
#[test]
fn gradients_run_across_the_boundary_at_their_angle() {
let box_ = {
let mut b = square(100.0);
b.apply_affine(Affine::scale_non_uniform(2.0, 1.0));
b
};
let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0)));
assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255]))));
assert_eq!(g.stops, [(0.0, false), (1.0, true)]);
// At a quarter turn it runs bottom to top.
let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}");
// Shifted, the center moves up and left: a sphere's center and a cylinder's middle.
let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0)));
assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center");
let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0));
// A curved gradient runs bottom to top, so the shift moves it up.
for name in ["CURVED", "INVCURVED"] {
let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}");
}
// A plane stretched twice as wide stretches the circle into an ellipse with it.
let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap();
assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom);
}
#[test]
fn inverse_gradients_swap_their_colors() {
for (name, inv) in
[("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")]
{
let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}");
let count = if name == "CYLINDER" { 3 } else { 2 };
assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}");
assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops);
}
}
#[test]
fn one_color_gradients_shade_or_tint_their_color() {
assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]);
assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]);
assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]);
assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]);
let mut g = grad("LINEAR", 0.0, 0.0);
(g.single, g.tint, g.colors) = (true, 0.75, vec![]);
let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap();
assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color");
}
}
+86 -2
View File
@@ -1,7 +1,8 @@
//! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer,
//! linetype and text style tables; the blocks; the entities; the layouts.
//! linetype and text style tables; the blocks; the entities; the layouts; the image files.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use craft_dxf::model::{self, EntityRecord};
use vectorcraft_geom::Point;
@@ -49,6 +50,15 @@ pub(crate) struct BlockDef<'a> {
pub xref: bool,
}
/// A raster image file that IMAGE entities show (an IMAGEDEF object).
#[derive(Clone, Debug)]
pub(crate) struct ImageFile {
/// The file's path as the drawing stores it (absolute, or relative to the drawing).
pub path: String,
/// Its size in pixels (0 when not given).
pub size: [f64; 2],
}
/// A layout: model space, or a paper layout with the block holding its art.
#[derive(Clone, Debug)]
pub(crate) struct LayoutDef {
@@ -79,8 +89,13 @@ pub(crate) struct Drawing<'a> {
pub entities: Vec<EntityRecord<'a>>,
/// Model space first, then the paper layouts in tab order.
pub layouts: Vec<LayoutDef>,
/// The image files by the handle of their IMAGEDEF.
pub images: HashMap<u64, ImageFile>,
/// How many sections the file has (none: not a drawing).
pub sections: usize,
/// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in
/// the ACDSDATA section).
pub regions: Rc<HashMap<u64, Vec<u8>>>,
}
/// The colour of index `i` on paper: index 7 (white on a CAD screen) is black.
@@ -112,6 +127,12 @@ impl<'a> Drawing<'a> {
}
let block_names = doc.block_names();
d.layouts = layouts(&doc, &block_names);
for def in doc.objects_of("IMAGEDEF").map(model::objects::ImageDef::read) {
if let Some(h) = def.handle {
d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size });
}
}
d.regions = Rc::new(region_data(&doc));
for b in doc.blocks {
if b.name.is_empty() {
continue;
@@ -148,6 +169,69 @@ impl<'a> Drawing<'a> {
}
}
/// The binary data of each region in the ACDSDATA section: an `ACDSRECORD` names its entity's
/// handle (320), then holds the bytes (310 chunks) after `2 ASM_Data`, their count in 94.
fn region_data(doc: &model::Document<'_>) -> HashMap<u64, Vec<u8>> {
let records = doc.entities.iter().chain(doc.blocks.iter().flat_map(|b| &b.entities));
let wanted: HashSet<u64> = records.filter(|e| e.kind == "REGION").filter_map(|e| e.record().handle()).collect();
let mut out = HashMap::new();
if wanted.is_empty() {
return out;
}
for section in doc.other_sections.iter().filter(|s| s.name.eq_ignore_ascii_case("ACDSDATA")) {
for r in model::records(section.tags).into_iter().filter(|r| r.kind == "ACDSRECORD") {
let Some(handle) = r.tags.iter().find(|t| t.code == 320).and_then(|t| model::parse_handle(&t.str())) else { continue };
if !wanted.contains(&handle) || out.contains_key(&handle) {
continue;
}
let Some(at) = r.tags.iter().position(|t| t.code == 2 && t.str_ref().is_some_and(|s| s.trim() == "ASM_Data")) else { continue };
let data = r.tags.get(at + 1..).unwrap_or_default();
let size = data.iter().find(|t| t.code == 94).and_then(|t| usize::try_from(t.i64()).ok());
let mut bytes = Vec::new();
let mut whole = true;
for t in data.iter().filter(|t| t.code == 310) {
whole = hex_bytes(t.str_ref().unwrap_or_default().trim(), &mut bytes);
if !whole || bytes.len() > super::acis::MAX_BYTES {
break;
}
}
if !whole {
continue;
}
if let Some(bytes) = sized_region(bytes, size, super::acis::MAX_BYTES) {
out.insert(handle, bytes);
}
}
}
out
}
/// A region's `bytes` cut to its declared `size`, or `None` when the record declares more bytes
/// than it holds (the data was cut short or damaged) or the data is longer than `limit`.
pub(super) fn sized_region(mut bytes: Vec<u8>, size: Option<usize>, limit: usize) -> Option<Vec<u8>> {
match size {
Some(n) if n <= bytes.len() => bytes.truncate(n),
Some(_) => return None,
None => {}
}
(bytes.len() <= limit).then_some(bytes)
}
/// Hex digits' bytes, two digits each, onto `out`. False when `hex` has a character that is not
/// a hex digit or an odd number of digits.
pub(super) fn hex_bytes(hex: &str, out: &mut Vec<u8>) -> bool {
let digit = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
let (pairs, rest) = hex.as_bytes().as_chunks::<2>();
if !rest.is_empty() {
return false;
}
for pair in pairs {
let (Some(hi), Some(lo)) = (digit(pair[0]), digit(pair[1])) else { return false };
out.push(hi << 4 | lo);
}
true
}
pub(crate) fn point(p: model::Point) -> Point {
Point::new(p[0], p[1])
}
+708 -2
View File
@@ -4,9 +4,9 @@
use std::sync::Arc;
use kurbo::ParamCurve;
use kurbo::{ParamCurve, Shape};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit};
use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit};
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
use super::*;
@@ -248,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() {
assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}");
}
/// The straight segments of the paths of the one object a drawing brings in, in drawing
/// coordinates (y up), each with its ends in order, sorted.
fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> {
let doc = &r.document;
assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings);
let h = height(doc);
let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64);
let mut edges = vec![];
for n in leaves(doc) {
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) };
for s in path.to_bezpath().segments() {
let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") };
edges.push([at(l.p0), at(l.p1)]);
}
}
sorted(edges)
}
/// Edges with their ends in order, sorted.
fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> {
for x in &mut e {
x.sort_unstable();
}
e.sort_unstable();
e
}
fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] {
[(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)]
}
#[test]
fn polyface_meshes_draw_their_faces_visible_edges_from_above() {
// A square at two heights as two triangles sharing a hidden diagonal, and a face naming a
// vertex the mesh doesn't have.
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")];
for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] {
e.extend(vertex("192", x, y, z));
}
for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] {
e.extend(vertex("128", "0", "0", "0"));
e.extend([(71, f[0]), (72, f[1]), (73, f[2])]);
}
e.push((0, "SEQEND"));
let r = open(&entities(&e), &points());
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
assert_eq!(drawn_edges(&r), square, "the outline without the diagonal");
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
// With every edge visible, each face is a closed outline.
let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect();
let r = open(&entities(&e), &points());
let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count();
assert_eq!(diagonal, 2, "the diagonal, once per face");
let faces = leaves(&r.document);
assert_eq!(faces.len(), 2);
assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed))));
}
#[test]
fn polygon_meshes_draw_their_m_and_n_lines_from_above() {
// Rows of 3 vertices: N runs along x, M along y.
let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| {
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)];
for y in rows {
for x in ["0", "10", "20"] {
e.extend(vertex("64", x, y, "7"));
}
}
e.push((0, "SEQEND"));
e
};
let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points()));
let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]];
let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]];
let open_grid = sorted([rows.clone(), cols.clone()].concat());
assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid);
// Closed in N (32): each row joins its last vertex to its first.
let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]];
assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat()));
// Closed in M (1): each column joins its last vertex to its first.
let tall = edges(&grid("17", "3", "3", &["0", "10", "20"]));
for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] {
assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}");
}
// A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when
// the frame (3 by 2) has as many vertices.
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")];
for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] {
e.extend(vertex("80", x, y, "0"));
}
e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]);
assert_eq!(edges(&e), open_grid);
// When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface
// vertices either: the mesh is left out with a warning.
let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}"));
e[i] = (74, "4");
let r = open(&entities(&e), &points());
assert!(leaves(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
// Vertices that don't fill the grid: the mesh is left out with a warning.
let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points());
assert!(leaves(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
}
#[test]
fn three_d_faces_leave_out_their_hidden_edges() {
let edges = |hidden: &'static str| {
let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)];
e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]);
drawn_edges(&open(&entities(&e), &points()))
};
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
assert_eq!(edges("0"), square);
// Bit 0 hides the edge from the first corner, bit 2 the one from the third.
assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]));
assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]]));
}
#[test]
fn nurbs_splines_stay_within_a_hundredth() {
// A rational quadratic circle of radius 100: nine weighted control points.
@@ -386,6 +505,593 @@ fn solid_hatches_fill_and_pattern_hatches_outline() {
assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none()));
}
/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through
/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups).
fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> {
let mut e = hatch("0");
e.insert(1, (6, linetype));
let seeds = e.iter().position(|p| *p == (98, "0")).unwrap();
let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")];
lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes });
e.splice(seeds..seeds, lines);
e
}
#[test]
fn ignore_islands_hatches_fill_and_pattern_through_the_hole() {
let mut e = hatch("1");
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square");
assert!(path.subpaths[0].closed);
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
let box_area = bounds(area).area();
assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled");
let mut e = pattern_hatch("CONTINUOUS", &[]);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole");
let width = bounds(lines).width();
assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square");
}
#[test]
fn hatch_island_styles_select_nested_boundary_levels() {
let mut e = hatch("1");
let count = e.iter().position(|p| p.0 == 91).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
e[count] = (91, "3");
let mut loops = Vec::new();
// Innermost first so nesting depends on geometry, not boundary order or flags.
for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] {
loops.extend([
(92, "2"),
(72, "0"),
(73, "1"),
(93, "4"),
(10, lo),
(20, lo),
(10, hi),
(20, lo),
(10, hi),
(20, hi),
(10, lo),
(20, hi),
(97, "0"),
]);
}
e.splice(count + 1..end, loops);
// The sides of the squares each style keeps: normal and unknown styles all three, outer the
// outermost and middle ones, ignore the outermost alone.
for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] {
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let mut sides: Vec<f64> = match &area.kind {
NodeKind::Compound { children, rule } => {
assert_eq!(*rule, FillRule::EvenOdd);
children.iter().map(|c| bounds(c).width().round()).collect()
}
_ => {
assert_eq!(area.path_data().unwrap().subpaths.len(), 1);
vec![bounds(area).width().round()]
}
};
sides.sort_by(f64::total_cmp);
assert_eq!(sides, expected, "boundary loops for island style {style}");
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
}
}
#[test]
fn hatch_ignore_islands_drops_small_island_far_from_origin() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
// Centered, so the art far from the drawing's origin lands on the canvas.
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed");
}
#[test]
fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
let mut loops = Vec::new();
for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
assert_eq!(children.len(), 2, "the island is removed and both outer squares remain");
}
#[test]
fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
let mut loops = Vec::new();
for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain");
}
#[test]
fn hatch_ignore_islands_keeps_squares_sharing_an_edge() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
// The first vertex lies on the second square's left edge.
for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in vertices {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") };
assert_eq!(children.len(), 2, "adjacent squares are both boundaries");
}
#[test]
fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
// The island's first vertex touches the outer square's right edge, where
// winding is zero. Its other vertices and all segment midpoints are inside.
for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in vertices {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "the touching island is removed");
}
#[test]
fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in vertices {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed");
}
#[test]
fn hatch_ignore_islands_drops_thin_island() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
for vertices in [
[("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")],
[("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")],
] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in vertices {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "the thin island is removed");
}
#[test]
fn hatch_ignore_islands_drops_rotated_thin_island() {
let mut e = hatch("1");
let start = e.iter().position(|p| p.0 == 92).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
let mut loops = Vec::new();
// These are the previous test's corners turned 45 degrees about the origin.
for vertices in [
[("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")],
[
("7.07106639765", "7.07106922608"),
("63.6396088926", "63.6396117210"),
("63.6396046499", "63.6396159636"),
("7.07106215421", "7.07107346952"),
],
] {
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in vertices {
loops.extend([(10, x), (20, y)]);
}
loops.push((97, "0"));
}
e.splice(start..end, loops);
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let path = area.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed");
}
#[test]
fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() {
let mut e = hatch("1");
let count = e.iter().position(|p| p.0 == 91).unwrap();
let hole = e.iter().position(|p| *p == (92, "0")).unwrap();
let end = e.iter().position(|p| p.0 == 75).unwrap();
e[count] = (91, "16");
// Keep the outer square and add 15 inner squares. With at least five path elements
// per square, 16 loops require at least 1,280 steps, over the test-time limit.
// Without the fallback, ignore style removes the inner squares.
let inner = [
(92, "2"),
(72, "0"),
(73, "1"),
(93, "4"),
(10, "20"),
(20, "20"),
(10, "80"),
(20, "20"),
(10, "80"),
(20, "80"),
(10, "20"),
(20, "80"),
(97, "0"),
];
e.splice(hole..end, inner.repeat(15));
for style in ["2", "0"] {
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
let r = open(&entities(&e), &points());
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let count = match &area.kind {
NodeKind::Compound { children, .. } => children.len(),
_ => area.path_data().unwrap().subpaths.len(),
};
assert_eq!(count, 16, "every boundary loop is kept for style {style}");
if style == "2" {
assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]);
} else {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
}
}
#[test]
fn pattern_hatches_draw_their_lines_inside_the_boundary() {
// A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them.
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
// Ten lines; the four that cross the hole (y 35 to 65) are cut in two.
assert_eq!(children.len(), 14);
assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]);
assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled");
assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines");
let h = height(&r.document);
for c in children {
let pts = path_points(c);
let (a, b) = (pts[0], *pts.last().unwrap());
let y = h - a.y;
assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}");
assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}");
let mid = Point::new((a.x + b.x) / 2.0, y);
assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}");
}
assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
// A pattern of dots (no length) shows them with round caps.
let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points());
let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings);
// Dashes and dots together: the dots take round caps on a path of their own, and the dashes
// keep butt caps, so they do not grow into their gaps.
let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")];
let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) };
assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round));
let length = |n: &Node| {
let pts = path_points(n);
pts[0].distance(*pts.last().unwrap())
};
let pieces = |n: &Node| match &n.kind {
NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(),
_ => vec![n.clone()],
};
assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes");
assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots");
// Without its pattern lines a pattern hatch still comes in as its boundary, with a note.
let r = open(&entities(&hatch("0")), &points());
assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings);
}
#[test]
fn user_defined_double_hatches_draw_level_and_vertical_lines() {
for double in ["1", "0"] {
let mut e = pattern_hatch("CONTINUOUS", &[]);
let kind = e.iter().position(|p| *p == (76, "1")).unwrap();
e[kind] = (76, "0");
e.insert(kind + 1, (77, double));
let r = open(&entities(&e), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
let (mut level, mut vertical) = (0, 0);
for c in children {
let pts = path_points(c);
let (a, b) = (pts[0], *pts.last().unwrap());
if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 {
level += 1;
} else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 {
vertical += 1;
} else {
panic!("level or vertical piece: {a:?} {b:?}");
}
}
assert!(level > 0, "level pieces with double = {double}");
assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}");
}
}
#[test]
fn pattern_hatches_share_the_drawings_budget() {
// Keep the fixture's square alone so every fallback is one closed path.
let mut hatch = pattern_hatch("CONTINUOUS", &[]);
let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap();
let end = hatch.iter().position(|p| p.0 == 75).unwrap();
hatch.drain(hole..end);
*hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1");
let limit = super::hatch::MAX_TOTAL_PIECES;
let count = limit / 10 + 5;
let e = hatch.repeat(count);
let r = open(&entities(&e), &points());
assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings);
assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings);
let art = r.document.layers[0].children().unwrap();
assert_eq!(art.len(), count, "each hatch keeps its place");
let mut pieces = 0;
let mut boundaries = 0;
for n in art {
if let NodeKind::Compound { children, .. } = &n.kind {
assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries");
pieces += children.len();
assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed))));
} else {
let path = n.path_data().unwrap();
assert_eq!(path.subpaths.len(), 1);
assert!(path.subpaths[0].closed);
boundaries += 1;
}
}
assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}");
assert!(boundaries >= 5, "hatches past the budget keep their boundaries");
}
/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from
/// a true color (red) to color 5 (blue), or from red alone with `tint`.
fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> {
let mut e = hatch("1");
e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]);
e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]);
e
}
fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint {
match n.appearance.fill().map(|f| &f.paint) {
Some(Paint::Gradient(g)) => (**g).clone(),
other => panic!("not a gradient: {other:?}"),
}
}
#[test]
fn gradient_hatches_keep_their_gradient() {
let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
let g = gradient_of(area);
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear);
assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5");
// Level, across the square from left to right through its middle.
let (h, geom) = (height(&r.document), g.geom.unwrap());
assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}");
// A quarter turn runs it up the square: from the bottom (larger y in the document) to the top.
let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points());
let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap();
assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}");
// A one-color sphere tinted to white: white in the center, red at the edge.
let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points());
let g = gradient_of(&r.document.layers[0].children().unwrap()[0]);
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]]));
assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9);
}
#[test]
fn block_gradient_stops_keep_the_inserts_color() {
for (color, layer) in [("0", "Doors"), ("256", "0")] {
for (second, tint) in [(false, None), (true, None), (false, Some("1"))] {
let mut hatch = gradient_hatch("LINEAR", "0", tint);
// The hatch's explicit color and other properties do not need insert inheritance.
hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]);
hatch.retain(|p| p.0 != 421);
let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap();
*stop = (63, color);
let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")];
let r = open(&with_door(&hatch, &inserts), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [symbol] = &r.document.symbols[..] else { panic!("one symbol") };
let g = gradient_of(&symbol.art);
let stop = &g.gradient.stops[usize::from(second)];
let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] };
assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}");
}
}
}
#[test]
fn gradient_hatches_far_out_keep_their_fill() {
// A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the
// strip still comes in, centered on the artboard.
let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")];
e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]);
for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] {
e.extend([(10, x), (20, y)]);
}
e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]);
e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]);
e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]);
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial);
assert_eq!(bounds(area).width().round(), 10.0);
}
/// [`with_door`] with a dashed linetype `DASHED` in the drawing.
fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec<u8> {
let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")];
blocks.extend_from_slice(block_art);
blocks.push((0, "ENDBLK"));
let tables = [
(0, "TABLE"),
(2, "LTYPE"),
(0, "LTYPE"),
(2, "DASHED"),
(73, "2"),
(40, "15"),
(49, "10"),
(49, "-5"),
(0, "ENDTAB"),
(0, "TABLE"),
(2, "LAYER"),
(0, "LAYER"),
(2, "Doors"),
(70, "0"),
(62, "5"),
(6, "CONTINUOUS"),
(0, "ENDTAB"),
];
drawing(&[], &tables, &blocks, inserts)
}
/// Whether `n` or any object inside it has a dashed stroke.
fn dashed(n: &Node) -> bool {
n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c)))
}
#[test]
fn block_pattern_hatches_ignore_the_inserts_linetype() {
let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")];
// Pattern lines draw without a linetype: inserts of other colors share one symbol.
let mut lines = pattern_hatch("BYBLOCK", &[]);
lines.splice(1..1, [(8, "Doors"), (370, "25")]);
let r = open(&with_door(&lines, &inserts), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert_eq!(r.document.symbols.len(), 1);
// A pattern hatch drawn as its boundary strokes it in the insert's linetype.
let mut boundary = hatch("0");
boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]);
let r = open(&with_door(&boundary, &inserts), &points());
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
// Inserts of one color, one dashed and one continuous.
let inserts =
[(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")];
let r = open(&with_dashed_door(&lines, &inserts), &points());
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") };
assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes");
// The boundary drawn for each insert takes that insert's linetype.
let r = open(&with_dashed_door(&boundary, &inserts), &points());
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
let looks: Vec<bool> = leaves(&r.document)
.iter()
.map(|n| {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) };
dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art)
})
.collect();
assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not");
}
#[test]
fn hatch_declaring_many_absent_source_handles_parses_quickly() {
let base = hatch("1");
+100
View File
@@ -0,0 +1,100 @@
//! DWG import: drawings written as DXF, converted to DWG by craft-dwg's writer, come in as the DXF
//! does; damaged files are errors. craft-dwg reads and writes DWG everywhere but wasm32 and FreeBSD
//! on aarch64.
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, Unit};
use vectorcraft_geom::{Rect, shapes};
use super::*;
use crate::{DxfOptions, DxfVersion};
/// A drawing in millimetres on a layer named `Walls`: a red rectangle and a blue ellipse.
fn dxf() -> Vec<u8> {
let mut d = Document::new(200.0, 100.0);
let layer = d.add_layer(Some("Walls"));
let stroke = |c| Appearance::basic(Paint::None, Paint::solid(c), 1.0);
let rect = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), stroke(Color::rgb(1.0, 0.0, 0.0)));
let oval = Node::path(d.alloc_id(), shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), stroke(Color::rgb(0.0, 0.0, 1.0)));
for n in [rect, oval] {
d.insert(Some(layer), usize::MAX, n).unwrap();
}
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..DxfOptions::default() };
crate::export(&d, &o).unwrap().bytes
}
fn dwg() -> Vec<u8> {
crate::dwg::allow_in_process();
craft_dwg::dxf_to_dwg_as(&dxf(), "AC1018").unwrap()
}
/// A layer's name, and each of its objects' bounds (to 0.01 pt) and stroke color.
type LayerArt = (Option<String>, Vec<([i64; 4], Option<[u8; 4]>)>);
/// Each layer holding art.
fn art(doc: &Document) -> Vec<LayerArt> {
let r = |v: f64| (v * 100.0).round() as i64;
doc.layers
.iter()
.filter_map(|layer| {
let objects: Vec<_> = layer
.children()?
.iter()
.map(|n| {
let b = n.geometric_bounds().unwrap();
let stroke = match n.appearance.stroke().map(|s| &s.paint) {
Some(Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)),
_ => None,
};
([r(b.x0), r(b.y0), r(b.x1), r(b.y1)], stroke)
})
.collect();
(!objects.is_empty()).then(|| (layer.name.clone(), objects))
})
.collect()
}
#[test]
fn a_dwg_drawing_comes_in_as_its_dxf_does() {
let (dxf, dwg) = (dxf(), dwg());
assert!(crate::is_dwg(&dwg) && !crate::is_dwg(&dxf));
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
let want = art(&import(&dxf, &o).unwrap().document);
assert_eq!(want.len(), 1, "{want:?}");
assert_eq!(want[0].0.as_deref(), Some("Walls"));
assert_eq!(want[0].1.len(), 2, "{want:?}");
assert_eq!(art(&import(&dwg, &o).unwrap().document), want);
let i = info(&dwg).unwrap();
assert_eq!((i.units.as_str(), i.unit, i.layouts.first().map(String::as_str)), ("Millimeters", Unit::Millimeters, Some("Model")));
assert!(i.layers.iter().any(|l| l == "Walls"), "{i:?}");
}
#[test]
fn a_damaged_dwg_is_an_error_that_names_dwg() {
let mut cut = dwg();
cut.truncate(cut.len() / 3);
let e = import(&cut, &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
assert!(info(&cut).is_err());
// A drawing of a version the DWG reader skips is refused by its version, without reading it.
for (old, name) in [
(&b"AC1.50\x00\x00\x00\x00"[..], "DWG R2.05 (AC1.50)"),
(b"MC0.0\x00\x00\x00\x00", "DWG R1.0 (MC0.0)"),
(b"AC1004\x00\x00\x00\x00", "DWG R9 (AC1004)"),
] {
let e = import(old, &ImportOptions::default()).unwrap_err();
assert!(e.starts_with(&format!("this drawing is {name},")) && e.contains("DXF"), "{e}");
assert_eq!(info(old).unwrap_err(), e);
}
assert_eq!(import(b"AC1018", &ImportOptions::default()).unwrap_err(), "DWG: the file is cut short");
}
#[test]
fn a_dwg_drawing_with_an_ad_version_code_comes_in_as_its_ac_one_does() {
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), ..ImportOptions::default() };
let ac = dwg();
let mut ad = ac.clone();
ad[1] = b'D';
assert_eq!(art(&import(&ad, &o).unwrap().document), art(&import(&ac, &o).unwrap().document));
}
+620
View File
@@ -0,0 +1,620 @@
//! Raster images: an IMAGE comes in as an image linked to the file its IMAGEDEF names, placed as
//! its corner and pixel vectors say and clipped by its clip boundary; images the export wrote come
//! back where they were.
use std::sync::Arc;
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Unit};
use vectorcraft_geom::{Affine, Point, Rect};
use super::*;
use crate::{DxfOptions, DxfVersion};
/// A DXF file of `entities` and `objects` (each a run of pairs).
fn drawing(entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
with_blocks(&[], entities, objects)
}
/// A DXF file of `blocks`, `entities` and `objects` (each a run of pairs).
fn with_blocks(blocks: &[(i32, &str)], entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec<u8> {
let mut p: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")];
p.extend([(0, "SECTION"), (2, "BLOCKS")]);
p.extend_from_slice(blocks);
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES")]);
p.extend_from_slice(entities);
p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]);
p.extend_from_slice(objects);
p.extend([(0, "ENDSEC"), (0, "EOF")]);
p.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::<String>().into_bytes()
}
/// An IMAGEDEF with handle `handle` naming `file`, 30 × 10 pixels.
fn def<'a>(handle: &'a str, file: &'a str) -> Vec<(i32, &'a str)> {
vec![(0, "IMAGEDEF"), (5, handle), (100, "AcDbRasterImageDef"), (1, file), (10, "30"), (20, "10")]
}
/// An IMAGE of IMAGEDEF `def` with its lower-left corner at (10, 20) and 2-unit pixels, `size`
/// pixels (none given: `None`), followed by `more` groups.
fn image<'a>(def: &'a str, size: Option<(&'a str, &'a str)>, more: &[(i32, &'a str)]) -> Vec<(i32, &'a str)> {
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "0"), (22, "2")];
if let Some((w, h)) = size {
e.extend([(13, w), (23, h)]);
}
e.push((340, def));
e.extend_from_slice(more);
e
}
/// Points at 1:1, not centred: drawing (x, y) lands at document (x, artboard height − y).
fn points() -> ImportOptions {
ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }
}
fn nodes(doc: &Document) -> Vec<Node> {
let mut out = vec![];
doc.walk(|n| out.push(n.clone()));
out
}
fn images(doc: &Document) -> Vec<ImageObject> {
nodes(doc)
.into_iter()
.filter_map(|n| match n.kind {
NodeKind::Image(im) => Some(*im),
_ => None,
})
.collect()
}
/// Where image `im`'s pixel corner `(x, y)` lands.
fn at(im: &ImageObject, x: f64, y: f64) -> Point {
im.xf * Point::new(x, y)
}
fn near(a: Point, b: Point) -> bool {
a.distance(b) < 1e-9
}
#[test]
fn an_image_comes_in_linked_to_its_file_with_its_top_left_pixel_at_the_top_left() {
let bytes = drawing(&image("1F", Some(("30", "10")), &[]), &def("1F", r"photos\scan.png"));
let r = import(&bytes, &points()).unwrap();
assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings);
let doc = &r.document;
assert_eq!(doc.layers.iter().filter_map(|l| l.name.as_deref()).collect::<Vec<_>>(), ["Photos"]);
let ims = images(doc);
assert_eq!(ims.len(), 1);
let im = &ims[0];
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(r"photos\scan.png"));
assert_eq!((im.width, im.height), (30, 10));
// The drawing's 60 × 20 units from (10, 20): y up there, y down here.
let h = doc.artboards[0].rect.height();
assert!(near(at(im, 0.0, 0.0), Point::new(10.0, h - 40.0)), "{:?}", at(im, 0.0, 0.0));
assert!(near(at(im, 30.0, 10.0), Point::new(70.0, h - 20.0)), "{:?}", at(im, 30.0, 10.0));
// Until its file is read it shows the placeholder.
assert!(doc.images.get(&im.key).is_some_and(ImageBlob::is_proxy));
}
#[test]
fn an_image_without_its_own_size_takes_its_file_s_and_two_images_of_one_file_share_its_data() {
let mut e = image("1F", None, &[]);
e.extend(image("1F", Some(("30", "10")), &[]));
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
let ims = images(&doc);
assert_eq!(ims.iter().map(|im| (im.width, im.height)).collect::<Vec<_>>(), [(30, 10), (30, 10)]);
assert_eq!(ims[0].key, ims[1].key);
assert_eq!(doc.images.len(), 1);
}
#[test]
fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() {
// Pixels 5 to 14 across and 2 to 6 down: a 20 × 10 unit window.
let part = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
let r = import(&drawing(&part, &def("1F", "scan.png")), &points()).unwrap();
let all = nodes(&r.document);
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
let children = group.children().unwrap();
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
assert!(matches!(children[1].kind, NodeKind::Image(_)));
let h = r.document.artboards[0].rect.height();
let clip = children[0].geometric_bounds().unwrap();
// x 10 + 2·5 to 10 + 2·15; y down from the image's top (20 + 2·10) 2·2 to 2·7.
let want = Rect::new(20.0, h - 40.0 + 4.0, 40.0, h - 40.0 + 14.0);
assert!([(clip.x0, want.x0), (clip.y0, want.y0), (clip.x1, want.x1), (clip.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-9), "{clip:?}");
// The default boundary, the whole image, makes no group; clipping off ignores a boundary.
let whole = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "9.5")]);
let off = image("1F", Some(("30", "10")), &[(280, "0"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]);
for e in [whole, off] {
let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document;
assert!(!nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })), "no clip group");
assert_eq!(images(&doc).len(), 1);
}
}
#[test]
fn a_clip_boundary_with_a_repeated_corner_still_clips_the_image() {
let boundary = image(
"1F",
Some(("30", "10")),
&[
(280, "1"),
(71, "2"),
(91, "4"),
(14, "-0.5"),
(24, "-0.5"),
(14, "29.5"),
(24, "-0.5"),
(14, "-0.5"),
(24, "-0.5"),
(14, "-0.5"),
(24, "9.5"),
],
);
let doc = import(&drawing(&boundary, &def("1F", "scan.png")), &points()).unwrap().document;
let all = nodes(&doc);
let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group");
let children = group.children().unwrap();
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
assert!(matches!(children[1].kind, NodeKind::Image(_)));
}
#[test]
fn image_display_flags_control_clipping_only_when_present() {
for (display, clipping, clipped) in [(None, "1", true), (Some("9"), "1", false), (Some("13"), "1", true), (Some("13"), "0", false)] {
let mut boundary = vec![(280, clipping), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")];
if let Some(flags) = display {
boundary.push((70, flags));
}
let e = image("1F", Some(("30", "10")), &boundary);
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
assert_eq!(images(&r.document).len(), 1);
assert_eq!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), clipped, "{display:?}, {clipping}");
}
}
#[test]
fn images_requested_opaque_warn_once_and_other_images_do_not() {
for (display, opaque) in [(None, false), (Some("9"), false), (Some("1"), true), (Some("5"), true)] {
let flags: Vec<_> = display.map(|flags| (70, flags)).into_iter().collect();
let mut e = image("1F", Some(("30", "10")), &flags);
e.extend(image("1F", Some(("30", "10")), &flags));
let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap();
assert_eq!(images(&r.document).len(), 2);
let warnings: Vec<_> = r.warnings.iter().filter(|w| w.contains("opaque") && w.contains("transparency")).collect();
assert_eq!(warnings.len(), usize::from(opaque), "{display:?}: {:?}", r.warnings);
}
}
#[test]
fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_with_a_warning() {
let tri = image(
"1F",
Some(("30", "10")),
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
);
let doc = import(&drawing(&tri, &def("1F", "scan.png")), &points()).unwrap().document;
let clip = nodes(&doc).into_iter().find(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).expect("a clip path");
let NodeKind::Path { path, .. } = &clip.kind else { panic!("not a path") };
let im = &images(&doc)[0];
let mut corners: Vec<Point> = path.to_bezpath().elements().iter().filter_map(|el| el.end_point()).collect();
// The path may draw its closing edge as a line back to the start.
if corners.len() > 1 && corners.first() == corners.last() {
corners.pop();
}
assert_eq!(corners.len(), 3, "{corners:?}");
for (c, (x, y)) in corners.iter().zip([(0.0, 0.0), (30.0, 0.0), (0.0, 10.0)]) {
assert!(near(*c, at(im, x, y)), "{c:?}");
}
// The same triangle closed by repeating its first point still clips: three corners of the
// image's box and a repeat are not the box.
let closed = image(
"1F",
Some(("30", "10")),
&[
(280, "1"),
(71, "2"),
(91, "4"),
(14, "-0.5"),
(24, "-0.5"),
(14, "29.5"),
(24, "-0.5"),
(14, "29.5"),
(24, "9.5"),
(14, "-0.5"),
(24, "-0.5"),
],
);
let doc = import(&drawing(&closed, &def("1F", "scan.png")), &points()).unwrap().document;
assert!(nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), "a clip group");
// A clip point far out of range leaves the image out.
let far = image(
"1F",
Some(("30", "10")),
&[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")],
);
let r = import(&drawing(&far, &def("1F", "scan.png")), &points()).unwrap();
assert!(images(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
let mut inverted = tri.clone();
inverted.push((290, "1"));
let r = import(&drawing(&inverted, &def("1F", "scan.png")), &points()).unwrap();
assert!(!nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })));
assert!(r.warnings.iter().any(|w| w.contains("inverted image clips")), "{:?}", r.warnings);
}
#[test]
fn images_without_usable_file_references_do_not_expand_the_artboard() {
for objects in [def("1F", "scan.png"), def("2A", " ")] {
let mut far = image("2A", Some(("30", "10")), &[]);
for (code, value) in &mut far {
if *code == 10 || *code == 20 {
*value = "100000";
}
}
let mut entities = vec![(0, "LINE"), (10, "0"), (20, "0"), (11, "100"), (21, "50")];
entities.extend(far);
let r = import(&drawing(&entities, &objects), &points()).unwrap();
assert!(images(&r.document).is_empty());
assert!(r.warnings.iter().any(|w| w.contains("name no image file")), "{:?}", r.warnings);
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })));
let board = r.document.artboards[0].rect;
assert!(board.width() < 1000.0 && board.height() < 1000.0, "{board:?}");
}
}
/// Entities, objects, and the warning they give.
type Case<'a> = (Vec<(i32, &'a str)>, Vec<(i32, &'a str)>, &'a str);
#[test]
fn images_that_name_no_file_or_have_no_size_or_area_are_left_out_with_warnings() {
let cases: [Case; 4] = [
(image("2A", Some(("30", "10")), &[]), def("1F", "scan.png"), "name no image file"),
(image("1F", Some(("30", "10")), &[]), def("1F", " "), "name no image file"),
(image("1F", Some(("0", "10")), &[]), vec![(0, "IMAGEDEF"), (5, "1F"), (1, "scan.png")], "no size in pixels"),
(
vec![(0, "IMAGE"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "4"), (22, "0"), (13, "30"), (23, "10"), (340, "1F")],
def("1F", "scan.png"),
"no width or height",
),
];
for (e, o, why) in cases {
let r = import(&drawing(&e, &o), &points()).unwrap();
assert!(images(&r.document).is_empty(), "{why}");
assert!(r.warnings.iter().any(|w| w.contains(why)), "{why}: {:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "an IMAGE is not an unknown entity: {:?}", r.warnings);
}
// Brightness, contrast and fade are noted.
let faded = image("1F", Some(("30", "10")), &[(283, "40")]);
let r = import(&drawing(&faded, &def("1F", "scan.png")), &points()).unwrap();
assert_eq!(images(&r.document).len(), 1);
assert!(r.warnings.iter().any(|w| w.contains("fade")), "{:?}", r.warnings);
}
#[test]
fn an_image_whose_show_image_flag_is_off_is_hidden() {
let o = def("1F", "scan.png");
for (flags, shown) in [("3", 1), ("1", 1), ("2", 0), ("0", 0)] {
let r = import(&drawing(&image("1F", Some(("30", "10")), &[(70, flags)]), &o), &points()).unwrap();
assert_eq!(images(&r.document).len(), shown, "group 70 = {flags}");
assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "{:?}", r.warnings);
}
}
#[test]
fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_on_the_canvas() {
// The block's image sits 10,000,000 units out, and the insert moves it back next to the origin.
let tri = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
let mut far = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10000010"), (20, "20")];
far.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
let head = far.len();
far.extend_from_slice(&tri);
let block_of = |image: &[(i32, &'static str)]| {
let mut block = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
block.extend_from_slice(image);
block.push((0, "ENDBLK"));
block
};
let insert = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-10000000"), (20, "0")];
let r = import(&with_blocks(&block_of(&far), &insert, &def("1F", "scan.png")), &points()).unwrap();
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
let art = &r.document.symbols.first().expect("a symbol").art;
assert!(matches!(art.kind, NodeKind::Group { clip: true, .. }), "{:?}", art.kind);
// A clip point far from its own image in the block still leaves the image out.
let mut farther = far[..head].to_vec();
farther.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
let r = import(&with_blocks(&block_of(&farther), &insert, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
// A wide image whose corner is far out, cropped to a part near the origin, comes in too.
let mut wide = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "-5000000"), (20, "0")];
wide.extend([(11, "1000"), (21, "0"), (12, "0"), (22, "1000"), (13, "10000"), (23, "10"), (340, "1F")]);
wide.extend([(280, "1"), (71, "2"), (91, "3"), (14, "5200"), (24, "0"), (14, "5400"), (24, "0"), (14, "5200"), (24, "5")]);
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
let r = import(&with_blocks(&block_of(&wide), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
assert!(r.document.symbols.first().is_some_and(|s| matches!(s.art.kind, NodeKind::Group { clip: true, .. })));
// A block's image near the origin whose clip reaches out of range where the insert places it
// is left out with that warning, and the block's other art stays.
let mut reaching = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20")];
reaching.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
reaching.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
reaching.extend([(0, "LINE"), (8, "Photos"), (10, "0"), (20, "0"), (11, "50"), (21, "50")]);
let r = import(&with_blocks(&block_of(&reaching), &at_origin, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
let placed = nodes(&r.document);
assert!(!placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Image(_))));
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's line");
// The block's symbol has no instance left, so it is not kept with the image it holds.
assert!(r.document.symbols.is_empty(), "{:?}", r.document.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
}
#[test]
fn a_symbol_that_only_placements_drawn_as_art_use_is_not_charged_twice() {
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where an
// insert at the origin places it, so that insert draws B's art instead of an instance.
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into())]);
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
for i in 0..600_000 {
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
}
owned.push((0, "ENDBLK".into()));
let block: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")];
let r = import(&with_blocks(&block, &at_origin, &def("1F", "scan.png")), &points()).unwrap();
// 1,200,000 points if the unused symbol stayed charged: past the tests' limit of 1,000,000.
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's polyline");
assert!(r.document.symbols.is_empty());
// A second insert that places B in range makes the symbol again, which is charged again: its
// polyline no longer fits, and the first insert's stays.
let both = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-2000000"), (20, "0")];
let r = import(&with_blocks(&block, &both, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
let placed = nodes(&r.document);
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the first insert's polyline");
assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the second insert's instance");
assert_eq!(r.document.symbols.len(), 1);
}
#[test]
fn a_symbol_that_only_a_removed_symbol_placed_is_removed_with_it() {
// Block B holds a 600,000-point polyline and an image whose clip reaches out of range where the
// drawing's insert of block A, which places B, puts it. That insert draws A's art and removes
// A's symbol; B's symbol, which only A's art placed, goes too, so drawing B's art fits.
let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())];
owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]);
for i in 0..600_000 {
owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]);
}
owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]);
owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]);
owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]);
owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into()), (0, "ENDBLK".into())]);
owned.extend([(0, "BLOCK".into()), (2, "A".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]);
owned.extend([(0, "INSERT".into()), (8, "Photos".into()), (2, "B".into()), (10, "0".into()), (20, "0".into()), (0, "ENDBLK".into())]);
let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect();
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0")];
let r = import(&with_blocks(&blocks, &insert, &def("1F", "scan.png")), &points()).unwrap();
assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "B's polyline");
assert!(r.document.symbols.is_empty());
}
/// Block B holds an image clipped by a triangle with a corner at (`far`, −0.5) in pixel space, and
/// block A places B by `inner` beside an image of its own clipped near it; the drawing places A
/// at the origin scaled by `outer`.
fn nested(far: &'static str, inner: &[(i32, &'static str)], outer: &'static str) -> Vec<u8> {
let clipped = |x: &'static str, corner: &'static str| {
let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, x), (20, "20")];
e.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]);
e.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, corner), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]);
e
};
let mut blocks = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")];
blocks.extend(clipped("10", far));
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "A"), (70, "0"), (10, "0"), (20, "0")]);
blocks.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
blocks.extend_from_slice(inner);
blocks.extend(clipped("100", "29.5"));
blocks.push((0, "ENDBLK"));
let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0"), (41, outer), (42, outer)];
with_blocks(&blocks, &insert, &def("1F", "scan.png"))
}
#[test]
fn a_block_s_clip_point_beyond_any_usable_range_leaves_its_image_out_even_where_inserts_scale_it_back() {
// B's clip corner is 2e19 units out in its own space, and two inserts at the smallest scale
// would bring it back next to the origin.
let r = import(&nested("1e19", &[(41, "1e-12"), (42, "1e-12")], "1e-12"), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
let mut held = 0;
for s in &r.document.symbols {
s.art.walk(&mut |n: &Node| held += usize::from(matches!(n.kind, NodeKind::Image(_))));
}
assert_eq!(held + images(&r.document).len(), 1, "A's own image");
}
#[test]
fn a_clip_reach_placed_by_an_overflowing_transform_is_unbounded() {
use super::build::placed_reach;
let out = |b: Rect| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite());
// Across, the terms of every corner overflow with opposite signs to NaN, which a union with
// another symbol's reach would drop; the reach is unbounded instead.
let h = 1e300;
let xf = Affine::new([h, 1.0, -h, 1.0, 0.0, 0.0]);
let r = Rect::new(1e10, 1e10, 2e10, 2e10);
let near = Rect::new(0.0, 0.0, 10.0, 10.0);
let whole = placed_reach(xf, r);
assert!(out(whole.union(near)), "{whole:?}");
// An unbounded reach stays unbounded wherever it is placed.
assert!(out(placed_reach(Affine::scale(1e-12), whole).union(near)));
assert!(out(placed_reach(Affine::IDENTITY, whole).union(near)));
// A placement that stays finite is the box of the placed corners.
let b = placed_reach(Affine::new([0.0, 1.0, -1.0, 0.0, 5.0, 0.0]), near);
assert_eq!((b.x0, b.y0, b.x1, b.y1), (-5.0, 0.0, 5.0, 10.0));
}
#[test]
fn clip_paths_count_against_the_path_point_limit() {
// A 1,000-point clip in an anonymous block placed 1,100 times: 1,001,000 path elements, past
// the tests' limit of 1,000,000.
let mut clip: Vec<(i32, String)> = vec![(280, "1".into()), (71, "2".into()), (91, "1000".into())];
for i in 0..1000 {
let a = f64::from(i) * std::f64::consts::TAU / 1000.0;
clip.extend([(14, format!("{}", 14.5 + 10.0 * a.cos())), (24, format!("{}", 4.5 + 4.0 * a.sin()))]);
}
let clip: Vec<(i32, &str)> = clip.iter().map(|(c, v)| (*c, v.as_str())).collect();
let mut block = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
block.extend(image("1F", Some(("30", "10")), &clip));
block.push((0, "ENDBLK"));
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "1100"), (44, "100")];
let r = import(&with_blocks(&block, &insert, &def("1F", "scan.png")), &points()).unwrap();
let clips = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).count();
assert!((900..1000).contains(&clips), "{clips} clip paths");
assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings);
}
#[test]
fn an_insert_drawn_as_art_gets_back_its_unused_symbol_s_objects_at_the_object_limit() {
// Block B holds a line and an image whose clip reaches out of range where B's insert places
// it: 4 objects as a symbol. 99,996 lines before it leave exactly room for that symbol under
// the tests' limit of 100,000 objects, so its insert draws B's art in the room the unused
// symbol gives back.
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
blocks.extend(image("1F", Some(("30", "10")), &reaching));
blocks.push((0, "ENDBLK"));
// An insert makes at most 10,000 copies: nine of 100 × 100 and one of 84 × 119.
let mut entities = vec![];
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("84", "119")]) {
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
}
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]);
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
let lines = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).count();
assert_eq!(lines, 99_997, "the lines and B's line");
assert!(r.document.symbols.is_empty());
}
#[test]
fn copies_drawn_as_art_past_the_object_limit_stop_without_looking_at_the_block() {
// Block B: 200 lines and an image whose clip reaches out of range unless its copy sits left of
// the origin. 99,796 lines, B's symbol and the first copy's instance fill the tests' limit of
// 100,000 objects; the next 9,999 copies would each look at B's 201 items, past the tests'
// block-work limit of 1,000,000.
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
for _ in 0..200 {
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
}
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
blocks.extend(image("1F", Some(("30", "10")), &reaching));
blocks.push((0, "ENDBLK"));
let mut entities = vec![];
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("79", "124")]) {
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
}
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-35"), (20, "0"), (70, "10000"), (44, "10")]);
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
}
#[test]
fn copies_of_a_symbol_taken_out_at_the_object_limit_are_not_drawn_again() {
// Block B: an image whose clip reaches out of range only for the first copy, and 200 lines.
// 99,800 lines and the first copy, drawn as art in the room its unused symbol gives back,
// fill the tests' limit of 100,000 objects; each of the next 9,999 copies would draw the
// symbol again from B's 201 items, past the tests' block-work limit of 1,000,000.
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]);
let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")];
blocks.extend(image("1F", Some(("30", "10")), &reaching));
for _ in 0..200 {
blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]);
}
blocks.push((0, "ENDBLK"));
let mut entities = vec![];
for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("98", "100")]) {
entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]);
}
entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-25"), (20, "0"), (70, "10000"), (44, "-10")]);
let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
}
/// A document with a 4 × 2 pixel image, 5 pt pixels, its top-left corner at (10, 20).
fn image_doc() -> Document {
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 = Document::new(200.0, 100.0);
let layer = d.add_layer(Some("Photos"));
let im = ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
d.insert(Some(layer), usize::MAX, n).unwrap();
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
d
}
/// Import `bytes`, written from [`image_doc`], and check its one image: linked to `name`, the file
/// the export wrote, and the size and way up it had.
fn written_and_read(bytes: &[u8], name: &str) {
let doc = import(bytes, &points()).unwrap().document;
let ims = images(&doc);
assert_eq!(ims.len(), 1, "{:?}", nodes(&doc).iter().map(|n| &n.kind).collect::<Vec<_>>());
let im = &ims[0];
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(name));
assert_eq!((im.width, im.height), (4, 2));
// 20 × 10 pt with the top-left pixel at the top-left, as it was.
let (tl, br) = (at(im, 0.0, 0.0), at(im, 4.0, 2.0));
assert!((br.x - tl.x - 20.0).abs() < 1e-6 && (br.y - tl.y - 10.0).abs() < 1e-6, "{tl:?} {br:?}");
}
#[test]
fn an_image_the_export_wrote_comes_back_linked_to_the_file_it_wrote() {
let d = image_doc();
let out = crate::export(&d, &DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }).unwrap();
assert_eq!(out.images.len(), 1);
written_and_read(&out.bytes, &out.images[0].name);
}
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn an_image_in_a_dwg_drawing_comes_in_as_in_its_dxf() {
let d = image_doc();
let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() };
let out = crate::export(&d, &o).unwrap();
crate::dwg::allow_in_process();
let dwg = craft_dwg::dxf_to_dwg_as(&out.bytes, "AC1018").unwrap();
written_and_read(&dwg, &out.images[0].name);
}
+686
View File
@@ -0,0 +1,686 @@
//! Regions: solid-modeler data in text (ciphered or not, lines split over groups 1 and 3) and in
//! binary form (the ACDSDATA section) comes in as one filled path of the region's loops; lines,
//! circles, ellipses and spline edges keep their shape, coedge and edge senses are followed, a
//! body's transform is applied, and damaged data is left out without hanging.
use kurbo::{BezPath, Shape};
use vectorcraft_doc::{Document, Node, NodeKind, Unit};
use vectorcraft_geom::{FillRule, Point, Rect};
use super::*;
/// A curve an edge runs along.
#[derive(Clone)]
enum Curve {
Line,
/// A circle about the z axis (`-z`: clockwise) of this centre and radius.
Circle {
c: [f64; 2],
r: f64,
down: bool,
},
/// A curve record's text after its first three values.
Raw(String),
}
/// An edge of a loop, from `a` to `b` as the loop runs it. `flip`: the edge is stored from `b`
/// to `a` and the coedge runs it reversed; `against`: the edge also runs against its curve.
#[derive(Clone)]
struct E {
a: [f64; 2],
b: [f64; 2],
curve: Curve,
flip: bool,
against: bool,
}
fn line(a: [f64; 2], b: [f64; 2]) -> E {
E { a, b, curve: Curve::Line, flip: false, against: false }
}
fn circle(c: [f64; 2], r: f64, down: bool) -> E {
let p = [c[0] + r, c[1]];
E { a: p, b: p, curve: Curve::Circle { c, r, down }, flip: false, against: false }
}
fn square(lo: f64, hi: f64) -> Vec<E> {
vec![line([lo, lo], [hi, lo]), line([hi, lo], [hi, hi]), line([hi, hi], [lo, hi]), line([lo, hi], [lo, lo])]
}
/// Text data (version 700) of one face with `loops`, placed by `transform` (12 numbers and a
/// scale) when given.
fn sat(loops: &[Vec<E>], transform: Option<&str>) -> String {
let mut recs: Vec<String> = vec![];
let xf = if transform.is_some() { "$5" } else { "$-1" };
recs.push(format!("body $-1 -1 $-1 $1 $-1 {xf}"));
recs.push("lump $-1 -1 $-1 $-1 $2 $0".into());
recs.push("shell $-1 -1 $-1 $-1 $-1 $3 $-1 $1".into());
recs.push("face $-1 -1 $-1 $-1 $6 $2 $-1 $4 forward single".into());
recs.push("plane-surface $-1 -1 $-1 0 0 0 0 0 1 1 0 0 forward_v I I I I".into());
recs.push(format!("transform $-1 -1 $-1 {} no_rotate no_reflect no_shear", transform.unwrap_or("1 0 0 0 1 0 0 0 1 0 0 0 1")));
let mut base = 6;
for (l, edges) in loops.iter().enumerate() {
let next_loop = if l + 1 < loops.len() { format!("${}", base + 1 + 7 * edges.len()) } else { "$-1".into() };
recs.push(format!("loop $-1 -1 $-1 {next_loop} ${} $3", base + 1));
let n = edges.len();
for (j, e) in edges.iter().enumerate() {
let at = |k: usize| base + 1 + 7 * k;
let i = at(j);
let (coedge, edge, sv, ev, sp, ep, cv) = (i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6);
let (start, end) = if e.flip { (e.b, e.a) } else { (e.a, e.b) };
let ev = if start == end { sv } else { ev };
let sense = |r: bool| if r { "reversed" } else { "forward" };
recs.push(format!("coedge $-1 -1 $-1 ${} ${} $-1 ${edge} {} ${base} $-1", at((j + 1) % n), at((j + n - 1) % n), sense(e.flip)));
recs.push(format!("edge $-1 -1 $-1 ${sv} 0 ${ev} 1 ${coedge} ${cv} {} @7 unknown", sense(e.against)));
recs.push(format!("vertex $-1 -1 $-1 ${edge} ${sp}"));
recs.push(format!("vertex $-1 -1 $-1 ${edge} ${ep}"));
recs.push(format!("point $-1 -1 $-1 {} {} 0", start[0], start[1]));
recs.push(format!("point $-1 -1 $-1 {} {} 0", end[0], end[1]));
recs.push(match &e.curve {
Curve::Line => format!("straight-curve $-1 -1 $-1 {} {} 0 {} {} 0 I I", start[0], start[1], end[0] - start[0], end[1] - start[1]),
Curve::Circle { c, r, down } => {
format!("ellipse-curve $-1 -1 $-1 {} {} 0 0 0 {} {r} 0 0 1 I I", c[0], c[1], if *down { -1 } else { 1 })
}
Curve::Raw(s) => s.clone(),
});
}
base += 1 + 7 * n;
}
let mut s = String::from("700 0 1 0\n9 Synthetic 3 ASM 4 none\n1 9.9999999999999995e-07 1e-10\n");
for r in recs {
s.push_str(&r);
s.push_str(" #\n");
}
s.push_str("End-of-ACIS-data\n");
s
}
/// DXF's cipher of text data: each printable character mapped, a space after each caret.
fn encipher(s: &str) -> String {
let mut out = String::new();
for c in s.chars() {
let m = match c {
' ' | '\n' => c,
'@'..='_' => char::from(159 - c as u8),
c => char::from(c as u8 ^ 0x5F),
};
out.push(m);
if m == '^' {
out.push(' ');
}
}
out
}
/// A drawing of `version` with `entities` and, when given, an ACDSDATA section.
fn drawing(version: &str, entities: &[(i32, String)], acds: &[(i32, String)]) -> Vec<u8> {
let mut s = format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{version}\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n");
let put = |pairs: &[(i32, String)], s: &mut String| {
for (c, v) in pairs {
s.push_str(&format!("{c:>3}\n{v}\n"));
}
};
put(entities, &mut s);
s.push_str(" 0\nENDSEC\n");
if !acds.is_empty() {
s.push_str(" 0\nSECTION\n 2\nACDSDATA\n");
put(acds, &mut s);
s.push_str(" 0\nENDSEC\n");
}
s.push_str(" 0\nEOF\n");
s.into_bytes()
}
/// A REGION entity holding `lines` of text data (`split`: each line over 40 characters goes on
/// in group 3 from inside a word).
fn region_text(lines: &str, split: bool) -> Vec<(i32, String)> {
let mut e = vec![
(0, "REGION".to_string()),
(5, "2A".into()),
(8, "0".into()),
(100, "AcDbEntity".into()),
(100, "AcDbModelerGeometry".into()),
(70, "1".into()),
];
for l in lines.lines() {
let b = l.as_bytes();
let cut = (40..b.len()).find(|&i| !b[i - 1].is_ascii_whitespace() && !b[i].is_ascii_whitespace());
if let Some(at) = cut.filter(|_| split) {
e.push((1, l[..at].to_string()));
e.push((3, l[at..].to_string()));
} else {
e.push((1, l.to_string()));
}
}
e
}
fn points() -> ImportOptions {
ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() }
}
/// Every leaf path of the document as one path, in document coordinates.
fn outline(doc: &Document) -> BezPath {
let mut bp = BezPath::new();
doc.walk(|n: &Node| {
if let NodeKind::Path { path, .. } = &n.kind {
bp.extend(path.to_bezpath());
}
});
bp
}
/// Inside the path by the even-odd rule.
fn filled(bp: &BezPath, p: Point) -> bool {
bp.winding(p) % 2 != 0
}
/// The region (drawing `x, y`) is filled at `inside` and not at `outside`.
fn check(doc: &Document, inside: &[[f64; 2]], outside: &[[f64; 2]]) {
let h = doc.artboards[0].rect.height();
let (bp, at) = (outline(doc), |p: &[f64; 2]| Point::new(p[0], h - p[1]));
for p in inside {
assert!(filled(&bp, at(p)), "{p:?} should be filled");
}
for p in outside {
assert!(!filled(&bp, at(p)), "{p:?} should be empty");
}
}
/// The only top-level object: filled, without a stroke.
fn filled_object(doc: &Document) -> Node {
let [n] = &doc.layers[0].children().unwrap()[..] else { panic!("{:?}", doc.layers[0].children()) };
assert!(n.appearance.fill().is_some_and(|f| !f.paint.is_none()), "regions are filled");
assert!(n.appearance.stroke().is_none_or(|s| s.paint.is_none()), "regions have no stroke");
n.as_ref().clone()
}
fn square_with_hole() -> Vec<Vec<E>> {
vec![square(0.0, 100.0), vec![circle([50.0, 50.0], 20.0, true)]]
}
#[test]
fn ciphered_text_data_comes_in_as_a_filled_path_with_its_hole() {
let text = encipher(&sat(&square_with_hole(), None));
let r = import(&drawing("AC1015", &region_text(&text, false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let n = filled_object(&r.document);
let NodeKind::Compound { rule, .. } = &n.kind else { panic!("{:?}", n.kind) };
assert_eq!(*rule, FillRule::EvenOdd);
assert!((n.geometric_bounds().unwrap().area() - 10_000.0).abs() < 1e-6);
check(&r.document, &[[10.0, 10.0], [50.0, 75.0], [90.0, 50.0]], &[[50.0, 50.0], [60.0, 55.0], [110.0, 50.0]]);
// The hole is a circle.
let h = r.document.artboards[0].rect.height();
let bp = outline(&r.document);
let centre = Point::new(50.0, h - 50.0);
let on_hole: Vec<f64> = bp.segments().map(|s| kurbo::ParamCurve::eval(&s, 0.5).distance(centre)).filter(|d| *d < 30.0).collect();
assert!(!on_hole.is_empty() && on_hole.iter().all(|d| (d - 20.0).abs() < 1e-3), "{on_hole:?}");
}
#[test]
fn plain_text_split_over_groups_one_and_three_reads_alike() {
let text = sat(&square_with_hole(), None);
let r = import(&drawing("AC1021", &region_text(&text, true), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
filled_object(&r.document);
check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]);
// Before version 700 a record starts with its attribute alone.
let old: String = text.replacen("700 0 1 0", "400 0 1 0", 1).lines().map(|l| format!("{}\n", l.replacen(" $-1 -1 $-1 ", " $-1 ", 1))).collect();
assert!(old.contains("body $-1 $1 $-1 $-1 #"), "{old}");
let r = import(&drawing("AC1012", &region_text(&old, false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
check(&r.document, &[[10.0, 10.0]], &[[50.0, 50.0]]);
}
/// Binary data of the same records: tagged values, type names in parts.
fn sab(text: &str) -> Vec<u8> {
let mut b = b"ACIS BinaryFile".to_vec();
for v in [700u32, 0, 1, 0] {
b.extend(v.to_le_bytes());
}
let string = |b: &mut Vec<u8>, tag: u8, s: &str| {
b.push(tag);
b.push(u8::try_from(s.len()).unwrap());
b.extend(s.as_bytes());
};
string(&mut b, 0x07, "Synthetic");
b.push(0x06);
b.extend(1.0f64.to_le_bytes());
for line in text.lines().skip(3) {
if line.starts_with("End-of") {
break;
}
let mut words = line.split_whitespace().peekable();
let kind = words.next().unwrap();
let parts: Vec<&str> = kind.split('-').collect();
for (i, p) in parts.iter().enumerate() {
string(&mut b, if i + 1 == parts.len() { 0x0D } else { 0x0E }, p);
}
while let Some(w) = words.next() {
match w {
"#" => {}
"forward" | "forward_v" => b.push(0x0B),
"reversed" | "reversed_v" => b.push(0x0A),
"{" => b.push(0x0F),
"}" => b.push(0x10),
w if w.starts_with('$') => {
b.push(0x0C);
b.extend(w[1..].parse::<i32>().unwrap().to_le_bytes());
}
w if w.starts_with('@') => {
let s = words.next().unwrap();
string(&mut b, 0x07, s);
}
w => match w.parse::<f64>() {
Ok(v) => {
b.push(0x06);
b.extend(v.to_le_bytes());
}
Err(_) => string(&mut b, 0x07, w),
},
}
}
b.push(0x11);
}
for p in ["End", "of", "ASM"] {
string(&mut b, 0x0E, p);
}
string(&mut b, 0x0D, "data");
b
}
/// An ACDSDATA record holding `bytes` for the entity with handle 2A, in 50-byte chunks.
fn acds(bytes: &[u8]) -> Vec<(i32, String)> {
let mut a = vec![
(0, "ACDSRECORD".to_string()),
(90, "1".into()),
(2, "AcDbDs::ID".into()),
(280, "10".into()),
(320, "2A".into()),
(2, "ASM_Data".into()),
(280, "15".into()),
(94, bytes.len().to_string()),
];
for c in bytes.chunks(50) {
a.push((310, c.iter().map(|b| format!("{b:02X}")).collect()));
}
a
}
#[test]
fn binary_data_in_the_acdsdata_section_reads_alike() {
let bytes = sab(&sat(&square_with_hole(), None));
let e = vec![(0, "REGION".to_string()), (5, "2A".into()), (8, "0".into()), (100, "AcDbModelerGeometry".into()), (290, "0".into())];
// ASM's signature in place of ACIS's, as DXF 2018 may write it.
let asm = [b"ASM BinaryFile4".as_slice(), &bytes[b"ACIS BinaryFile".len()..]].concat();
for data in [&bytes, &asm] {
let r = import(&drawing("AC1032", &e, &acds(data)), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
filled_object(&r.document);
check(&r.document, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]);
}
// Without its data the region is left out and listed.
let r = import(&drawing("AC1027", &e, &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
// Data shorter than its declared size is left out and listed too.
let mut short = acds(&bytes);
short[7].1 = (bytes.len() + 1).to_string();
let r = import(&drawing("AC1032", &e, &short), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
// A chunk with an odd number of digits or a character that is not a hex digit fails to read.
let mut out = Vec::new();
assert!(super::reader::hex_bytes("0aFf", &mut out));
assert_eq!(out, [0x0A, 0xFF]);
for hex in ["0aF", "0aZZ", "0 aF"] {
assert!(!super::reader::hex_bytes(hex, &mut Vec::new()), "{hex}");
}
// Data longer than the limit is left out, unless its declared size cuts it within the limit.
let sized = |len: usize, size: Option<usize>| super::reader::sized_region(vec![7; len], size, 8).map(|b| b.len());
assert_eq!(sized(10, None), None);
assert_eq!(sized(10, Some(9)), None);
assert_eq!(sized(10, Some(11)), None);
assert_eq!(sized(10, Some(5)), Some(5));
assert_eq!(sized(8, None), Some(8));
}
/// A drawing the export writes (R2000, millimetres) with a region added to its entities.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn exported_with_region() -> Vec<u8> {
let d = Document::new(200.0, 200.0);
let o =
crate::DxfOptions { version: crate::DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Millimeters, ..crate::DxfOptions::default() };
let dxf = String::from_utf8(crate::export(&d, &o).unwrap().bytes).unwrap();
let mut region = String::new();
for (c, v) in region_text(&encipher(&sat(&square_with_hole(), None)), false) {
let v = if c == 5 { "FFF0".to_string() } else { v };
region.push_str(&format!("{c:>3}\n{v}\n"));
}
let at = dxf.find("ENTITIES\n").unwrap() + "ENTITIES\n".len();
format!("{}{region}{}", &dxf[..at], &dxf[at..]).into_bytes()
}
/// The converter writes a region's data as text in a 2004 drawing and as binary data in the
/// ACDSDATA section of a 2013 one; both come in as the DXF does.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn regions_in_dwg_drawings_come_in_from_text_and_binary_data() {
crate::dwg::allow_in_process();
let dxf = exported_with_region();
let o = ImportOptions { unit: Some(Unit::Millimeters), scale: Some(1.0), center: false, ..ImportOptions::default() };
let want = import(&dxf, &o).unwrap();
assert!(want.warnings.is_empty(), "{:?}", want.warnings);
let want = filled_object(&want.document).geometric_bounds().unwrap();
for version in ["AC1018", "AC1027"] {
let dwg = craft_dwg::dxf_to_dwg_as(&dxf, version).unwrap();
let back = craft_dwg::dwg_to_dxf(&dwg).unwrap();
let binary = String::from_utf8_lossy(&back).contains("ACDSDATA");
assert_eq!(binary, version == "AC1027", "{version}: the data's form");
let r = import(&dwg, &o).unwrap();
assert!(!r.warnings.iter().any(|w| w.contains("REGION")), "{version}: {:?}", r.warnings);
let got = filled_object(&r.document).geometric_bounds().unwrap();
assert!((got.area() - want.area()).abs() < 1e-6 && got.origin().distance(want.origin()) < 1e-6, "{version}: {got:?} {want:?}");
let mm = 72.0 / 25.4;
check_at(&r.document, mm, &[[10.0, 10.0], [50.0, 75.0]], &[[50.0, 50.0]]);
}
}
/// [`check`] for art at `k` points per drawing unit.
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn check_at(doc: &Document, k: f64, inside: &[[f64; 2]], outside: &[[f64; 2]]) {
let scale = |ps: &[[f64; 2]]| ps.iter().map(|p| [p[0] * k, p[1] * k]).collect::<Vec<_>>();
check(doc, &scale(inside), &scale(outside));
}
#[test]
fn reversed_coedges_and_edges_run_their_curves_backwards() {
// A quarter of a circle from (100, 0) to (0, 100): on a counter-clockwise circle run along
// it, or on a clockwise one run against it, with the edge stored either way round.
for (down, flip, against) in [(false, true, true), (true, false, true), (true, true, false), (false, false, false)] {
let quarter = E { a: [100.0, 0.0], b: [0.0, 100.0], curve: Curve::Circle { c: [0.0, 0.0], r: 100.0, down }, flip, against };
let flipped_line = E { flip: true, against: true, ..line([0.0, 100.0], [0.0, 0.0]) };
let quadrant = vec![line([0.0, 0.0], [100.0, 0.0]), quarter, flipped_line];
let r = import(&drawing("AC1015", &region_text(&sat(&[quadrant], None), false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
// A quarter disc, not the three quarters the other way round.
check(&r.document, &[[20.0, 20.0], [10.0, 50.0], [65.0, 65.0]], &[[80.0, 80.0], [-50.0, 50.0], [50.0, -50.0]]);
let b = filled_object(&r.document).geometric_bounds().unwrap();
assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{down} {flip} {against}: {b:?}");
}
}
#[test]
fn a_spline_edge_keeps_only_its_part_of_the_curve() {
// A parabola from (0, 0) through (100, -50) to (200, 0); the edge runs its first half,
// stored from its end and run reversed.
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 2 open 2 0 2 1 2 0 0 0 100 -100 0 200 0 0 0 } I I".to_string();
let half = E { a: [0.0, 0.0], b: [100.0, -50.0], curve: Curve::Raw(curve), flip: true, against: true };
let shape = vec![half, line([100.0, -50.0], [100.0, 50.0]), line([100.0, 50.0], [0.0, 0.0])];
let r = import(&drawing("AC1015", &region_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let b = filled_object(&r.document).geometric_bounds().unwrap();
assert!((b.width() - 100.0).abs() < 1e-6, "only the first half of the curve: {b:?}");
assert!((b.height() - 100.0).abs() < 1e-6, "down to the curve's midpoint: {b:?}");
// Below the chord from (0, 0) to (100, -50), above the curve.
check(&r.document, &[[50.0, -30.0], [90.0, 0.0]], &[[50.0, -45.0], [150.0, 0.0]]);
}
#[test]
fn a_spline_edge_warns_when_an_endpoint_lies_on_separate_parts_of_its_curve() {
// The first and last spans both pass through (0, 0), away from their ends.
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 4 0 2 1 1 2 1 3 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 } I I";
for back in [false, true] {
let (a, b) = if back { ([100.0, 100.0], [0.0, 0.0]) } else { ([0.0, 0.0], [100.0, 100.0]) };
let edge = E { a, b, curve: Curve::Raw(curve.into()), flip: false, against: back };
let shape = vec![edge, line(b, [100.0, 0.0]), line([100.0, 0.0], a)];
let r = import(&drawing("AC1015", &region_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
assert!(!outline(&r.document).elements().is_empty());
}
}
#[test]
fn a_spline_edge_warns_when_an_endpoint_is_at_one_cubic_spans_crossing() {
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I";
let edge = E { a: [0.0, 0.0], b: [36.0, 18.0], curve: Curve::Raw(curve.into()), flip: false, against: false };
let shape = vec![edge, line([36.0, 18.0], [36.0, 0.0]), line([36.0, 0.0], [0.0, 0.0])];
let r = import(&drawing("AC1015", &region_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
assert!(!outline(&r.document).elements().is_empty());
}
#[test]
fn a_closed_spline_edge_keeps_the_loop_at_one_cubic_spans_crossing() {
// The curve crosses (0, 0) at 0.25 and 0.75; the loop reaches (-12, 0) at 0.5.
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 3 open 2 0 3 1 3 36 -18 0 -28 26 0 -28 -26 0 36 18 0 } I I";
for back in [false, true] {
let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve.into()), flip: false, against: back };
let r = import(&drawing("AC1015", &region_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
check(&r.document, &[[-6.0, 0.0]], &[[30.0, 0.0]]);
}
}
#[test]
fn a_closed_spline_ring_warns_only_when_its_vertex_is_at_the_crossing() {
// The first and third spans cross (0, 0) halfway along each; the seam is (-100, -100).
let curve = "intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 -100 -100 0 100 100 0 -100 100 0 100 -100 0 -100 -100 0 } I I";
for a in [[0.0, 0.0], [-100.0, -100.0]] {
for back in [false, true] {
let edge = E { a, b: a, curve: Curve::Raw(curve.into()), flip: false, against: back };
let r = import(&drawing("AC1015", &region_text(&sat(&[vec![edge]], None), false), &[]), &points()).unwrap();
if a == [0.0, 0.0] {
assert_eq!(r.warnings, ["region edges on curves that cross themselves may come in along the wrong part of the curve"]);
} else {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
check(&r.document, &[[0.0, 50.0], [0.0, -50.0]], &[[75.0, 0.0], [-75.0, 0.0]]);
}
}
}
#[test]
fn spline_joints_and_a_closed_curves_seam_do_not_warn() {
for (curve, a) in [
("intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 open 3 0 2 1 1 2 2 0 0 0 100 0 0 100 100 0 } I I", [100.0, 0.0]),
(
"intcurve-curve $-1 -1 $-1 forward { exactcur 0 nubs 1 closed 5 0 2 1 1 2 1 3 1 4 2 0 0 0 100 0 0 100 100 0 0 100 0 0 0 0 } I I",
[0.0, 0.0],
),
] {
let edge = E { a, b: [100.0, 100.0], curve: Curve::Raw(curve.into()), flip: false, against: false };
let shape = vec![edge, line([100.0, 100.0], [0.0, 100.0]), line([0.0, 100.0], a)];
let r = import(&drawing("AC1015", &region_text(&sat(&[shape], None), false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
assert!(!outline(&r.document).elements().is_empty());
}
}
#[test]
fn a_transform_places_the_body() {
// Twice the size, moved 1000 along x.
let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2"));
let r = import(&drawing("AC1015", &region_text(&text, false), &[]), &points()).unwrap();
let b = filled_object(&r.document).geometric_bounds().unwrap();
assert!((b.width() - 20.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9, "{b:?}");
let h = r.document.artboards[0].rect.height();
assert!(Rect::new(b.x0, h - b.y1, b.x1, h - b.y0).contains(Point::new(1010.0, 10.0)), "{b:?}");
}
#[test]
fn missing_or_unreadable_body_transforms_leave_the_region_out() {
let text = sat(&[square(0.0, 10.0)], Some("1 0 0 0 1 0 0 0 1 1000 0 0 2"));
for damaged in [
text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $99999", 1),
text.replacen("body $-1 -1 $-1 $1 $-1 $5", "body $-1 -1 $-1 $1 $-1 $4", 1),
text.replacen("1 0 0 0 1 0 0 0 1 1000 0 0 2 no_rotate", "1 0 0 0 1 0 0 0 1 1000 0 no_rotate", 1),
text.replacen("1000 0 0 2 no_rotate", "1000 0 0 no_rotate", 1),
text.replacen("1000 0 0 2 no_rotate", "1000 0 0 unreadable no_rotate", 1),
text.replacen("1 0 0 0 1 0 0 0 1 1000", "1 unreadable 0 0 0 1 0 0 0 1 1000", 1),
] {
assert_ne!(damaged, text);
let r = import(&drawing("AC1015", &region_text(&damaged, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
assert!(outline(&r.document).elements().is_empty());
}
}
#[test]
fn missing_or_unreadable_edge_and_coedge_senses_leave_the_region_out() {
let text = sat(&[square(0.0, 10.0)], None);
for before in ["$8 forward $6", "$13 forward @7 unknown"] {
assert!(text.contains(before), "{text}");
for sense in ["", "unreadable"] {
let damaged = text.replacen(before, &before.replace("forward", sense), 1);
let r = import(&drawing("AC1015", &region_text(&damaged, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{before} {sense}: {:?}", r.warnings);
assert!(outline(&r.document).elements().is_empty());
}
}
}
#[test]
fn missing_curve_records_warn_when_edges_come_in_straight() {
let text = sat(&square_with_hole(), None);
let before = "$42 forward @7 unknown";
assert!(text.contains(before), "{text}");
let damaged = text.replacen(before, "$99999 forward @7 unknown", 1);
let r = import(&drawing("AC1015", &region_text(&damaged, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings);
check(&r.document, &[[10.0, 10.0], [50.0, 50.0]], &[[110.0, 50.0]]);
}
#[test]
fn disconnected_edges_warn_even_when_the_coedge_ring_is_complete() {
let mut edges = square(0.0, 100.0);
edges[1].a[0] += 5.0;
edges[1].b[0] += 5.0;
let mut closing = square(0.0, 100.0);
closing[3].b[0] += 5.0;
for edges in [edges, closing] {
let r = import(&drawing("AC1015", &region_text(&sat(&[edges], None), false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
check(&r.document, &[[50.0, 50.0]], &[[110.0, 50.0]]);
}
}
#[test]
fn unknown_curves_come_in_straight_and_damaged_data_is_left_out() {
let mut edges = square(0.0, 100.0);
edges[0].curve = Curve::Raw("helix-curve $-1 -1 $-1 0 0 0".into());
let r = import(&drawing("AC1015", &region_text(&sat(&[edges], None), false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("straight lines")), "{:?}", r.warnings);
check(&r.document, &[[50.0, 50.0]], &[]);
// A ring of coedges whose second points at itself ends there; a body pointing out of range
// and text that isn't data are listed as left out.
let ring = sat(&[square(0.0, 10.0)], None);
assert!(ring.contains("coedge $-1 -1 $-1 $21 $7 $-1"));
let ring = ring.replace("coedge $-1 -1 $-1 $21 $7 $-1", "coedge $-1 -1 $-1 $14 $7 $-1");
let wild = sat(&[square(0.0, 10.0)], None).replace("body $-1 -1 $-1 $1", "body $-1 -1 $-1 $99999");
let mut e = region_text(&ring, false);
for text in [wild.as_str(), "not data", "700 0 1 0\n"] {
e.extend(region_text(text, false));
}
let r = import(&drawing("AC1015", &e, &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("3 REGION")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
// The ring's two edges and the line that closes them.
check(&r.document, &[[8.0, 2.0]], &[[2.0, 8.0]]);
// A hole whose ring of coedges is missing is listed, not dropped quietly.
let holed = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None);
assert!(holed.contains("loop $-1 -1 $-1 $-1 $36 $3"), "{holed}");
let holed = holed.replace("loop $-1 -1 $-1 $-1 $36 $3", "loop $-1 -1 $-1 $-1 $99999 $3");
let r = import(&drawing("AC1015", &region_text(&holed, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{:?}", r.warnings);
}
#[test]
fn shared_topology_chains_are_walked_within_a_limit() {
// 100 lumps share one chain of 100 shells, each shell one chain of 100 faces: the first face
// a square, the others without loops. That is 1,000,000 faces visited, over the limit of
// records visited, though only 40,000 coedges.
let one = sat(&[square(0.0, 10.0)], None);
let mut recs: Vec<String> = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect();
let (lumps, shells, faces) = (recs.len(), recs.len() + 100, recs.len() + 200);
recs[0] = format!("body $-1 -1 $-1 ${lumps} $-1 $-1 #");
let next = |i: usize, n: usize, at: usize| if i + 1 < n { format!("${}", at + i + 1) } else { "$-1".into() };
for i in 0..100 {
recs.push(format!("lump $-1 -1 $-1 {} ${shells} $0 #", next(i, 100, lumps)));
}
for i in 0..100 {
recs.push(format!("shell $-1 -1 $-1 {} $-1 ${faces} $-1 ${lumps} #", next(i, 100, shells)));
}
for i in 0..100 {
let lp = if i == 0 { "$6" } else { "$-1" };
recs.push(format!("face $-1 -1 $-1 {} {lp} ${shells} $-1 $4 forward single #", next(i, 100, faces)));
}
let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::<Vec<_>>().join("\n"), recs.join("\n"));
let r = import(&drawing("AC1015", &region_text(&text, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
// One lump, shell and face of the same records come in.
let small = text.replacen(&format!("lump $-1 -1 $-1 ${} ", lumps + 1), "lump $-1 -1 $-1 $-1 ", 1);
let small = small.replacen(&format!("shell $-1 -1 $-1 ${} ", shells + 1), "shell $-1 -1 $-1 $-1 ", 1);
let small = small.replacen(&format!("face $-1 -1 $-1 ${} ", faces + 1), "face $-1 -1 $-1 $-1 ", 1);
let r = import(&drawing("AC1015", &region_text(&small, false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
check(&r.document, &[[5.0, 5.0]], &[[15.0, 5.0]]);
}
#[test]
fn broken_topology_chains_warn_when_the_next_record_is_missing_or_the_wrong_type() {
let text = sat(&[square(0.0, 100.0), square(40.0, 60.0)], None);
for (before, prefix) in [
("lump $-1 -1 $-1 $-1", "lump $-1 -1 $-1"),
("shell $-1 -1 $-1 $-1", "shell $-1 -1 $-1"),
("face $-1 -1 $-1 $-1", "face $-1 -1 $-1"),
("loop $-1 -1 $-1 $35", "loop $-1 -1 $-1"),
] {
for next in ["$99999", "$4"] {
assert!(text.contains(before), "{before}");
let broken = text.replacen(before, &format!("{prefix} {next}"), 1);
let r = import(&drawing("AC1015", &region_text(&broken, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("break off")), "{before} {next}: {:?}", r.warnings);
check(&r.document, &[[10.0, 10.0]], &[[110.0, 10.0]]);
}
}
}
#[test]
fn shared_spline_loops_are_left_out_when_their_generated_outline_is_too_large() {
// Many faces share one loop. Its degree-one spline follows a square with many knot spans,
// so generated elements reach their limit well before topology visits do.
let spans = 1024;
let mut curve = format!("intcurve-curve $-1 -1 $-1 forward {{ exactcur 0 nubs 1 closed {} 0 2", spans + 1);
for i in 1..spans {
curve.push_str(&format!(" {i} 1"));
}
curve.push_str(&format!(" {spans} 2"));
for i in 0..=spans {
let t = (i % (spans / 4)) as f64 / (spans / 4) as f64;
let (x, y) = match i / (spans / 4) {
0 => (t, 0.0),
1 => (1.0, t),
2 => (1.0 - t, 1.0),
_ => (0.0, 1.0 - t),
};
let (x, y) = if i == spans { (0.0, 0.0) } else { (x, y) };
curve.push_str(&format!(" {x} {y} 0"));
}
curve.push_str(" } I I");
let edge = E { a: [0.0, 0.0], b: [0.0, 0.0], curve: Curve::Raw(curve), flip: false, against: false };
let one = sat(&[vec![edge]], None);
let r = import(&drawing("AC1015", &region_text(&one, false), &[]), &points()).unwrap();
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
check(&r.document, &[[0.5, 0.5]], &[[1.5, 0.5]]);
let mut recs: Vec<String> = one.lines().skip(3).take_while(|l| !l.starts_with("End-of")).map(str::to_string).collect();
let faces = recs.len();
let count = super::build::MAX_ELEMENTS / (spans + 2) + 1;
recs[2] = format!("shell $-1 -1 $-1 $-1 $-1 ${faces} $-1 $1 #");
for i in 0..count {
let next = if i + 1 < count { format!("${}", faces + i + 1) } else { "$-1".into() };
recs.push(format!("face $-1 -1 $-1 {next} $6 $2 $-1 $4 forward single #"));
}
let text = format!("{}\n{}\nEnd-of-ACIS-data\n", one.lines().take(3).collect::<Vec<_>>().join("\n"), recs.join("\n"));
let r = import(&drawing("AC1015", &region_text(&text, false), &[]), &points()).unwrap();
assert!(r.warnings.iter().any(|w| w.contains("1 REGION")), "{:?}", r.warnings);
assert!(outline(&r.document).elements().is_empty());
}
+13 -1
View File
@@ -5,7 +5,8 @@
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
//! become polylines (straight segments) or cubic splines (curves), fills their outlines and solid
//! 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
//! or JPEG files the caller writes next to the drawing; with [`DxfOptions::group_blocks`] groups
//! become blocks placed by INSERT entities. 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.
@@ -14,16 +15,21 @@
//! clipping) is approximated or left out, and each such loss comes back as a warning.
//!
//! [`import()`] reads a DXF drawing (ASCII or binary, any version) into a document: see [`import`].
//! It reads a DWG drawing too, converted to DXF by [`dwg`].
//! [`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.
//! - 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.
//! - `dwg`: DWG drawings converted to DXF by craft-dwg, in a child process on desktop builds.
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
#![doc(test(attr(deny(unsafe_code))))]
mod aci;
// Temporary until storytold/craft-libs#5381 merges and the craft-libs pin moves past it.
mod blocks_compat;
pub mod dwg;
#[cfg(test)]
mod expansion_test;
pub mod hpgl;
@@ -34,6 +40,7 @@ use vectorcraft_doc::{Document, Unit};
use vectorcraft_geom::Rect;
pub use aci::{aci_rgb, nearest_aci};
pub use dwg::is_dwg;
pub use import::{DxfInfo, ImportOptions, Imported, import, info, is_dxf};
/// How deep symbols, blocks and brush art may nest in one another (deeper art is left out).
@@ -312,6 +319,10 @@ pub struct DxfOptions {
pub alter_paths: bool,
/// Type is written as glyph outlines (always with [`Preserve::Appearance`]).
pub outline_text: bool,
/// Always Export Group as Block Reference: each group is written as a block definition of its
/// contents, placed by an INSERT entity on the group's layer (groups inside it are blocks
/// placed inside that block). Off: a group's contents are written as plain entities.
pub group_blocks: bool,
/// The drawing's origin is this region's bottom-left corner (document space).
pub region: Rect,
/// Leave out objects entirely outside `region` (one drawing per artboard).
@@ -332,6 +343,7 @@ impl Default for DxfOptions {
preserve: Preserve::default(),
alter_paths: false,
outline_text: false,
group_blocks: false,
region: Rect::ZERO,
crop: false,
}
+51 -13
View File
@@ -2,7 +2,8 @@
//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with
//! hatches left out), placed images are linked image files unless left out, strokes
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
//! filled outlines where the look needs them.
//! filled outlines where the look needs them. With [`DxfOptions::group_blocks`] each group is a
//! block, placed by an INSERT.
use std::collections::HashMap;
@@ -14,6 +15,8 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
use crate::aci::nearest_aci;
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
// Block and the INSERT writer come from craft-libs#5381 once it merges; see `blocks_compat`.
use crate::blocks_compat::Block;
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
@@ -503,8 +506,13 @@ pub(crate) struct Scene<'a> {
to_dxf: Affine,
/// Drawing units per point.
k: f64,
/// The entities written so far.
/// The entities written so far: those of model space, or of the group block being written.
e: Codes,
/// The owner of the entities in `e`: model space, or the group block's record.
owner: Handle,
/// Group blocks written so far ([`DxfOptions::group_blocks`]), each after the blocks it inserts.
blocks: Vec<Block>,
block_names: Names,
next: u32,
layers: Vec<Layer>,
layer_names: Names,
@@ -544,6 +552,9 @@ impl<'a> Scene<'a> {
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
k,
e: Codes::new(o.version.into()),
owner: fixed::MODEL_RECORD,
blocks: vec![],
block_names: Names::with(&["*Model_Space", "*Paper_Space"]),
next: fixed::FIRST_FREE,
layers: vec![],
layer_names: Names::with(&["0", "Defpoints"]),
@@ -593,7 +604,12 @@ impl<'a> Scene<'a> {
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
DxfOutput {
bytes: crate::blocks_compat::write(drawing, &self.blocks).into_bytes(),
images: self.files,
warnings: self.warnings,
setting_notes: self.setting_notes,
}
}
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
@@ -660,6 +676,7 @@ impl<'a> Scene<'a> {
self.children(children, *clip);
(self.layer, self.flags) = outer;
}
NodeKind::Group { children, clip } if self.o.group_blocks => self.group_block(n, children, *clip),
NodeKind::Group { children, clip } => self.children(children, *clip),
NodeKind::Path { path, rule, guide, .. } => {
if !*guide {
@@ -754,6 +771,27 @@ impl<'a> Scene<'a> {
}
}
/// Group `n` as a block of its children's entities and an INSERT that places it on the current
/// layer ([`DxfOptions::group_blocks`]). The block's base point is the drawing's origin, so its
/// entities keep their coordinates. A group that writes no entity writes no block.
fn group_block(&mut self, n: &Node, children: &[std::sync::Arc<Node>], clip: bool) {
let (record, begin, end, insert) = (self.handle(), self.handle(), self.handle(), self.handle());
let outer = std::mem::replace(&mut self.e, Codes::new(self.o.version.into()));
let owner = std::mem::replace(&mut self.owner, record);
self.children(children, clip);
let entities = std::mem::replace(&mut self.e, outer).into_string();
self.owner = owner;
if entities.is_empty() {
return;
}
let long = self.o.version.r2000();
let base = symbol_name(n.name.as_deref().unwrap_or_default(), long);
let base = if base.is_empty() { symbol_name("Group", long) } else { base };
let name = self.block_names.unique(&base, if long { 255 } else { 31 });
crate::blocks_compat::insert(&mut self.e, insert, self.owner, &self.layer, &name);
self.blocks.push(Block { name, record, begin, end, entities });
}
/// Warn about what DXF can't hold in `n`'s look.
fn note_losses(&mut self, n: &Node) {
if n.blend != vectorcraft_color::BlendMode::Normal {
@@ -959,7 +997,7 @@ impl<'a> Scene<'a> {
}
let h = self.handle();
let layer = self.layer.clone();
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
self.e.entity("HATCH", h, self.owner, &layer, style, "AcDbHatch");
self.e.xyz(10, 0.0, 0.0);
self.e.normal();
self.e.raw(2, "SOLID");
@@ -1040,7 +1078,7 @@ impl<'a> Scene<'a> {
let (a, b) = (self.pt(a), self.pt(b));
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("LINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbLine");
self.e.entity("LINE", h, self.owner, &layer, style, "AcDbLine");
self.e.xyz(10, a.x, a.y);
self.e.xyz(11, b.x, b.y);
}
@@ -1058,7 +1096,7 @@ impl<'a> Scene<'a> {
// Bit 128: a linetype runs on through the vertices instead of restarting at each one.
let flags = i64::from(closed) | if style.linetype.is_some() { 128 } else { 0 };
if self.o.version.lwpolyline() {
self.e.entity("LWPOLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbPolyline");
self.e.entity("LWPOLYLINE", h, self.owner, &layer, style, "AcDbPolyline");
self.e.int(90, pts.len() as i64);
self.e.int(70, flags);
if let Some(w) = width {
@@ -1072,7 +1110,7 @@ impl<'a> Scene<'a> {
}
return;
}
self.e.entity("POLYLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDb2dPolyline");
self.e.entity("POLYLINE", h, self.owner, &layer, style, "AcDb2dPolyline");
self.e.int(66, 1);
self.e.xyz(10, 0.0, 0.0);
self.e.int(70, flags);
@@ -1134,7 +1172,7 @@ impl<'a> Scene<'a> {
let layer = self.layer.clone();
let h = self.handle();
if sub.closed {
self.e.entity("CIRCLE", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle");
self.e.entity("CIRCLE", h, self.owner, &layer, style, "AcDbCircle");
self.e.xyz(10, centre.x, centre.y);
self.e.num(40, radius);
self.e.normal();
@@ -1150,7 +1188,7 @@ impl<'a> Scene<'a> {
if !on_ccw_arc(a0, a1, am) {
std::mem::swap(&mut a0, &mut a1);
}
self.e.entity("ARC", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle");
self.e.entity("ARC", h, self.owner, &layer, style, "AcDbCircle");
self.e.xyz(10, centre.x, centre.y);
self.e.num(40, radius);
self.e.normal();
@@ -1197,7 +1235,7 @@ impl<'a> Scene<'a> {
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("ELLIPSE", h, fixed::MODEL_RECORD, &layer, style, "AcDbEllipse");
self.e.entity("ELLIPSE", h, self.owner, &layer, style, "AcDbEllipse");
self.e.xyz(10, centre.x, centre.y);
self.e.xyz(11, axis.x, axis.y);
self.e.normal();
@@ -1232,7 +1270,7 @@ impl<'a> Scene<'a> {
let ctrl: Vec<Point> = ctrl.iter().map(|p| self.pt(*p)).collect();
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("SPLINE", h, fixed::MODEL_RECORD, &layer, style, "AcDbSpline");
self.e.entity("SPLINE", h, self.owner, &layer, style, "AcDbSpline");
self.e.normal();
// Planar (bit 3) and, if the subpath is closed, also closed (bit 0). A geometrically
// closed cut needs the closed flag set so CAM/CAM tools (e.g. VCarve) treat it as a
@@ -1308,7 +1346,7 @@ impl<'a> Scene<'a> {
let p = self.pt(t.xf * origin);
let layer = self.layer.clone();
let h = self.handle();
self.e.entity("TEXT", h, fixed::MODEL_RECORD, &layer, &style, "AcDbText");
self.e.entity("TEXT", h, self.owner, &layer, &style, "AcDbText");
self.e.xyz(10, p.x, p.y);
self.e.num(40, height);
let s: String = s.chars().take(MAX_TEXT).collect();
@@ -1368,7 +1406,7 @@ impl<'a> Scene<'a> {
let def = def.handle;
let layer = self.layer.clone();
let style = EntityStyle { aci: 7, ..EntityStyle::default() };
self.e.entity("IMAGE", handle, fixed::MODEL_RECORD, &layer, &style, "AcDbRasterImage");
self.e.entity("IMAGE", handle, self.owner, &layer, &style, "AcDbRasterImage");
self.e.int(90, 0);
self.e.xyz(10, at.x, at.y);
self.e.xyz(11, u.x, u.y);
+2
View File
@@ -8,6 +8,8 @@ use vectorcraft_geom::{Affine, ParamCurve, PathData, Point, Rect, Shape, shapes}
use crate::*;
mod blocks;
type Pairs = Vec<(i32, String)>;
/// The `(code, value)` pairs of a DXF file.
+125
View File
@@ -0,0 +1,125 @@
//! Always Export Group as Block Reference: groups written as blocks placed by INSERT entities.
use super::*;
/// The user blocks of a drawing (not model or paper space): each its name and the entities
/// between its BLOCK and its ENDBLK.
fn blocks(out: &DxfOutput) -> Vec<(String, Vec<Pairs>)> {
let mut found: Vec<(String, Vec<Pairs>)> = vec![];
let mut open = false;
for o in section(&pairs(&out.bytes), "BLOCKS") {
match kind(&o) {
"BLOCK" => {
found.push((get(&o, 2).unwrap_or_default().to_string(), vec![]));
open = true;
}
"ENDBLK" => open = false,
_ if open => found.last_mut().expect("a block").1.push(o),
_ => {}
}
}
found.retain(|(name, _)| !name.starts_with('*'));
found
}
/// A filled square outside any group; the group `Frame` holding a stroked rectangle and the group
/// `Ring` holding a circle, on a second layer `Parts`.
fn grouped_doc() -> Document {
let mut d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(150.0, 10.0, 170.0, 30.0)), Paint::solid(Color::BLACK), Paint::None, 0.0)]);
let parts = d.add_layer(Some("Parts"));
let rect = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0);
let circle = path(&mut d, shapes::ellipse(Rect::new(40.0, 20.0, 70.0, 50.0)), Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let mut ring = Node::group(d.alloc_id(), vec![Arc::new(circle)]);
ring.name = Some("Ring".into());
let mut frame = Node::group(d.alloc_id(), vec![Arc::new(rect), Arc::new(ring)]);
frame.name = Some("Frame".into());
d.insert(Some(parts), usize::MAX, frame).unwrap();
d
}
#[test]
fn groups_are_blocks_placed_by_inserts_in_every_version() {
let d = grouped_doc();
for v in DxfVersion::ALL {
let out = export(&d, &DxfOptions { version: v, group_blocks: true, ..opts(&d) }).unwrap();
let top = entities(&out);
let inserts: Vec<&Pairs> = top.iter().filter(|e| kind(e) == "INSERT").collect();
assert_eq!(inserts.len(), 1, "{v:?}: the outer group alone is placed in model space");
// Before 2000, names are capitals, letters, digits and $-_ only.
let long = v >= DxfVersion::R2000;
let (frame, ring, parts, first) = if long { ("Frame", "Ring", "Parts", "Layer 1") } else { ("FRAME", "RING", "PARTS", "LAYER_1") };
assert_eq!((get(inserts[0], 2), get(inserts[0], 8)), (Some(frame), Some(parts)), "{v:?}");
assert!(top.iter().any(|e| kind(e) != "INSERT" && get(e, 8) == Some(first)), "{v:?}: the loose square stays in model space");
let found = blocks(&out);
let names: Vec<&str> = found.iter().map(|b| b.0.as_str()).collect();
assert_eq!(names, [ring, frame], "{v:?}: the inner block comes first");
let (ring_entities, frame_entities) = (&found[0].1, &found[1].1);
assert!(!ring_entities.is_empty() && ring_entities.iter().all(|e| kind(e) != "INSERT"), "{v:?}: the circle is in its group's block");
let nested: Vec<&Pairs> = frame_entities.iter().filter(|e| kind(e) == "INSERT").collect();
assert_eq!(nested.len(), 1, "{v:?}: the inner group is placed inside the outer block");
assert_eq!(get(nested[0], 2), Some(ring), "{v:?}");
assert!(frame_entities.iter().any(|e| kind(e) != "INSERT"), "{v:?}: the rectangle is in the outer block");
if v >= DxfVersion::R13 {
// Each block's entities are owned by its BLOCK_RECORD, and the INSERTs by what holds them.
let records = table(&out, "BLOCK_RECORD");
let record = |name: &str| records.iter().find(|r| get(r, 2) == Some(name)).and_then(|r| get(r, 5).map(str::to_string));
for (name, ents) in &found {
let owner = record(name).unwrap_or_else(|| panic!("{v:?}: no BLOCK_RECORD for {name}"));
// A polyline's vertices and its SEQEND are owned by the polyline.
let owned: Vec<&Pairs> = ents.iter().filter(|e| !matches!(kind(e), "VERTEX" | "SEQEND")).collect();
assert!(!owned.is_empty() && owned.iter().all(|e| get(e, 330) == Some(owner.as_str())), "{v:?}: {name}");
}
assert_eq!(get(inserts[0], 330).map(str::to_string), record("*Model_Space"), "{v:?}: the outer INSERT is in model space");
assert_eq!(get(nested[0], 330).map(str::to_string), record(frame), "{v:?}: the inner INSERT is in the outer block");
}
}
}
#[test]
fn without_the_option_groups_are_written_as_their_contents() {
let d = grouped_doc();
let out = export(&d, &opts(&d)).unwrap();
assert!(blocks(&out).is_empty());
assert!(!kinds(&out).iter().any(|k| k == "INSERT"));
let with = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap();
// The same entities are written, moved into blocks.
let count = |o: &DxfOutput| {
let drawn = |ents: &[Pairs]| ents.iter().filter(|e| kind(e) != "INSERT").count();
drawn(&entities(o)) + blocks(o).iter().map(|b| drawn(&b.1)).sum::<usize>()
};
assert_eq!(count(&out), count(&with));
assert_eq!(header(&pairs(&out.bytes), "$EXTMIN"), header(&pairs(&with.bytes), "$EXTMIN"));
assert_eq!(header(&pairs(&out.bytes), "$EXTMAX"), header(&pairs(&with.bytes), "$EXTMAX"));
}
#[test]
fn blocks_read_back_at_the_place_their_group_was() {
let d = grouped_doc();
let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() };
let plain = import(&export(&d, &opts(&d)).unwrap().bytes, &o).unwrap().document;
let blocked = import(&export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap().bytes, &o).unwrap().document;
let names: Vec<&str> = blocked.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(names.contains(&"Frame") && names.contains(&"Ring"), "{names:?}");
let (a, b) = (plain.art_bounds().unwrap(), blocked.art_bounds().unwrap());
assert!(close_to(&[a.x0, a.y0, a.x1, a.y1], &[b.x0, b.y0, b.x1, b.y1], 1e-6), "{a:?} against {b:?}");
}
#[test]
fn a_group_with_nothing_written_is_no_block_and_names_stay_unique() {
let mut d = Document::new(200.0, 100.0);
let layer = d.layers[0].id;
let mut hidden = path(&mut d, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Paint::solid(Color::BLACK), Paint::None, 0.0);
hidden.visible = false;
let empty = Node::group(d.alloc_id(), vec![Arc::new(hidden)]);
d.insert(Some(layer), usize::MAX, empty).unwrap();
for name in [Some("Part"), Some("part"), None, Some("*Model_Space")] {
let p = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut g = Node::group(d.alloc_id(), vec![Arc::new(p)]);
g.name = name.map(str::to_string);
d.insert(Some(layer), usize::MAX, g).unwrap();
}
let out = export(&d, &DxfOptions { group_blocks: true, ..opts(&d) }).unwrap();
let names: Vec<String> = blocks(&out).into_iter().map(|b| b.0).collect();
assert_eq!(names, ["Part", "part_2", "Group", "_Model_Space"], "the hidden-only group writes no block");
assert_eq!(kinds(&out).iter().filter(|k| *k == "INSERT").count(), 4);
}
+5
View File
@@ -15,6 +15,8 @@ spine-count = []
symbol-read-count = []
# `vectorcraft_doc::locked_artboard_measures` for other crates' tests (dev-dependencies only).
locked-artboard-count = []
# `vectorcraft_doc::swatches::swatch_scans` for other crates' tests (dev-dependencies only).
swatch-scans = []
[dependencies]
vectorcraft-geom = { workspace = true }
@@ -39,3 +41,6 @@ flate2 = { workspace = true }
zune-jpeg = { workspace = true }
jpeg-encoder = { workspace = true }
proptest = { workspace = true }
# The counter vectorcraft-ui-egui's tests turn on, also when this crate is tested without
# vectorcraft-ui-egui (`cargo xtask ci shard`).
vectorcraft-doc = { path = ".", features = ["swatch-scans"] }
+151 -17
View File
@@ -28,40 +28,48 @@ pub fn resolve_stored_radii(base: &PathData, stored: &[f64], relative: bool) ->
out
}
fn dormant_radius_scale(base: &PathData) -> f64 {
base.length().max(1e-12)
}
/// Turn stored absolute radii into fractions of each corner's maximum, or the other way.
/// Anchors without a cuttable corner use the outline's length (at least 1e-12 document units).
/// Their fractions are not capped at 1.
/// When an anchor edit straightens or bends a corner, [`edit_corner_anchors`] converts its
/// radius between these reference lengths, preserving its document length at that edit.
pub fn convert_radii_relative(live: &mut LiveShape, relative: bool) {
if live.radii_relative() == relative {
return;
}
let was_relative = live.radii_relative();
let base = match live {
LiveShape::Rectangle { w, h, .. } => shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)),
LiveShape::Polygon { .. } => live.polygon_outline(),
LiveShape::Polygon { .. } | LiveShape::Star { .. } => live.polygon_outline(),
LiveShape::Path { base, .. } => base.clone(),
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
let corners = path_corners(&base);
let dormant_scale = dormant_radius_scale(&base);
let radii: &mut [f64] = match live {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } => radii,
LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return,
};
for c in corners {
if let Some(r) = radii.get(c.index) {
let max = c.max_radius();
radii[c.index] = if relative {
if max > 1e-12 && !was_relative { (*r / max).clamp(0.0, 1.0) } else { *r }
} else if was_relative {
(*r).clamp(0.0, 1.0) * max
} else {
*r
};
for (index, r) in radii.iter_mut().enumerate() {
let corner = corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &corners[i]);
let max = corner.map_or(dormant_scale, Corner::max_radius);
if relative {
if max > 0.0 {
*r = if corner.is_some() { (*r / max).clamp(0.0, 1.0) } else { (*r / max).max(0.0) };
}
} else {
*r = if corner.is_some() { (*r).clamp(0.0, 1.0) } else { (*r).max(0.0) } * max;
}
}
match live {
LiveShape::Rectangle { radii_relative: rel, .. }
| LiveShape::Polygon { radii_relative: rel, .. }
| LiveShape::Star { radii_relative: rel, .. }
| LiveShape::Path { radii_relative: rel, .. } => {
*rel = relative;
}
@@ -99,7 +107,7 @@ impl<'a> LiveCorners<'a> {
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = l.folded() else { return None };
(Cow::Owned(shapes::rectangle(Rect::new(0.0, 0.0, w, h))), xf, radii.to_vec(), kinds.to_vec(), radii_relative)
}
Some(l @ LiveShape::Polygon { radii, kinds, radii_relative, .. }) => {
Some(l @ (LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. })) => {
(Cow::Owned(l.polygon_outline()), Affine::IDENTITY, radii.clone(), kinds.clone(), *radii_relative)
}
Some(LiveShape::Path { base, radii, kinds, radii_relative }) => {
@@ -142,7 +150,8 @@ impl<'a> LiveCorners<'a> {
}
/// The radius corner `index` is stored at: document lengths, or a fraction in 0..1 when
/// [`LiveCorners::radii_relative`].
/// [`LiveCorners::radii_relative`]. Dormant anchors use the reference length documented in
/// [`convert_radii_relative`], and their fractions can exceed 1.
pub fn radius(&self, index: usize) -> f64 {
self.radii.get(index).copied().unwrap_or(0.0)
}
@@ -205,8 +214,8 @@ impl<'a> LiveCorners<'a> {
/// Set `radius` (document units; negative: 0) and/or `kind` on the `corners` (anchor indices of
/// the uncut outline, see [`LiveCorners`]) of a path and its live shape, then cut the path again.
/// A path that isn't a live shape keeps its uncut outline as a [`LiveShape::Path`], which is a
/// plain path again once no corner is cut. Ellipses and lines have no corners: they stay as they
/// are.
/// plain path again once no radius or nondefault corner kind is stored. A straight anchor keeps
/// its stored radius. Ellipses and lines have no corners: they stay as they are.
pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corners: &BTreeSet<usize>, radius: Option<f64>, kind: Option<CornerKind>) {
fn edit(
base: &PathData,
@@ -258,6 +267,14 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
edit(&outline, relative, radii, kinds, corners, radius, kind);
trim_vec_radii(radii, kinds);
}
LiveShape::Star { r1, r2, points, xf, radii, kinds, .. } => {
let outline = shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf);
let n = 2 * *points as usize;
radii.resize(n, 0.0);
kinds.resize(n, CornerKind::Round);
edit(&outline, relative, radii, kinds, corners, radius, kind);
trim_vec_radii(radii, kinds);
}
LiveShape::Path { base, radii, kinds, .. } => {
let n = base.anchor_count();
radii.resize(n, 0.0);
@@ -277,6 +294,81 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
}
}
/// Convert relative `radii` (fractions, one per anchor of the outline) after the outline changed
/// from `before` to `after`: a corner that straightened keeps its document length as a fraction of
/// `after`'s length, and a corner that bent again takes that length back as a fraction of its new
/// maximum. Other radii are left as they are.
pub fn rebase_relative_radii(before: &PathData, after: &PathData, radii: &mut [f64]) {
let (old_corners, new_corners) = (path_corners(before), path_corners(after));
let (old_dormant_scale, new_dormant_scale) = (dormant_radius_scale(before), dormant_radius_scale(after));
for (index, r) in radii.iter_mut().enumerate() {
let old = old_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &old_corners[i]);
let new = new_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &new_corners[i]);
match (old, new) {
(Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale,
(None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0),
_ => {}
}
}
}
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
/// [`LiveShape::Path`] with that outline. [`LiveCorners::sources`] before and after the edit map
/// the anchors as drawn to the corners they come from.
/// Returns `None`, leaving the path unchanged, when the path has no live shape or
/// no corner with a radius, or is a rectangle sheared or scaled unevenly.
pub fn edit_corner_anchors(
path: &mut PathData,
live: &mut Option<Box<LiveShape>>,
anchors: &BTreeSet<AnchorRef>,
edit: impl FnOnce(&mut PathData, &BTreeSet<AnchorRef>),
) -> Option<()> {
live.as_ref()?;
if let Some(LiveShape::Rectangle { xf, .. }) = live.as_deref() {
let [a, b, c, d, _, _] = xf.as_coeffs();
let scale = (a * a + b * b).max(c * c + d * d).max(1e-12);
if ((a * a + b * b) - (c * c + d * d)).abs() > 1e-9 * scale || (a * c + b * d).abs() > 1e-9 * scale {
return None;
}
}
let (mut base, moved, mut radii, kinds, relative) = {
let lc = LiveCorners::new(path, live.as_deref())?;
// The stored radii decide, not the drawn ones: a corner the edit straightened draws no
// arc but keeps its radius, and rounds again when a later edit bends it.
if !lc.radii.iter().any(|r| *r > 0.0) {
return None;
}
let moved: BTreeSet<usize> = anchors.iter().filter_map(|(si, ai)| lc.sources.get(*si)?.get(*ai).copied()).collect();
if moved.is_empty() {
return None;
}
let mut radii = lc.radii.clone();
radii.resize(lc.base.anchor_count(), 0.0);
(lc.base.transformed(lc.xf), moved, radii, lc.kinds.clone(), lc.relative)
};
let mut on_base = BTreeSet::new();
let mut k = 0;
for (si, sp) in base.subpaths.iter().enumerate() {
for ai in 0..sp.anchors.len() {
if moved.contains(&k) {
on_base.insert((si, ai));
}
k += 1;
}
}
let before = relative.then(|| base.clone());
edit(&mut base, &on_base);
if let Some(before) = before {
rebase_relative_radii(&before, &base, &mut radii);
}
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
*path = l.to_path();
*live = Some(Box::new(l));
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -363,6 +455,48 @@ mod tests {
assert!(!p.transform(Affine::translate((5.0, 0.0))), "a move needs no new cuts");
}
/// Moving the anchor of the only rounded corner into a straight line and back keeps its
/// stored radius, so the corner is rounded again.
#[test]
fn a_straightened_corner_rounds_again_when_it_bends_back() {
let pen = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 80.0)], false));
let (mut path, mut live) = (pen.clone(), None);
set_corners(&mut path, &mut live, &set(&[1]), Some(10.0), None);
let corner = LiveCorners::new(&path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let move_corner = |path: &mut PathData, live: &mut Option<Box<LiveShape>>, to: Point| {
let sel = LiveCorners::new(path, live.as_deref()).unwrap().anchors_of(&set(&[1]));
let sel = if sel.is_empty() { anchors(&[1]) } else { sel };
edit_corner_anchors(path, live, &sel, |base, on_base| {
for &(si, ai) in on_base {
if let Some(a) = base.anchor_mut(si, ai) {
(a.p, a.h_in, a.h_out) = (to, to, to);
}
}
})
};
assert_eq!(corner.len(), 2, "the corner is cut");
// Straight: the corner has nothing to cut.
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert!(matches!(live.as_deref(), Some(LiveShape::Path { radii, .. }) if radii.get(1) == Some(&10.0)));
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0, "the straight corner draws no arc");
// Bent again: the stored radius cuts it again.
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some(), "the straightened corner stays live");
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius: {live:?}");
for relative in [true, false] {
assert!(move_corner(&mut path, &mut live, Point::new(50.0, 40.0)).is_some());
assert_eq!(LiveCorners::new(&path, live.as_deref()).unwrap().drawn_radius(1), 0.0);
let l = live.as_deref_mut().unwrap();
convert_radii_relative(l, relative);
assert_eq!(l.radii_relative(), relative);
path = l.to_path();
assert!(move_corner(&mut path, &mut live, Point::new(100.0, 0.0)).is_some());
let c = LiveCorners::new(&path, live.as_deref()).unwrap();
assert!((c.drawn_radius(1) - 10.0).abs() < 1e-6, "the corner keeps its radius after changing modes: {live:?}");
}
}
#[test]
fn relative_radii_scale_with_rectangle_size() {
let l = LiveShape::Rectangle {
+55 -14
View File
@@ -318,7 +318,7 @@ impl Document {
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
/// [`Document::index_path`] finds it.
pub fn node(&self, id: NodeId) -> Option<&Node> {
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id).or_else(|| cached.added_node_in(&self.layers, id))) {
crate::id_index::note_path_lookup();
return Some(n);
}
@@ -365,10 +365,21 @@ impl Document {
Some(None) => return self.walk_index_path(id),
_ => {}
}
let stale = cached.contains_key(&id);
// An id the table doesn't have, at the path an earlier walk found for it, while the node
// there still has the id.
if !stale
&& let Some(p) = cached.added(&id)
&& self.node_at(&p).is_some_and(|n| n.id == id)
{
return Some(p);
}
// A stale path (the tree changed) or an id the cache doesn't have (deleted or added
// since): walk, and rebuild now and then.
let found = self.walk_index_path(id);
let stale = cached.contains_key(&id);
if !stale && let Some(p) = &found {
cached.note_added(id, p);
}
if (stale || found.is_some()) && self.index.missed() {
self.index.rebuild(&self.layers);
}
@@ -425,23 +436,37 @@ impl Document {
// Cached paths that still check out ([`id_index`]); the rest take one walk. For a good
// share of the document, one walk is quicker than checking each cached path.
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
want.retain(|id| match cache.get(id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
want.retain(|id| match self.cached_path(&cache, *id) {
Some(p) => {
out.insert(*id, p);
false
}
_ => true,
None => true,
});
}
if !want.is_empty() {
crate::id_index::note_tree_walk();
let mut rest = HashMap::with_capacity(want.len());
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
// The cache keeps the paths of found ids it doesn't have, for the next lookup.
if let Some(cache) = self.index.get().filter(|_| rest.len() <= crate::id_index::ADDED_PATHS) {
rest.iter().for_each(|(id, p)| cache.note_added(*id, p));
}
out.extend(rest);
}
out
}
/// The path the lookup cache `cache` has for `id`, while the node there has the id: the table's
/// path, or for an id the table doesn't have, the path an earlier walk found ([`id_index`]).
fn cached_path(&self, cache: &crate::id_index::Paths, id: NodeId) -> Option<Vec<usize>> {
let p = match cache.get(&id) {
Some(p) => p?,
None => cache.added(&id)?,
};
self.node_at(&p).is_some_and(|n| n.id == id).then_some(p)
}
/// 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
@@ -452,7 +477,8 @@ impl Document {
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 cache = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len());
if let Some(cache) = &cache {
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) => {
@@ -476,6 +502,10 @@ impl Document {
out.push(n);
}
});
// Found ids the table doesn't have count toward a rebuild for later ordered lookups.
if cache.is_some_and(|cache| out.iter().any(|n| !cache.contains_key(&n.id))) && self.index.missed() {
self.index.rebuild(&self.layers);
}
}
out
}
@@ -584,10 +614,14 @@ impl Document {
/// Remove a node and return it.
pub fn remove(&mut self, id: NodeId) -> Result<Arc<Node>, DocError> {
let parent = self.parent_of(id);
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
let idx = *path.last().ok_or(DocError::NoNode(id))?;
let ch = self.children_mut(parent)?;
self.remove_at(id, &path)
}
/// Remove the node at `path`, the index path [`Document::index_path`] gave for `id`, and return it.
fn remove_at(&mut self, id: NodeId, path: &[usize]) -> Result<Arc<Node>, DocError> {
let (&idx, up) = path.split_last().ok_or(DocError::NoNode(id))?;
let ch = self.children_at(up).ok_or(DocError::NoNode(id))?;
if idx >= ch.len() {
return Err(DocError::NoNode(id));
}
@@ -602,10 +636,11 @@ impl Document {
{
return Err(DocError::Invalid("cannot move an object into itself".into()));
}
if let Some(n) = self.node(id) {
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
if let Some(n) = self.node_at(&path) {
self.check_ruler_guide_place(n, parent)?;
}
let n = self.remove(id)?;
let n = self.remove_at(id, &path)?;
let ch = self.children_mut(parent)?;
let i = Node::insert_index(ch, index, &n);
ch.insert(i, n);
@@ -623,9 +658,15 @@ impl Document {
/// Position of `id` within its parent: (parent, index, sibling count).
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
let parent = self.parent_of(id);
let idx = *self.index_path(id)?.last()?;
let n = self.children(parent)?.len();
let path = self.index_path(id)?;
let (&idx, up) = path.split_last()?;
let (parent, n) = match up {
[] => (None, self.layers.len()),
_ => {
let parent = self.node_at(up)?;
(Some(parent.id), parent.children()?.len())
}
};
Some((parent, idx, n))
}
+46
View File
@@ -239,6 +239,52 @@ impl Document {
round_json_paths(brushes, &round);
}
}
/// Make every live star a plain path of the outline it draws, for a save that versions before
/// live stars read: in the art of the layers, symbols, graph designs, pattern swatches and the
/// pattern definition that pattern editing's Cancel puts back (opacity-mask art included), and
/// in the brush definitions.
pub fn live_stars_to_paths(&mut self) {
let is_star = |n: &Node| matches!(n.live_shape(), Some(LiveShape::Star { .. }));
let mut plain = |n: &mut Node| {
if let NodeKind::Path { live, .. } = &mut n.kind
&& matches!(live.as_deref(), Some(LiveShape::Star { .. }))
{
*live = None;
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
edit_branches_where(root, &is_star, &mut plain);
}
if let Some(brushes) = self.unknown.get_mut("brushes") {
json_stars_to_paths(brushes);
}
}
}
/// Take `live` off every serialized path object (`type: "path"`) in `v` whose live shape is a
/// star.
fn json_stars_to_paths(v: &mut serde_json::Value) {
use serde_json::Value;
match v {
Value::Object(o) => {
if o.get("type").and_then(Value::as_str) == Some("path")
&& o.get("live").and_then(|l| l.get("shape")).and_then(Value::as_str) == Some("star")
{
o.remove("live");
}
o.values_mut().for_each(json_stars_to_paths);
}
Value::Array(a) => a.iter_mut().for_each(json_stars_to_paths),
_ => {}
}
}
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
+48 -4
View File
@@ -4,10 +4,15 @@
//! The tree is edited in many places through public fields, so the cache can't be kept in step
//! with it. It is checked instead: a cached path is used only while the node at that path still
//! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache,
//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before.
//! and an id the cache doesn't have (added since, or removed) is looked up by walking.
//! An id that appears more than once (a damaged file) is never cached, so lookups keep returning
//! its first place in tree order.
//!
//! The path a walk finds for an id the table doesn't have is kept beside the table, shared by every
//! document that reads it, and checked the same way before it is used. Documents that each start
//! from the same copy and add the same object (every preview of a drag starts from the document as
//! it was at the press) then find that object without walking the tree.
//!
//! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache
//! places each node after a removed sibling one lower and finds no path for a removed node or one
//! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first
@@ -16,8 +21,10 @@
//! The one case a cached lookup can answer differently from a walk: a second node with an
//! existing id put in the tree *after* the cache was built, earlier in tree order than the first.
//! The lookup then returns the original node (also one with that id) instead of the new one. The
//! app never makes such a node (paste and duplicate give new ids, undo restores whole trees);
//! duplicated ids come from damaged files, which are cached afresh when opened.
//! same holds for an id the table doesn't have: once a walk in one document has found it, a copy
//! that holds a second node with that id earlier in tree order gets the node at the path the walk
//! found. The app never makes such a node (paste and duplicate give new ids, undo restores whole
//! trees); duplicated ids come from damaged files, which are cached afresh when opened.
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
@@ -65,8 +72,15 @@ type Gaps = HashMap<u32, Vec<u32>>;
pub(crate) struct Paths {
table: Arc<Table>,
gaps: Arc<Gaps>,
/// The index paths that walks found for ids the table doesn't have, at most [`ADDED_PATHS`] of
/// them. Every document that reads the table reads them too, and checks a path against its own
/// tree before using it.
added: Arc<RwLock<IdMap<Vec<usize>>>>,
}
/// The most paths [`Paths`] keeps for ids its table doesn't have; one more lets the kept ones go.
pub(crate) const ADDED_PATHS: usize = 4096;
/// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level
/// layer) and its index among its siblings. One flat table, so building it allocates nothing per
/// node.
@@ -152,6 +166,36 @@ impl Paths {
Err(k) => Some(i - k as u32),
}
}
/// The index path a walk found for `id`, an id the table doesn't have ([`Paths::note_added`]);
/// the caller checks that the node there has the id.
pub(crate) fn added(&self, id: &NodeId) -> Option<Vec<usize>> {
let path = self.added.read().ok()?.get(id)?.clone();
note_path_copy();
Some(path)
}
/// The node with `id` in `layers` at the path [`Paths::added`] has for it, found without copying
/// the path: `None` when there is none or the node there does not have the id.
pub(crate) fn added_node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
let added = self.added.read().ok()?;
let (first, rest) = added.get(&id)?.split_first()?;
let mut node: &Node = layers.get(*first)?;
for &i in rest {
node = node.children()?.get(i)?;
}
(node.id == id).then_some(node)
}
/// Keep `path`, which a walk found for `id`, when the table doesn't have `id`. Past
/// [`ADDED_PATHS`] ids, the kept paths are let go first.
pub(crate) fn note_added(&self, id: NodeId, path: &[usize]) {
if self.table.ids.contains_key(&id) {
return;
}
let Ok(mut added) = self.added.write() else { return };
if added.len() >= ADDED_PATHS && !added.contains_key(&id) {
added.clear();
}
added.insert(id, path.to_vec());
}
}
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
@@ -297,7 +341,7 @@ impl IdIndex {
note_tree_walk();
let mut table = Table::default();
walk(layers, u32::MAX, &mut table);
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() });
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default(), added: Arc::default() });
if let Ok(mut g) = self.0.write() {
*g = Some(out.clone());
}
+2 -2
View File
@@ -103,7 +103,7 @@ pub use appearance::{
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii};
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
@@ -119,7 +119,7 @@ pub use node::Knockout;
pub use node::Scaling;
pub use node::changed_nodes;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
+3 -1
View File
@@ -25,7 +25,9 @@ mod opacity;
mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use attributes::{
ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS, attribute_copies,
};
#[cfg(test)]
pub(crate) use changed::COUNTERPART_LOOKUPS;
pub use changed::changed_nodes;
+29 -1
View File
@@ -3,7 +3,7 @@ use super::live_shape::LiveShape;
use super::{Deserialize, Node, Serialize};
/// Window → Attributes: an object's settings that don't change how it prints.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectAttributes {
/// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]).
@@ -45,6 +45,34 @@ pub struct ObjectAttributes {
pub tags: Vec<ObjectTag>,
}
impl Clone for ObjectAttributes {
fn clone(&self) -> Self {
ATTRIBUTE_COPIES.set(ATTRIBUTE_COPIES.get().saturating_add(1));
Self {
show_center: self.show_center,
image_map: self.image_map,
url: self.url.clone(),
note: self.note.clone(),
data: self.data.clone(),
events: self.events.clone(),
classes: self.classes.clone(),
foreign: self.foreign.clone(),
tags: self.tags.clone(),
}
}
}
thread_local! {
/// [`attribute_copies`] of this thread.
static ATTRIBUTE_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many times an object's [`ObjectAttributes`] have been copied on this thread. Tags can hold
/// up to [`MAX_TAGS`] values of [`MAX_TAG_TEXT`] bytes each, so each copy can cost megabytes.
pub fn attribute_copies() -> u64 {
ATTRIBUTE_COPIES.get()
}
/// The most tags one object has.
pub const MAX_TAGS: usize = 64;
+90 -19
View File
@@ -46,11 +46,32 @@ pub enum LiveShape {
#[serde(default, skip_serializing_if = "is_false")]
radii_relative: bool,
},
/// A star drawn with the Star tool or `shape.star`: its point count and radii stay editable.
Star {
/// Outer radius: centre to each tip.
r1: f64,
/// Inner radius: centre to each point between two tips.
r2: f64,
/// 2–1000, as [`LiveShape::set_points`] gives it; a file's count is clamped when read.
#[serde(deserialize_with = "de_points")]
points: u32,
/// Maps the star (centred on the origin, first tip straight up) into the document.
xf: Affine,
/// Corner radii in document units, by vertex from the first tip clockwise, tips and inner
/// points alternating (none: sharp).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
radii: Vec<f64>,
/// Corner kinds, in the same order (none: round).
#[serde(default, skip_serializing_if = "all_round")]
kinds: Vec<CornerKind>,
#[serde(default, skip_serializing_if = "is_false")]
radii_relative: bool,
},
Line {
a: Point,
b: Point,
},
/// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut
/// Any other path whose corners Live Corners cut (a pen path, a star saved as a path): it keeps its uncut
/// outline so the corners stay editable. Without a cut corner it is a plain path again.
Path {
/// The path with its corners uncut, in the document.
@@ -74,9 +95,10 @@ fn is_false(b: &bool) -> bool {
impl LiveShape {
pub fn radii_relative(&self) -> bool {
match self {
LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => {
*radii_relative
}
LiveShape::Rectangle { radii_relative, .. }
| LiveShape::Polygon { radii_relative, .. }
| LiveShape::Star { radii_relative, .. }
| LiveShape::Path { radii_relative, .. } => *radii_relative,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false,
}
}
@@ -86,6 +108,7 @@ impl LiveShape {
LiveShape::Rectangle { .. } => "Rectangle",
LiveShape::Ellipse { .. } => "Ellipse",
LiveShape::Polygon { .. } => "Polygon",
LiveShape::Star { .. } => "Star",
LiveShape::Line { .. } => "Line",
LiveShape::Path { .. } => "Path",
}
@@ -100,7 +123,7 @@ impl LiveShape {
shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf)
}
LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf),
LiveShape::Polygon { radii, kinds, radii_relative, .. } => {
LiveShape::Polygon { radii, kinds, radii_relative, .. } | LiveShape::Star { radii, kinds, radii_relative, .. } => {
let outline = self.polygon_outline();
let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative);
cut_corners(&outline, &radii, kinds).0
@@ -112,10 +135,12 @@ impl LiveShape {
}
}
}
/// A polygon's outline with its corners uncut, in the document (empty for other shapes).
/// A polygon's or star's outline with its corners uncut, in the document (empty for other
/// shapes).
pub fn polygon_outline(&self) -> PathData {
match self {
LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
LiveShape::Star { r1, r2, points, xf, .. } => shapes::star(Point::ZERO, *r1, *r2, *points, 0.0).transformed(*xf),
_ => PathData::default(),
}
}
@@ -123,16 +148,38 @@ impl LiveShape {
/// the corners past the old last one are sharp.
pub fn set_sides(&mut self, n: u64) {
let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return };
let old = *sides as usize;
*sides = n.clamp(3, 1000) as u32;
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) {
match v.first().copied() {
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
Some(_) => v.resize(n, T::default()),
None => {}
}
spread(radii, old, *sides as usize);
spread(kinds, old, *sides as usize);
}
/// A star's point count. None for other shapes.
pub fn star_points(&self) -> Option<u32> {
let LiveShape::Star { points, .. } = self else { return None };
Some(*points)
}
/// Give a star `n` points (2–1000). Its corners keep the radius and kind they shared; else the
/// corners past the old last one are sharp.
pub fn set_points(&mut self, n: u64) {
let LiveShape::Star { points, radii, kinds, .. } = self else { return };
let old = 2 * *points as usize;
*points = n.clamp(2, 1000) as u32;
spread(radii, old, 2 * *points as usize);
spread(kinds, old, 2 * *points as usize);
}
/// A star's ratio: its inner radius over its outer radius (0 when the outer radius is 0). None
/// for other shapes.
pub fn star_ratio(&self) -> Option<f64> {
let LiveShape::Star { r1, r2, .. } = self else { return None };
Some(if *r1 > 0.0 { *r2 / *r1 } else { 0.0 })
}
/// Give a star the ratio `ratio` (0 to 1, see [`LiveShape::star_ratio`]), keeping its outer
/// radius. Nothing changes for other shapes or a ratio outside 0 to 1.
pub fn set_star_ratio(&mut self, ratio: f64) {
let LiveShape::Star { r1, r2, .. } = self else { return };
if ratio.is_finite() && (0.0..=1.0).contains(&ratio) {
*r2 = *r1 * ratio;
}
spread(radii, *sides as usize);
spread(kinds, *sides as usize);
}
/// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of
/// `xf` (exact while its sides are equal). None for other shapes.
@@ -151,7 +198,9 @@ impl LiveShape {
/// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for
/// other shapes.
pub fn shape_angle(&self) -> Option<f64> {
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None };
let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. } | LiveShape::Star { .. }) = self else {
return None;
};
// No −0° or 360° from rounding: a shape drawn level reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
@@ -168,7 +217,7 @@ impl LiveShape {
let angle = angle.rem_euclid(360.0);
let (xf, local) = match self {
LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)),
LiveShape::Polygon { xf, .. } => (xf, Point::ZERO),
LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => (xf, Point::ZERO),
LiveShape::Line { .. } | LiveShape::Path { .. } => return,
};
let center = *xf * local;
@@ -274,7 +323,7 @@ impl LiveShape {
*xf = a * *xf;
false
}
LiveShape::Polygon { xf, radii, radii_relative, .. } => {
LiveShape::Polygon { xf, radii, radii_relative, .. } | LiveShape::Star { xf, radii, radii_relative, .. } => {
*xf = a * *xf;
scale_radii(radii, a, *radii_relative)
}
@@ -326,7 +375,7 @@ impl LiveShape {
let relative = self.radii_relative();
let radii: &mut [f64] = match self {
LiveShape::Rectangle { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii,
LiveShape::Polygon { radii, .. } | LiveShape::Star { radii, .. } | LiveShape::Path { radii, .. } => radii,
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false,
};
if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 {
@@ -338,7 +387,7 @@ impl LiveShape {
/// Rotation angle of the live shape in degrees, clockwise on the page (y points down).
pub fn angle_deg(&self) -> f64 {
match self {
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => {
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } | LiveShape::Star { xf, .. } => {
let c = xf.as_coeffs();
c[1].atan2(c[0]).to_degrees()
}
@@ -358,6 +407,28 @@ fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
u32::deserialize(d).map(|n| n.clamp(3, 1000))
}
/// A star's point count read from a file, clamped as the commands clamp it (see [`de_sides`]).
fn de_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
u32::deserialize(d).map(|n| n.clamp(2, 1000))
}
/// Give a corner list for `old` corners `n` entries: one value all `old` corners shared fills it;
/// otherwise entries past its end are the default (sharp, round) and entries past `n` go. A list
/// shorter than `old` holds the default for its missing corners, so it is shared only when that
/// default is; entries of a longer list past `old` name no corner and go first. An empty list
/// stays empty.
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, old: usize, n: usize) {
v.truncate(old);
if !v.is_empty() && v.len() < old {
v.resize(old, T::default());
}
match v.first().copied() {
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
Some(_) => v.resize(n, T::default()),
None => {}
}
}
/// Whether `a` only moves (no rotation, scale, shear or reflection).
pub(super) fn moves_only(a: Affine) -> bool {
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
+10
View File
@@ -227,6 +227,16 @@ impl Node {
}
}
/// The path whose anchors the anchor tools edit, in document space: a path's, or the path of
/// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt).
pub fn anchor_path(&self) -> Option<std::borrow::Cow<'_, PathData>> {
match &self.kind {
NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)),
NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned),
_ => None,
}
}
pub fn path_data_mut(&mut self) -> Option<&mut PathData> {
match &mut self.kind {
NodeKind::Path { path, .. } => Some(path),
+71
View File
@@ -158,6 +158,77 @@ fn a_polygon_from_a_file_has_3_to_1000_sides() {
assert_eq!(huge.polygon_outline().anchor_count(), 1000);
}
/// A live star saves and reads back as it was, and one read from a file has 2 to 1000 points.
#[test]
fn a_star_round_trips_and_its_file_count_is_clamped() {
let star = LiveShape::Star {
r1: 40.0,
r2: 20.0,
points: 7,
xf: Affine::translate((10.0, 20.0)),
radii: vec![2.0; 14],
kinds: vec![],
radii_relative: false,
};
let text = serde_json::to_string(&star).unwrap();
assert_eq!(serde_json::from_str::<LiveShape>(&text).unwrap(), star);
assert_eq!(star.label(), "Star");
let read = |points: u64| {
let json = serde_json::json!({"shape": "star", "r1": 10.0, "r2": 5.0, "points": points, "xf": [1, 0, 0, 1, 0, 0]});
serde_json::from_value::<LiveShape>(json).unwrap().star_points().unwrap()
};
assert_eq!([0, 2, 5, 1000, 4_000_000_000].map(read), [2, 2, 5, 1000, 1000]);
// Points and ratio change; the outer radius stays.
let mut s = star.clone();
s.set_points(9);
s.set_star_ratio(0.25);
assert!(matches!(&s, LiveShape::Star { r1, r2, points: 9, radii, .. } if *r1 == 40.0 && *r2 == 10.0 && *radii == vec![2.0; 18]));
assert_eq!(s.polygon_outline().anchor_count(), 18);
}
/// A corner list shorter than the corners holds sharp corners past its end, so a new point or
/// side count does not give those corners the first corner's radius.
#[test]
fn a_short_corner_list_keeps_its_missing_corners_sharp() {
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
star.set_points(6);
let mut want = vec![0.0; 12];
want[0] = 2.0;
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want), "{star:?}");
let mut polygon = LiveShape::Polygon { radius: 40.0, sides: 5, xf: Affine::IDENTITY, radii: vec![2.0], kinds: vec![], radii_relative: false };
polygon.set_sides(6);
let mut want = vec![0.0; 6];
want[0] = 2.0;
assert!(matches!(&polygon, LiveShape::Polygon { radii, .. } if *radii == want), "{polygon:?}");
}
/// A corner list longer than the corners drops its entries past the old last corner, so the
/// corners a new point count adds are sharp and keep the default kind.
#[test]
fn a_long_corner_list_drops_its_entries_past_the_corners() {
let mut radii = vec![0.0; 12];
radii[0] = 2.0;
radii[10] = 7.0;
radii[11] = 7.0;
let mut kinds = vec![CornerKind::Round; 12];
kinds[0] = CornerKind::Chamfer;
kinds[10] = CornerKind::Chamfer;
kinds[11] = CornerKind::Chamfer;
let mut star = LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii, kinds, radii_relative: false };
star.set_points(6);
let mut want_radii = vec![0.0; 12];
want_radii[0] = 2.0;
let mut want_kinds = vec![CornerKind::Round; 12];
want_kinds[0] = CornerKind::Chamfer;
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == want_radii), "{star:?}");
assert!(matches!(&star, LiveShape::Star { kinds, .. } if *kinds == want_kinds), "{star:?}");
// A complete list that all corners share still fills the new corners.
let mut star =
LiveShape::Star { r1: 40.0, r2: 20.0, points: 5, xf: Affine::IDENTITY, radii: vec![3.0; 10], kinds: vec![], radii_relative: false };
star.set_points(6);
assert!(matches!(&star, LiveShape::Star { radii, .. } if *radii == vec![3.0; 12]), "{star:?}");
}
#[test]
fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
+18 -7
View File
@@ -368,18 +368,29 @@ impl Document {
}
}
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too.
fn overprints_anywhere(n: &Node) -> bool {
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too, and with `images` an
/// image's color.
fn overprints_anywhere(n: &Node, images: bool) -> bool {
n.appearance.items.iter().any(|i| i.overprint())
|| n.extras().colorize_overprint
|| (images && n.extras().colorize_overprint)
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c)))
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c, images)))
}
/// Stop every fill and stroke of `a`'s subtree overprinting (characters' too), copying only the
/// nodes on the way to them.
pub fn clear_overprints(a: &mut Arc<Node>) {
if !overprints_anywhere(a) {
clear(a, true);
}
/// [`clear_overprints`] for fills, strokes and characters only: the colors of images keep their
/// overprint ([`crate::NodeExtras::colorize_overprint`]).
pub fn clear_paint_overprints(a: &mut Arc<Node>) {
clear(a, false);
}
fn clear(a: &mut Arc<Node>, images: bool) {
if !overprints_anywhere(a, images) {
return;
}
let n = Arc::make_mut(a);
@@ -392,11 +403,11 @@ pub fn clear_overprints(a: &mut Arc<Node>) {
}
}
// Also the flag an image keeps after its color is removed.
if n.extras().colorize_overprint {
if images && n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
for c in n.children_mut().into_iter().flatten() {
clear_overprints(c);
clear(c, images);
}
}
+1 -1
View File
@@ -78,7 +78,7 @@ pub struct Selection {
}
/// See [`Selection::symbol_part`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SymbolPart {
/// The symbol instance.
pub instance: NodeId,
+29 -2
View File
@@ -16,6 +16,23 @@ use vectorcraft_color::{Color, Paint, Swatch, tint_percent};
use crate::{AppearanceItem, Document, Node, NodeId, NodeKind};
#[cfg(any(test, feature = "swatch-scans"))]
thread_local! {
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
/// name on this thread.
static SWATCH_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How many swatches and color groups [`Document::swatch`] and [`Document::swatch_name_taken`] have compared by
/// name on this thread, for other crates' tests that count how much work their lookups by name do (the
/// `swatch-scans` feature, dev-dependencies only). A lookup compares the swatches up to the one it finds, or all of
/// them for a name the document does not hold.
#[cfg(any(test, feature = "swatch-scans"))]
#[doc(hidden)]
pub fn swatch_scans() -> usize {
SWATCH_SCANS.with(std::cell::Cell::get)
}
impl Document {
/// Every swatch: the ungrouped ones first, then each colour group's in order.
pub fn swatches_iter(&self) -> impl Iterator<Item = &Swatch> {
@@ -27,7 +44,12 @@ impl Document {
/// Swatch `name`, the built-in Registration swatch ([`vectorcraft_color::swatch::registration`])
/// included.
pub fn swatch(&self, name: &str) -> Option<&Swatch> {
self.swatches_iter().find(|s| s.name == name).or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
let found = self.swatches_iter().find(|s| {
#[cfg(any(test, feature = "swatch-scans"))]
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
s.name == name
});
found.or_else(|| (name == REGISTRATION).then(vectorcraft_color::swatch::registration))
}
pub fn swatch_mut(&mut self, name: &str) -> Option<&mut Swatch> {
self.swatches_iter_mut().find(|s| s.name == name)
@@ -74,7 +96,12 @@ impl Document {
}
/// Is `name` used by a swatch or a colour group (they share one namespace)?
pub fn swatch_name_taken(&self, name: &str) -> bool {
self.swatch(name).is_some() || self.swatch_groups.iter().any(|g| g.name == name)
self.swatch(name).is_some()
|| self.swatch_groups.iter().any(|g| {
#[cfg(any(test, feature = "swatch-scans"))]
SWATCH_SCANS.with(|c| c.set(c.get() + 1));
g.name == name
})
}
/// `base`, or the first of "base 2", "base 3"… no swatch or colour group uses.
pub fn free_swatch_name(&self, base: &str) -> String {
+86
View File
@@ -608,3 +608,89 @@ fn node_lookups_copy_no_index_path() {
agree(&d, &ids[..200], "after remove_many");
agree(&d, &nested, "nested");
}
/// Copies of one document that each add the same object, as the previews of a drag do from the document at the press,
/// find that object where a walk finds it. The first copy walks the tree once for it and the later copies do not walk,
/// and [`Document::node`] finds it without copying an index path.
/// A copy that adds the object elsewhere, adds an object below it, groups it or deletes it, and the document they
/// were copied from, still find what a walk finds. A copy that adds it twice finds one node with its id, and
/// [`Document::nodes_in_order`] finds both.
#[test]
fn copies_that_add_an_object_find_it_without_walking_again() {
let (mut base, ids) = squares(2_000);
let layer = base.layers[0].id;
let added = base.alloc_id();
let new = || Node::path(added, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art());
base.drop_lookup_cache();
base.node(layer);
let walks = tree_walks();
let mut node_copies = 0;
for copy in 0..20 {
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
let copies = path_copies();
assert!(d.node(added).is_some_and(|n| n.id == added), "copy {copy}");
node_copies += path_copies() - copies;
assert_eq!(d.index_path(added), Some(vec![0, ids.len()]), "copy {copy}");
assert_eq!(d.index_paths([added, ids[5]]).get(&added), Some(&vec![0, ids.len()]), "copy {copy}");
assert_eq!(d.ancestry(added), Some(vec![layer, added]), "copy {copy}");
}
assert_eq!(tree_walks() - walks, 1, "walks of the tree for 20 copies");
assert_eq!(node_copies, 0, "index paths copied by node for 20 copies");
// A copy that adds the object twice: lookups give one node with its id, and nodes_in_order,
// which reads only the table's paths, gives both.
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
d.insert(Some(layer), 3, new()).unwrap();
agree_except(&d, &[added, ids[3], ids[0]], Some(added), "added twice");
assert_eq!(d.nodes_in_order([ids[7], added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added, ids[7], added], "added twice");
let gone = d.index_path(added).unwrap();
assert_eq!(d.remove(added).unwrap().id, added);
assert_eq!(d.walk_index_path(added).filter(|p| *p != gone).map(|_| ()), Some(()), "the other one stays");
assert_eq!(d.layers[0].children().unwrap().len(), ids.len() + 1, "removed one node");
// The object lower in the layer, with another object below it, and the next copy back at the top.
let mut d = base.clone();
d.insert(Some(layer), 10, new()).unwrap();
agree(&d, &[added, ids[9], ids[10]], "added at 10");
let below = square(&mut d);
let below = d.insert(Some(layer), 0, below).unwrap();
agree(&d, &[added, below, ids[9]], "an object below it");
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
agree(&d, &[added], "back at the top");
// Grouped with the object below it, then deleted.
let gid = d.alloc_id();
let members = vec![d.remove(ids[ids.len() - 1]).unwrap(), d.remove(added).unwrap()];
d.insert(Some(layer), usize::MAX, Node::group(gid, members)).unwrap();
assert_eq!(d.index_path(added), Some(vec![0, ids.len() - 1, 1]));
agree(&d, &[added, gid, ids[ids.len() - 1]], "grouped");
d.remove(gid).unwrap();
assert!(d.node(added).is_none() && d.index_path(added).is_none(), "deleted with its group");
agree(&d, &[added, gid], "deleted");
// The document the copies came from has no such object, and a copy that adds it again finds it.
assert!(base.node(added).is_none() && base.index_path(added).is_none() && base.index_paths([added]).is_empty());
let mut d = base.clone();
d.insert(Some(layer), usize::MAX, new()).unwrap();
agree(&d, &[added, ids[0]], "added again");
}
/// Repeated ordered lookups of an added object rebuild the table and then use its cached path.
#[test]
fn ordered_lookups_of_an_added_object_stop_walking() {
let (mut d, _) = squares(2_000);
let layer = d.layers[0].id;
d.drop_lookup_cache();
d.node(layer);
let new = square(&mut d);
let added = d.insert(Some(layer), usize::MAX, new).unwrap();
assert!(d.node(added).is_some_and(|n| n.id == added));
let walks = tree_walks();
for lookup in 0..20 {
assert_eq!(d.nodes_in_order([added]).iter().map(|n| n.id).collect::<Vec<_>>(), [added], "lookup {lookup}");
}
assert!(tree_walks() - walks <= 5, "walks of the tree for 20 ordered lookups");
}
+10
View File
@@ -487,6 +487,16 @@ impl TextObject {
true
})
}
/// Replace type on a path's path with `path`, given in document space; the brackets keep their
/// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path
/// that would not be finite.
pub fn set_type_path(&mut self, path: &PathData) -> bool {
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|frame, to_text| {
*frame = path.transformed(to_text);
true
})
}
/// Edit a copy of the area frame with `f` (given the document → text space map) and keep it
/// when `f` succeeds and the result is finite.
fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool {
+5
View File
@@ -24,6 +24,11 @@ craft-svg = { workspace = true, features = ["tree-render"] }
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
svgtypes = "0.16"
serde_json = { workspace = true }
# Render Settings › Rendered: the 3D effects' solids drawn as an image with depth and shadow maps.
craft-raster3d = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-raster3d = { workspace = true, features = ["parallel"] }
[dev-dependencies]
vectorcraft-color = { workspace = true }
+3 -3
View File
@@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
return Some(bake_pieces(d, m));
}
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) {
return Some(m);
}
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
+4 -4
View File
@@ -241,28 +241,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
),
g(
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
),
g(
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
),
g(
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), material: object ({roughness: 1, metallic: 0}; as Revolve's), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, quality, resolution and background, as Revolve's; rendered mode checks the paint of every fill and stroke)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}),
),
g(
+10 -7
View File
@@ -96,16 +96,19 @@ pub use reshape::{
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve,
validate_revolve_in,
};
pub use solids::rendered::{rendered_warning, three_d_bounds_art_in};
pub use solids::{
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic,
MeshGraphics, RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options,
is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol,
rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of,
three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at,
validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings,
SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame,
graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art,
solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
+232 -4
View File
@@ -172,8 +172,9 @@ fn highlight_fills(highlight: vectorcraft_three_d::Highlight) -> Vec<AppearanceI
}
/// The path that screens `highlight` over a face of outline `path` closed by a seam `seam` wide:
/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], else the
/// outline alone). `None` without a highlight or when it holds no light.
/// the highlight's fills ([`highlight_fills`]) on the face and its seam ([`seamed_fill`], or for a
/// curved face [`curved_seamed_fill`]; else the outline alone). Each fill covers the face and its
/// seam once. `None` without a highlight or when it holds no light.
pub(crate) fn highlight_over(
id: vectorcraft_doc::NodeId,
path: &vectorcraft_geom::PathData,
@@ -184,10 +185,126 @@ pub(crate) fn highlight_over(
if items.is_empty() {
return None;
}
let shape = seamed_fill(path, seam).unwrap_or_else(|| path.clone());
let shape = seamed_fill(path, seam).or_else(|| curved_seamed_fill(path, seam)).unwrap_or_else(|| path.clone());
Some(vectorcraft_doc::Node::path(id, shape, vectorcraft_doc::Appearance { items, ..Default::default() }))
}
/// How far, in points, a curved face's flattened outline may stray from its curves when
/// [`curved_seamed_fill`] tests it.
const HIGHLIGHT_FLATNESS: f64 = 0.05;
/// Curved face `path` and its round seam `seam` wide as one path to fill: the [`footprint`] of the
/// curves themselves, as the face's clip is. `None` unless `path` has curves and its outline,
/// flattened to within [`HIGHLIGHT_FLATNESS`], is a polygon [`seamed_fill`] takes: one closed
/// contour of up to [`SEAMED_FILL_EDGES`] edges that does not fold over itself. Flattening stops
/// once the outline passes that many edges.
fn curved_seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{ParamCurve, ParamCurveExtrema, PathEl, PathSeg, Shape};
let bez = path.to_bezpath();
let elements = bez.elements();
if elements.len() > SEAMED_FILL_EDGES + 2 || !elements.iter().any(|el| matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))) {
return None;
}
let segments: Vec<PathSeg> = bez.segments().collect();
for (i, a) in segments.iter().enumerate() {
let b = &segments[(i + 1) % segments.len()];
if matches!((a, b), (PathSeg::Line(_), PathSeg::Line(_))) {
continue;
}
let controls = |s: &PathSeg| match s {
PathSeg::Line(s) => vec![s.p0, s.p1],
PathSeg::Quad(s) => vec![s.p0, s.p1, s.p2],
PathSeg::Cubic(s) => vec![s.p0, s.p1, s.p2, s.p3],
};
let seam = a.end();
let directions: Vec<_> = controls(a)
.into_iter()
.map(|p| p - seam)
.chain(controls(b).into_iter().map(|p| seam - p))
.filter(|v| v.hypot() > 0.0)
.map(|v| v / v.hypot())
.collect();
let separated = directions.iter().any(|a| {
directions.iter().any(|b| {
let axis = *a + *b;
directions.iter().all(|v| axis.dot(*v) > 1e-12)
})
});
if !separated {
return None;
}
}
let mut flat = vectorcraft_geom::BezPath::new();
let mut overflow = false;
let mut last = kurbo::Point::ZERO;
for el in elements {
if overflow {
break;
}
let from = last;
let controls = match el {
PathEl::QuadTo(a, b) => Some([from, *a, *b, *b]),
PathEl::CurveTo(a, b, c) => Some([from, *a, *b, *c]),
_ => None,
};
if let Some(controls) = controls {
let length: f64 = controls.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
if !length.is_finite()
|| length > HIGHLIGHT_FLATNESS * vectorcraft_geom::MAX_FLATTEN_PER_CURVE.powi(2)
|| controls.iter().any(|p| !(p.x.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH && p.y.abs() <= vectorcraft_geom::MAX_FLATTEN_LENGTH))
{
return None;
}
}
last = match el {
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => *p,
PathEl::ClosePath => last,
};
let curve = match el {
PathEl::QuadTo(a, b) => Some(PathSeg::Quad(kurbo::QuadBez::new(from, *a, *b))),
PathEl::CurveTo(a, b, c) => Some(PathSeg::Cubic(kurbo::CubicBez::new(from, *a, *b, *c))),
_ => None,
};
// Each curve piece is monotonic in both coordinates before flattening.
let pieces = curve.map_or_else(
|| vec![(from, *el)],
|curve| {
curve
.extrema_ranges()
.into_iter()
.map(|range| {
let piece = curve.subsegment(range);
(piece.start(), piece.as_path_el())
})
.collect()
},
);
for (from, el) in pieces {
if overflow {
break;
}
let start = [PathEl::MoveTo(from)].into_iter().filter(|_| !matches!(el, PathEl::MoveTo(_)));
let mut skip = usize::from(!matches!(el, PathEl::MoveTo(_)));
vectorcraft_geom::flatten(start.chain([el]), HIGHLIGHT_FLATNESS, |e| {
if skip > 0 {
skip -= 1;
} else if flat.elements().len() > SEAMED_FILL_EDGES + 2 {
overflow = true;
} else {
flat.push(e);
}
});
}
}
if overflow {
return None;
}
// Each flattened edge may be HIGHLIGHT_FLATNESS away from its curve.
seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), seam, 2.0 * HIGHLIGHT_FLATNESS)?;
let fill = footprint(&bez, seam);
(fill.bounding_box().is_finite() && fill.area().abs() >= bez.area().abs()).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
}
/// `face`, the art of a face of outline `path` closed by a seam `seam` wide, with `highlight`
/// screened over it: a group of the face and the highlight's path on the face and its seam
/// ([`highlight_over`]). An opacity mask on the face moves to the group, so it covers the
@@ -255,7 +372,13 @@ const SEAMED_FILL_EDGES: usize = 256;
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
/// than the facet.
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{PathEl, Point, Shape};
seamed_fill_with_clearance(path, seam, 0.0)
}
/// [`seamed_fill`], also `None` when two edges that are not neighbors come within `clearance` of
/// each other.
fn seamed_fill_with_clearance(path: &vectorcraft_geom::PathData, seam: f64, clearance: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{Line, ParamCurveNearest, PathEl, Point, Shape};
if !(seam.is_finite() && seam > 0.0) {
return None;
}
@@ -294,6 +417,19 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio
if touch(a, b, c, d) {
return None;
}
if clearance > 0.0 {
let ab = Line::new(a, b);
let cd = Line::new(c, d);
let distance_sq = ab
.nearest(c, 1e-6)
.distance_sq
.min(ab.nearest(d, 1e-6).distance_sq)
.min(cd.nearest(a, 1e-6).distance_sq)
.min(cd.nearest(b, 1e-6).distance_sq);
if distance_sq <= clearance * clearance {
return None;
}
}
}
}
let fill = footprint(&bez, seam);
@@ -690,6 +826,98 @@ mod tests {
}
}
/// A material's highlight over a curved face reaches its seam too, as the face's clip does,
/// wound one way so a nonzero fill screens it once. A curved face that folds over itself keeps
/// its outline alone.
#[test]
fn a_highlight_over_a_curved_face_covers_its_seam() {
use kurbo::Shape;
let circle = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for path in [circle.clone(), vectorcraft_geom::PathData::from_bezpath(&circle.to_bezpath().reverse_subpaths())] {
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
let Some(shape) = over.path_data() else { panic!("a path") };
let bez = shape.to_bezpath();
assert_ne!(bez.winding(Point::new(5.0, 10.4)), 0, "the seam past the bottom edge");
assert_ne!(bez.winding(Point::new(5.0, 5.0)), 0, "the face");
assert_eq!(bez.winding(Point::new(5.0, 11.0)), 0, "past the seam");
assert!(bez.elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count() >= 2);
}
// A curved face that folds over itself keeps its outline alone, as its own nonzero fill.
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.quad_to((5.0, -1.0), (10.0, 10.0));
folded.line_to((10.0, 0.0));
folded.quad_to((5.0, 1.0), (0.0, 10.0));
folded.close_path();
let folded = vectorcraft_geom::PathData::from_bezpath(&folded);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &folded, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&folded));
}
/// A curved face whose fold is smaller than the flattening tolerance, so that its flattened
/// outline does not cross itself, still keeps its outline alone, wound either way.
#[test]
fn a_highlight_over_a_fold_smaller_than_flatness_keeps_its_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.line_to((10.0, 0.0));
folded.line_to((10.0, 10.0));
folded.line_to((0.0, 10.0));
folded.line_to((0.0, 0.01));
folded.quad_to((5.0, -0.03), (9.0, 0.01));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the fold");
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&path));
}
}
/// A face with a collinear cubic that reverses direction keeps its highlight outline.
#[test]
fn a_highlight_over_a_retraced_cubic_keeps_its_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.curve_to((-8.0, 0.0), (-4.0, 0.0), (12.0, 0.0));
folded.line_to((12.0, 10.0));
folded.line_to((0.0, 10.0));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0).is_some(), "flattening hides the reversal");
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let Some(over) = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)) else { panic!("a highlight") };
assert_eq!(over.path_data(), Some(&path));
}
}
#[test]
fn a_curved_edge_crossing_its_neighbor_keeps_the_highlight_outline() {
let mut folded = vectorcraft_geom::BezPath::new();
folded.move_to((0.0, 0.0));
folded.line_to((1000.0, 1000.0));
folded.quad_to((500.0, 499.999), (0.0, 0.2));
folded.line_to((-1000.0, 1000.0));
folded.line_to((-1000.0, -1000.0));
folded.close_path();
let highlight = vectorcraft_three_d::Highlight { flat: [0.5; 3], ramp: None };
for bez in [folded.clone(), folded.reverse_subpaths()] {
let mut flat = vectorcraft_geom::BezPath::new();
vectorcraft_geom::flatten(bez.iter(), HIGHLIGHT_FLATNESS, |el| flat.push(el));
assert!(seamed_fill_with_clearance(&vectorcraft_geom::PathData::from_bezpath(&flat), 1.0, 2.0 * HIGHLIGHT_FLATNESS).is_some());
let path = vectorcraft_geom::PathData::from_bezpath(&bez);
let over = highlight_over(vectorcraft_doc::NodeId(1), &path, 1.0, Some(highlight)).unwrap();
assert_eq!(over.path_data(), Some(&path));
}
}
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
+224 -16
View File
@@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option<Node> {
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
/// resolved.
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, false)
art_reporting(doc, n, false, Build::Vector, &mut None)
}
/// [`expand_revolve_art_in`] without a document.
@@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
expand_revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
/// command and UI remain unchanged.
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in
/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI
/// remain unchanged.
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art(doc, n, true)
art_reporting(doc, n, true, Build::Draw, &mut None)
}
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
@@ -918,8 +919,9 @@ fn surface_meshes(
graphics: bool,
) -> Result<Vec<crate::SolidMesh>, String> {
let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params));
let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options));
surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics)
.map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, ..m }).collect())
.map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect())
}
/// [`surface_meshes`] in the default material.
@@ -1070,8 +1072,23 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, fx_options(fx))?;
members_meshes(fx, &shapes, b, options, total, limit)
}
/// The meshes of the members `shapes` of a group with Revolve `fx`, each swept about the axis of `b`
/// with `options` and painted with its surface's fill or stroke at its member's opacity, in order.
/// Members with no fill or stroke are left out. Each mesh is counted against `limit`
/// ([`crate::solids::keep_mesh`]) before the next is built.
fn members_meshes(
fx: &Effect,
shapes: &[Profile],
b: Rect,
options: Revolve,
total: &mut usize,
limit: usize,
) -> Result<Vec<crate::SolidMesh>, String> {
// The graphics go on the side of the member with the longest profile, as the canvas draws them.
let longest = if options.map_surface { graphics_member(&shapes, b, options) } else { None };
let longest = if options.map_surface { graphics_member(shapes, b, options) } else { None };
let mut out = vec![];
for (k, s) in shapes.iter().enumerate() {
let Some(item) = surface_item(&s.items) else { continue };
@@ -1083,13 +1100,32 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
Ok(out)
}
fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered,
/// the image of the lit surface where it can be made, in place of the shaded faces that
/// [`revolve_art_in`] keeps for bounds, hit testing and snapping.
pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art_reporting(doc, n, false, Build::Draw, &mut None)
}
/// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with
/// the reason a rendered image can't be made kept in `warning`.
pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
let check_only = build == Build::Check;
if !has_revolve(n) {
return None;
}
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
let n = &*match resolve_for(doc, n, "Revolve", false) {
Ok(n) => n,
Err(error) => {
// Art that has to be resolved draws only the Revolve on the object itself.
if n.appearance.effects.iter().find(|e| e.visible && is_revolve(&e.id)).is_some_and(crate::renders_image) {
warning.get_or_insert(error);
}
return None;
}
};
if is_container(n) {
return group_art(doc, n, expand);
return group_art(doc, n, expand, build, warning);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -1103,7 +1139,14 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let paints = solid_paints(n);
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
let later = n.appearance.effects.get(index + 1..).unwrap_or_default();
let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &path, rule, item, warning);
if check_only {
return None;
}
if let Some(image) = image {
children.push(image);
} else if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of the faces, with no shadow.
children.push(wire_art(n.id, [(&path, rule)], path.bounds()?, fx, fx_options(fx))?);
} else {
@@ -1132,7 +1175,22 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
if check_only && !crate::renders_image(fx) {
continue;
}
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
// Rendered, this fill's or stroke's surface as an image, under the effects after its
// Revolve, with the shadows in the image.
let later = item.effects().get(index + 1..).unwrap_or_default();
let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &p, rule, item, warning);
if check_only {
continue;
}
if let Some(mut image) = image {
Arc::make_mut(&mut image).appearance.effects = later.iter().filter(|e| !is_revolve(&e.id)).cloned().collect();
children.push(image);
continue;
}
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
if crate::solids::renders_wireframe(fx) {
let mut art = wire_art(n.id, [(&p, rule)], p.bounds()?, fx, fx_options(fx))?;
@@ -1164,6 +1222,126 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
Some(art)
}
/// What a rendered image is made for: the object `id` it is art of, the document `doc` whose raster
/// effects resolution it takes, and the art `build` it goes in.
#[derive(Clone, Copy)]
struct ImageFor<'a> {
doc: Option<&'a Document>,
id: NodeId,
build: Build,
}
/// The rendered image of Revolve `fx` for `to`, swept from `path` (filled under `rule`) about its
/// own bounds and painted with `item`; `later` are the effects after `fx`. `None` when `fx` draws no
/// image or `to.build` takes none, and when the image can't be made, with the reason in `warning`:
/// the caller then draws the shaded faces.
fn surface_image(
to: ImageFor,
fx: &Effect,
later: &[Effect],
path: &PathData,
rule: FillRule,
item: &AppearanceItem,
warning: &mut Option<String>,
) -> Option<Arc<Node>> {
let p = merged_params(&fx.id, &fx.params);
let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?;
let paint = item.paint();
let opacity = item.opacity();
let result = if crate::solids::rendered::reshapes_paths_only(later) {
Err(crate::solids::rendered::PATHS_ONLY.into())
} else if !crate::mapped_graphics(&p).is_empty()
|| !crate::solids::rendered::takes([item], false)
|| crate::solids::mesh_color(paint, opacity)[3] != 1.0
{
Err(crate::solids::rendered::OPAQUE_ONLY.into())
} else if let Some(b) = path.bounds() {
let options = rule_options(fx, rule);
surface_meshes(path, rule, b, fx, options, (paint, opacity, 1.0), true).and_then(|meshes| {
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) {
Some(shadow) => {
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let faces = cast_surface(&mut caster, path, b, options, None)?;
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
}
None => lighting,
};
image_for(to, &lighting, &meshes, settings)
})
} else {
Err("Revolve requires a shape with at least two anchors".into())
};
crate::solids::rendered::reported(result, warning)
}
/// [`surface_image`] of the members `shapes` of a group, every member swept about the axis of `b`
/// with `options` into one image, as the shaded faces draw them in one order. The shaded faces are
/// drawn instead when a member's surface is not an opaque solid color in Normal blending, or when a
/// member, or a group it is in, has an opacity below 100%, a blending mode or an opacity mask.
fn members_image(
to: ImageFor,
fx: &Effect,
later: &[Effect],
shapes: &[Profile],
b: Rect,
options: Revolve,
warning: &mut Option<String>,
) -> Option<Arc<Node>> {
let p = merged_params(&fx.id, &fx.params);
let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?;
let profiles = shapes.iter().filter(|s| surface_item(&s.items).is_some());
let surfaces = profiles.clone().filter_map(|s| surface_item(&s.items));
let result = if profiles.clone().next().is_none() {
Err("Revolve requires a group holding a shape with a fill or stroke".into())
} else if crate::solids::rendered::reshapes_paths_only(later) {
Err(crate::solids::rendered::PATHS_ONLY.into())
} else if crate::mapped_graphics(&p).is_empty()
&& crate::solids::rendered::takes(surfaces, crate::solids::profiles_have_masks(profiles))
&& shapes.iter().all(|s| {
let Some(item) = surface_item(&s.items) else { return true };
crate::solids::mesh_color(item.paint(), item.opacity() * s.opacity)[3] == 1.0
})
{
members_meshes(fx, shapes, b, options, &mut 0, crate::solids::MAX_MESH_TRIANGLES).and_then(|meshes| {
let lighting = crate::solids::rendered::lighting(&fx.id, &p);
let lighting = match crate::solids::rendered::plane_settings(&p, &lighting) {
Some(shadow) => {
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let mut faces = vec![];
for s in shapes {
let Some((_, opacity, _)) = surface_item(&s.items).map(paint_of) else { continue };
if crate::solids::shadow::casts(opacity * s.opacity) {
faces.push(cast_surface(&mut caster, &s.path, b, Revolve { fill_rule: s.rule, ..options }, None)?);
}
}
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &faces)
}
None => lighting,
};
image_for(to, &lighting, &meshes, settings)
})
} else {
Err(crate::solids::rendered::OPAQUE_ONLY.into())
};
crate::solids::rendered::reported(result, warning)
}
/// The rendered image of `meshes` lit by `lighting` for `to`: for [`Build::Bounds`] its rectangle
/// without pixels, for [`Build::Check`] only the check of its limits.
fn image_for(
to: ImageFor,
lighting: &crate::solids::rendered::Lighting,
meshes: &[crate::SolidMesh],
settings: crate::solids::wireframe::RenderSettings,
) -> Result<Option<Arc<Node>>, String> {
if to.build == Build::Bounds {
crate::solids::rendered::bounds_art(to.doc, to.id, lighting, meshes, settings)
} else {
crate::solids::rendered::art(to.doc, to.id, lighting, meshes, settings, to.build == Build::Check)
}
}
/// The members' `surfaces`, or runs of their faces, in order, from the [`Scope`] at `level` of each
/// one's `Profile::scopes` inward: consecutive surfaces that share a scope go in one group with its
/// opacity, blending mode and opacity mask, so each applies once, to the faces it holds together.
@@ -1284,13 +1462,43 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
fn group_art(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
let check_only = build == Build::Check;
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
let fx = n.appearance.effects.get(index)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let b = union_bounds(&shapes)?;
let options = shared_options(&shapes, fx_options(fx)).ok()?;
if check_only && !crate::renders_image(fx) {
return None;
}
let prepared = members(n, "Revolve").and_then(|mut shapes| {
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, fx_options(fx))?;
Ok((shapes, b, options))
});
let (shapes, b, options) = match prepared {
Ok(prepared) => prepared,
Err(e) => {
// In rendered mode the reason the members can't be revolved is reported, as the reason
// an image can't be made is; the canvas then draws the source art.
if crate::renders_image(fx) {
warning.get_or_insert(e);
}
return None;
}
};
// Rendered, one image of every member's surface, with the shadows of every light on the
// surfaces and on the shadow plane; the shaded faces when it can't be made.
let later = n.appearance.effects.get(index + 1..).unwrap_or_default();
let image = members_image(ImageFor { doc, id: n.id, build }, fx, later, &shapes, b, options, warning);
if check_only {
return None;
}
if let Some(image) = image {
let mut art = n.clone();
art.kind = NodeKind::Group { children: vec![image], clip: false };
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
return Some(art);
}
if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of every member's faces, with no shadow.
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| (&s.path, s.rule));
+133 -21
View File
@@ -41,7 +41,12 @@ pub use vectorcraft_three_d::SurfaceKind;
pub(crate) mod shadow;
pub(crate) mod wireframe;
pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in};
pub use wireframe::{
RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, RenderSettings, render_settings, renders_image, renders_wireframe,
three_d_wireframe_in,
};
pub mod rendered;
pub(crate) mod material;
pub use material::MATERIAL;
@@ -684,7 +689,12 @@ fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc<Node>)>) -> Vec<Arc<Node>> {
/// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal?
pub(crate) fn has_masks(shapes: &[Profile]) -> bool {
shapes.iter().any(|s| s.scopes.iter().any(composites))
profiles_have_masks(shapes.iter())
}
/// Does any profile sit in a scope with an opacity mask or a blending mode other than Normal?
pub(crate) fn profiles_have_masks<'a>(mut shapes: impl Iterator<Item = &'a Profile>) -> bool {
shapes.any(|s| s.scopes.iter().any(composites))
}
/// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint
@@ -716,7 +726,7 @@ const MAX_MEMBERS: usize = 4096;
/// The most triangles the meshes of one 3D effect hold together (about 290 MB of corners and
/// normals): past it the object is too complex to export.
const MAX_MESH_TRIANGLES: usize = 2_000_000;
pub(crate) const MAX_MESH_TRIANGLES: usize = 2_000_000;
/// The most facets of solid colors under colored lights that one 3D effect draws as faces of their
/// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite
@@ -1003,6 +1013,17 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData,
/// fill rule, its shape's scopes and the index of its shape.
type Part<'a> = (&'a AppearanceItem, f32, PathData, FillRule, &'a [Scope], usize);
fn solid_items(shape: &Profile) -> impl Iterator<Item = &AppearanceItem> {
let top_fill = shape.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
shape.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(|(_, i)| i)
}
/// The fills and strokes 3D effect `id` draws for `shapes`: every one for Rotate, which draws a
/// plane for each ([`meshes_for`]), and [`solid_items`] for the other effects.
fn drawn_items<'a>(id: &str, shapes: &'a [Profile]) -> Box<dyn Iterator<Item = &'a AppearanceItem> + 'a> {
if is_plane(id) { Box::new(shapes.iter().flat_map(|s| s.items.iter())) } else { Box::new(shapes.iter().flat_map(solid_items)) }
}
/// The parts Extrude & Bevel and Inflate build solids from: each shape's top fill and its strokes,
/// a group's members from the back up, each with its shape's opacity, the region it paints and its
/// shape's scopes. The solids share the bounds of all their parts (`fallback` when none has any):
@@ -1012,8 +1033,7 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
.iter()
.enumerate()
.flat_map(|(member, s)| {
let top_fill = s.items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_)));
s.items.iter().enumerate().filter(move |(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))).map(move |(_, i)| {
solid_items(s).map(move |i| {
let (area, rule) = region(&s.path, s.rule, i);
(i, s.opacity, area, rule, s.scopes.as_slice(), member)
})
@@ -2053,12 +2073,57 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
/// surface of the object, and the surfaces.
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
fn art_for(
doc: Option<&Document>,
n: &Node,
effects: &[Effect],
shapes: &[Profile],
build: Build,
warning: &mut Option<String>,
) -> Option<ShadowAndSurfaces> {
let (fx, later) = effects.split_first()?;
if build == Build::Check && !crate::renders_image(fx) {
return Some((vec![], vec![]));
}
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
if wireframe::renders_wireframe(fx) {
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
}
let p = crate::merged_params(&fx.id, &fx.params);
// Rendered, the solids' image, with the shadows of every light on the solids and on the shadow
// plane; the shaded faces when it can't be made, and for vector measurements.
if build != Build::Vector
&& let Some(settings) = wireframe::render_settings(&fx.id, &p)
{
let image = if rendered::reshapes_paths_only(later) {
Err(rendered::PATHS_ONLY.into())
} else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) {
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| {
let lighting = rendered::lighting(&fx.id, &p);
let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? {
Some((caster, shadow, cast)) => {
let faces: Vec<std::ops::Range<usize>> = cast.iter().map(|c| c.2.clone()).collect();
rendered::with_receiver(lighting, &caster, shadow, &faces)
}
None => lighting,
};
if build == Build::Bounds {
rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
} else {
rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check)
}
})
} else {
Err(rendered::OPAQUE_ONLY.into())
};
let image = rendered::reported(image, warning);
if build == Build::Check {
return Some((vec![], vec![]));
}
if let Some(image) = image {
return Some((vec![], vec![image]));
}
}
let cast = casts_shadow(&fx.id, &p);
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
@@ -2091,10 +2156,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<
/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to
/// the part of the shadow they cast too ([`shadow::scoped_art`]).
fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> {
cast_shadow_with(id, p, shapes, shadow::options(p))
}
/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`.
fn cast_shadow_with<'a>(
id: &str,
p: &Value,
shapes: &'a [Profile],
settings: Option<vectorcraft_three_d::Shadow>,
) -> Result<Option<Cast<'a>>, String> {
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
return Ok(None);
}
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) };
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
@@ -2823,21 +2898,48 @@ pub fn solid_art(n: &Node) -> Option<Node> {
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
/// resolved.
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, Build::Vector, &mut None)
}
/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the
/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that
/// [`solid_art_in`] keeps for bounds, hit testing and snapping.
pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, Build::Draw, &mut None)
}
/// What a 3D effect's art is built for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Build {
/// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No
/// rendered image is made.
Vector,
/// Painted measurement art, with rendered images represented by their rectangles and no pixels.
Bounds,
/// Only whether the rendered image can be made, with the reason in the warning when it can't:
/// no art and no pixels.
Check,
/// The art drawn and exported: the rendered image where it can be made.
Draw,
}
pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
if !has_solid(n) {
return None;
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(doc, n);
return group_solid_art(doc, n, build, warning);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let (sources, paints) = solid_paint_sources(n);
let mut children = vec![];
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
if let Some((index, _)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) =
art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = past_effect(&n.appearance.effects, index);
@@ -2851,9 +2953,16 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for (source, item) in sources.into_iter().zip(&paints) {
if let Some((index, fx)) = solid(item.effects()) {
if let Some((index, _)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item)));
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(
doc,
n,
&item.effects()[index..],
&[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }],
build,
warning,
)?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -2882,11 +2991,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
let (index, _) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
@@ -3195,12 +3304,15 @@ pub struct SolidMesh {
/// The surface's Roughness and Metallic ([`MATERIAL`]); [`vectorcraft_three_d::Material::DEFAULT`]
/// for the 3D (Classic) effects.
pub material: vectorcraft_three_d::Material,
/// The projection that takes the mesh's points to where the effect draws them on the page;
/// `None` when it is not known.
pub projection: Option<vectorcraft_three_d::MeshProjection>,
}
impl SolidMesh {
/// A mesh painted `color`, with no graphics, in the default material.
/// A mesh painted `color`, with no graphics, in the default material, with no projection.
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT }
Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None }
}
}
@@ -3305,17 +3417,17 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
let material = material::of(&fx.id, &p);
let mut out = vec![];
// A solid's parts with and without graphics count together against the limit.
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
let mut keep = |out: &mut Vec<SolidMesh>, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| {
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
.into_iter()
.try_for_each(|part| keep_mesh(out, total, SolidMesh { material, ..part }, limit))
.try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit))
};
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (paint, opacity, _) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?;
}
}
return Ok(out);
@@ -3352,7 +3464,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, (&paint, opacity), bounds)?;
keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
+776
View File
@@ -0,0 +1,776 @@
//! Render Settings › Rendered: the solids of a 3D effect drawn as one image, with a depth buffer,
//! the metallic-roughness shading of every light and the shadows each light casts on the solids,
//! instead of the shaded vector faces. The image lies on the page where the vector faces lie: each
//! mesh point goes through the projection the effect draws its faces with
//! ([`vectorcraft_three_d::MeshProjection`]).
use std::io::Cursor;
use std::sync::Arc;
use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps};
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_three_d::{Light, MeshProjection};
use super::SolidMesh;
use super::wireframe::RenderSettings;
/// The message a rendered image that can't be made is reported with; the effect then draws its
/// shaded faces.
pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead";
/// The message for a solid painted with something other than an opaque solid color in Normal
/// blending, or with graphics; the effect then draws its shaded faces.
pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead";
/// The message for a later geometry effect that reshapes paths but leaves images unchanged.
pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead";
/// Do any visible effects reshape paths without also reshaping images in `reshape_leaves`?
pub(crate) fn reshapes_paths_only(effects: &[vectorcraft_doc::Effect]) -> bool {
effects.iter().any(|e| {
e.visible
&& (crate::is_geometry(&e.id) || crate::is_pathfinder(&e.id))
&& e.id != "distort.transform"
&& e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).is_none()
})
}
/// Why a visible 3D effect in rendered mode on `n` draws shaded faces instead of an image.
/// Messages are English, to be translated when displayed. `None` when no rendered effect falls back.
pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option<String> {
let rendered = |fx: &vectorcraft_doc::Effect| fx.visible && crate::renders_image(fx);
if !n.appearance.effects.iter().any(rendered) && !n.appearance.items.iter().any(|i| i.effects().iter().any(rendered)) {
return None;
}
let mut warning = None;
if crate::has_revolve(n) {
let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning);
} else {
let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning);
}
warning
}
/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page
/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds.
/// This art is for measurement only; selection and snapping use the vector art instead.
pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option<Node> {
crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None)
.or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None))
}
/// The image rectangle for painted measurements, with the same eligibility and scene limits as
/// the rendered image, without rasterizing or adding an image to the cache.
pub(crate) fn bounds_art(
doc: Option<&vectorcraft_doc::Document>,
id: NodeId,
lighting: &Lighting,
meshes: &[SolidMesh],
settings: RenderSettings,
) -> Result<Option<Arc<Node>>, String> {
art(doc, id, lighting, meshes, settings, true)?;
let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?;
let object = ImageObject {
key: String::new(),
width: m.cols,
height: m.rows,
xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]),
link: None,
placement: Default::default(),
pixels: None,
};
Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// The rendered image of `result`, or `None` after a successful check. An error keeps its message
/// in `warning` when no earlier reason is there; the caller then draws its shaded faces.
pub(crate) fn reported(result: Result<Option<Arc<Node>>, String>, warning: &mut Option<String>) -> Option<Arc<Node>> {
match result {
Ok(image) => image,
Err(message) => {
warning.get_or_insert(message);
None
}
}
}
/// The lights a rendered image is shaded with, as the effect's shaded faces are.
#[derive(Clone, Debug, PartialEq)]
pub struct Lighting {
/// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]).
pub lights: Vec<Light>,
/// Each light's shadow diffusion in points, in the same order as `lights`.
pub diffusion: Vec<f64>,
/// The ambient light, 0 to 2.
pub ambient: f64,
/// Shading on: off, the solids show their paint unlit, as the shaded faces do.
pub shade: bool,
/// Shadows on: each light that lights the art casts shadows on the solids and on
/// [`Lighting::receiver`]. Off, no light casts one.
pub shadows: bool,
/// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in
/// order round it ([`receiver`]); `None` without one.
pub receiver: Option<[[f64; 3]; 4]>,
}
impl Lighting {
/// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art?
fn casts(&self, l: &Light) -> bool {
self.shade && self.shadows && l.intensity > 0.0
}
}
/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector
/// shadow paints it.
const PLANE_SHADOW: f32 = 0.5;
/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size,
/// so a soft edge is not cut. VectorCraft's own value.
const PLANE_MARGIN: f64 = 0.05;
/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster`
/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]).
pub(crate) fn with_receiver(
mut lighting: Lighting,
caster: &vectorcraft_three_d::ShadowCaster,
shadow: vectorcraft_three_d::Shadow,
faces: &[std::ops::Range<usize>],
) -> Lighting {
let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect();
lighting.diffusion = lighting
.lights
.iter()
.map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0))
.collect();
let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max);
let shadow = vectorcraft_three_d::Shadow { softness, ..shadow };
lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z]));
lighting
}
/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page,
/// made with `samples` × `samples` samples a pixel.
#[derive(Clone, Debug, PartialEq)]
pub struct Rendered {
pub rect: Rect,
pub cols: u32,
pub rows: u32,
pub samples: u32,
pub pixels: Vec<u8>,
}
/// The margin, as a share of the depth range, the solids' nearest and farthest points keep from the
/// ends of the depth buffer.
const DEPTH_MARGIN: f64 = 0.01;
/// The largest share of the eye's distance a point may lie in front of the projection origin: at it
/// the vector faces stop growing ([`vectorcraft_three_d::MeshProjection::project`]).
const NEAREST: f64 = 0.999;
/// The image of `meshes` lit by `lighting`, with `settings`, at the document's raster effects
/// resolution `doc_ppi` when the settings take it, within `limits`. An error ([`TOO_LARGE`]) when a
/// mesh has no projection or a different one, when a point lies at or behind the eye, when the
/// image has more pixels than `limits` allow even at one sample a pixel, or when the rasterizer
/// refuses the scene. `draft` takes one sample a pixel and draft shadow maps, as Low quality does.
pub fn render(
meshes: &[SolidMesh],
lighting: &Lighting,
settings: RenderSettings,
doc_ppi: f64,
draft: bool,
limits: &Limits,
) -> Result<Rendered, String> {
let too_large = || TOO_LARGE.to_string();
let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?;
let scale = f64::from(cols * k) / rect.width();
let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?;
scene.ssaa = k;
#[cfg(test)]
RASTERIZATIONS.with(|n| n.set(n.get() + 1));
if scene.lights.iter().any(|l| l.shadow >= 0) {
try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?;
}
let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?;
try_encode(&mut image).map_err(|_| too_large())?;
let pixels = image
.data
.iter()
.flat_map(|p| {
let p = if settings.white { [p[0] + 1.0 - p[3], p[1] + 1.0 - p[3], p[2] + 1.0 - p[3], 1.0] } else { *p };
let a = p[3].clamp(0.0, 1.0);
let straight = |c: f32| if a > 0.0 { (c / a).clamp(0.0, 1.0) } else { 0.0 };
[straight(p[0]), straight(p[1]), straight(p[2]), a].map(|c| (c * 255.0).round() as u8)
})
.collect();
Ok(Rendered { rect, cols, rows, samples: k, pixels })
}
#[cfg(test)]
thread_local! {
/// How many rendered images enter the rasterizing path on this thread.
static RASTERIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The projection, clip matrix and raster dimensions within the image's sample budget.
struct Measured {
projection: MeshProjection,
rect: Rect,
z: [f64; 2],
clip: [[f32; 4]; 4],
cols: u32,
rows: u32,
samples: u32,
low: bool,
}
/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples,
/// without building a scene or producing pixels.
fn measure(
meshes: &[SolidMesh],
lighting: &Lighting,
settings: RenderSettings,
doc_ppi: f64,
draft: bool,
limits: &Limits,
) -> Result<Measured, String> {
let too_large = || TOO_LARGE.to_string();
let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?;
if meshes.iter().any(|m| m.projection != Some(projection)) {
return Err(too_large());
}
let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?;
let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0);
let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0));
let pixels = cols * rows;
if pixels.is_nan() || pixels > limits.max_pixels as f64 {
return Err(too_large());
}
let (cols, rows) = (cols as u32, rows as u32);
let rect = Rect::new(bounds.x0, bounds.y0, bounds.x0 + f64::from(cols) * cell, bounds.y0 + f64::from(rows) * cell);
let low = draft || settings.quality == 0;
let mut k = if low { 1 } else { settings.samples() };
while k > 1 && pixels * f64::from(k * k) > limits.max_pixels as f64 {
k -= 1;
}
let clip = clip(projection, rect, z).ok_or_else(too_large)?;
Ok(Measured { projection, rect, z, clip, cols, rows, samples: k, low })
}
/// Check scene limits without allocating raster or shadow depth buffers. The counts follow
/// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223,
/// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and
/// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657.
/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible
/// materials, the plane's two triangles hold no texture and the lights are directional, so each
/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer.
fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> {
let m = measure(meshes, lighting, settings, ppi, false, limits)?;
let size = (m.cols * m.samples, m.rows * m.samples);
let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?;
limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?;
if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights {
return Err(TOO_LARGE.into());
}
let transform =
|matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3];
let mut work = 0u64;
for tri in s.indices.as_chunks::<3>().0 {
let mut points = [[0.0; 2]; 3];
for (point, &i) in points.iter_mut().zip(tri) {
let p = s.vertices[i as usize].pos;
let c = [0, 1, 2, 3].map(|r| transform(&s.clip, p, r));
// Refuse transforms whose rounding escapes the measured clip volume.
if !c.iter().all(|v| v.is_finite()) || c[3] <= 0.0 || c[2] < 0.0 || c[2] > c[3] {
return Err(TOO_LARGE.into());
}
let iw = 1.0 / c[3];
*point = [(f64::from(c[0] * iw) + 1.0) * 0.5 * f64::from(s.width), (1.0 - f64::from(c[1] * iw)) * 0.5 * f64::from(s.height)];
}
let area = (0..3).map(|i| points[i][0] * points[(i + 1) % 3][1] - points[(i + 1) % 3][0] * points[i][1]).sum::<f64>();
if !area.is_finite() {
return Err(TOO_LARGE.into());
}
if area != 0.0 {
let pixels = bounding_work(points, [s.width, s.height]);
if pixels > 0 {
work = work.saturating_add(pixels + 1);
}
}
if work > limits.max_work {
return Err(TOO_LARGE.into());
}
}
// Shadow maps are made only for the lights that cast shadows, from the triangles that cast them.
let casters: Vec<&[u32; 3]> = s
.indices
.as_chunks::<3>()
.0
.iter()
.filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows))
.collect();
if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) {
return Ok(());
}
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for v in &s.vertices {
for k in 0..3 {
lo[k] = lo[k].min(f64::from(v.pos[k]));
hi[k] = hi[k].max(f64::from(v.pos[k]));
}
}
let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
let kinds: Vec<u32> = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect();
let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds);
let maps = sizes.iter().flatten().count() as u64;
if maps.saturating_mul(casters.len() as u64) > limits.max_work {
return Err(TOO_LARGE.into());
}
let mut work = 0u64;
for (light, size) in s.lights.iter().zip(sizes) {
let (Some(size), true) = (size, light.shadow >= 0) else { continue };
let dir = light.dir.map(f64::from);
let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0);
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let unit = |v: [f64; 3]| v.map(|x| x / dot(v, v).sqrt());
let forward = unit(dir);
let hint = if dir[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
let down = unit([0, 1, 2].map(|k| hint[k] - forward[k] * dot(hint, forward)));
let right = unit([
down[1] * forward[2] - down[2] * forward[1],
down[2] * forward[0] - down[0] * forward[2],
down[0] * forward[1] - down[1] * forward[0],
]);
let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]);
let focal = (f64::from(size) * 0.5 / radius) as f32;
for tri in &casters {
let points = [0, 1, 2].map(|k| {
let p = s.vertices[tri[k] as usize].pos;
[0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5))
});
let [a, b, c] = points;
let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
if !area.is_finite() {
return Err(TOO_LARGE.into());
}
let texels = if area.abs() < 1e-12 { 0 } else { bounding_work(points, [size; 2]) };
work = work.saturating_add(texels + 1);
if work > limits.max_work {
return Err(TOO_LARGE.into());
}
}
}
Ok(())
}
/// The pixels inside a triangle's bounding box, clamped to the raster.
fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 {
[0, 1]
.map(|k| {
let lo = points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min).floor().clamp(0.0, f64::from(size[k])) as u64;
let hi = points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max).ceil().clamp(0.0, f64::from(size[k])) as u64;
hi.saturating_sub(lo)
})
.into_iter()
.product()
}
/// The corners of the shadow plane of `lighting`, in mesh space; none without one.
fn receiver(lighting: &Lighting) -> &[[f64; 3]] {
lighting.receiver.as_ref().map_or(&[], |q| q.as_slice())
}
/// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and
/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or
/// behind the eye.
fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> {
let mut bounds: Option<Rect> = None;
let mut z = [f64::INFINITY, f64::NEG_INFINITY];
meshes.iter().flat_map(|m| &m.mesh.positions).next()?;
for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) {
if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) {
return None;
}
let at = projection.project(*p);
let r = Rect::from_points(at, at);
bounds = Some(bounds.map_or(r, |b| b.union(r)));
z = [z[0].min(p[2]), z[1].max(p[2])];
}
bounds.filter(|b| b.width().is_finite() && b.height().is_finite()).map(|b| (b, z))
}
/// The row-major clip matrix that takes a point of the solids' world space (mesh space with y down,
/// about the projection origin) to the image `rect` as [`MeshProjection::project`] places it, with
/// depths `z` kept inside the depth buffer and nearer points deeper in it. `None` when no depth
/// mapping keeps them in order.
fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]; 4]> {
let (rw, rh) = (rect.width(), rect.height());
let a = 2.0 * (projection.origin.x - rect.x0) / rw - 1.0;
let b = 1.0 - 2.0 * (projection.origin.y - rect.y0) / rh;
// w = 1 − z / eye without perspective's eye: 1.
let inv_eye = projection.eye.map_or(0.0, |e| 1.0 / e);
let (z0, z1) = if z[1] > z[0] { (z[0], z[1]) } else { (z[0] - 0.5, z[0] + 0.5) };
let w = |z: f64| 1.0 - z * inv_eye;
// ndc depth (dz · z + d0) / w: the farthest at DEPTH_MARGIN, the nearest at 1 − DEPTH_MARGIN.
// With w positive over [z0, z1] the ndc depth is a linear-fractional function of z, so it rises
// monotonically between those two ends even when dz itself is negative (a near eye).
let (w0, w1) = (w(z0), w(z1));
if !(w0 > 0.0 && w1 > 0.0) {
return None;
}
let (lo, hi) = (DEPTH_MARGIN * w0, (1.0 - DEPTH_MARGIN) * w1);
let dz = (hi - lo) / (z1 - z0);
let d0 = lo - dz * z0;
if !(dz.is_finite() && d0.is_finite() && hi / w1 > lo / w0) {
return None;
}
let m = [[2.0 / rw, 0.0, -a * inv_eye, a], [0.0, -2.0 / rh, -b * inv_eye, b], [0.0, 0.0, dz, d0], [0.0, 0.0, -inv_eye, 1.0]];
let m = m.map(|row| row.map(|v| v as f32));
m.iter().flatten().all(|v| v.is_finite()).then_some(m)
}
/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world
/// space (mesh space with y down, as the page is), opaque ones first, then
/// those of see-through solids from back to front; one material for each mesh; one parallel light,
/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including
/// the samples per image pixel.
fn scene(
meshes: &[SolidMesh],
lighting: &Lighting,
projection: MeshProjection,
z: [f64; 2],
clip: [[f32; 4]; 4],
size: (u32, u32),
scale: f64,
) -> Option<Scene> {
let eye = projection.eye.unwrap_or(z[1] + 1.0);
let mut vertices = vec![];
let mut opaque: Vec<[u32; 3]> = vec![];
let mut clear: Vec<([u32; 3], f64)> = vec![];
let mut materials = vec![];
for (index, m) in meshes.iter().enumerate() {
let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 });
materials.push(craft_raster3d::Material {
base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0],
metallic: m.material.metallic() as f32,
roughness: m.material.roughness() as f32,
opacity: alpha,
double_sided: true,
unlit: !lighting.shade,
casts_shadows: true,
..Default::default()
});
let base = vertices.len() as u32;
let mesh = &m.mesh;
for (i, p) in mesh.positions.iter().enumerate() {
let n = mesh.normals.get(i).copied().unwrap_or([0.0, 0.0, 1.0]);
vertices.push(Vertex {
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
normal: [n[0] as f32, -n[1] as f32, n[2] as f32],
uv: mesh.uvs.get(i).map_or([0.0; 2], |uv| [uv[0] as f32, uv[1] as f32]),
tangent: [1.0, 0.0, 0.0, 1.0],
material: index as u32,
});
}
for t in &mesh.triangles {
if t.iter().any(|&i| i as usize >= mesh.positions.len()) {
return None;
}
let tri = t.map(|i| base + i);
if alpha >= 1.0 {
opaque.push(tri);
} else {
let depth = t.iter().map(|&i| mesh.positions[i as usize][2]).sum::<f64>() / 3.0;
clear.push((tri, depth));
}
}
}
clear.sort_by(|a, b| a.1.total_cmp(&b.1));
// The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's
// opacity, behind every surface, so first in the see-through range.
let mut plane = vec![];
if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) {
let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3]));
let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len.is_finite() && len > 0.0 {
let material = materials.len() as u32;
materials.push(craft_raster3d::Material {
base: [0.0, 0.0, 0.0, 1.0],
opacity: PLANE_SHADOW,
double_sided: true,
shadows_only: true,
receives_shadows: true,
casts_shadows: false,
..Default::default()
});
let base = vertices.len() as u32;
for p in q {
vertices.push(Vertex {
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32],
uv: [0.0; 2],
tangent: [1.0, 0.0, 0.0, 1.0],
material,
});
}
plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]];
}
}
// Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles
// first so the strict depth test keeps that paint when surfaces share a depth.
let opaque_count = (opaque.len() * 3) as u32;
let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect();
let lights = lighting
.lights
.iter()
.enumerate()
.filter(|_| lighting.shade)
.map(|(i, l)| {
// The direction the light travels: away from it.
let [x, y, z] = l.direction().map(|v| -v);
let len = (x * x + y * y + z * z).sqrt();
craft_raster3d::Light {
kind: 0,
pos: [0.0; 3],
dir: [(x / len) as f32, (y / len) as f32, (z / len) as f32],
color: l.color.map(|c| srgb_to_linear((c * l.intensity).clamp(0.0, 1.0) as f32)),
cos_inner: 1.0,
cos_outer: 1.0,
falloff: 0,
radius: 0.0,
falloff_distance: 0.0,
// With Shadows off no light casts one, on the solids or on a plane.
shadow: if lighting.casts(l) { 0 } else { -1 },
shadow_darkness: 1.0,
shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32,
}
})
.collect();
// Ambient light up to 100% goes through the sRGB curve; above it, the linear value scales with
// the intensity, as the shaded faces' ambient term does.
let ambient = lighting.ambient.clamp(0.0, 2.0) as f32;
let ambient = srgb_to_linear(ambient.min(1.0)) * ambient.max(1.0);
Some(Scene {
width: size.0,
height: size.1,
ssaa: 1,
clip,
// Camera depth: the distance in front of the eye, on the z axis.
view: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, eye as f32], [0.0, 0.0, 0.0, 1.0]],
eye: [0.0, 0.0, eye as f32],
cam_fwd: [0.0, 0.0, -1.0],
ortho: projection.eye.is_none(),
vertices,
indices,
opaque_count,
// Read only by the renderers with auxiliary outputs, which this one does not use.
part_ids: vec![],
materials,
textures: vec![],
texels: vec![],
lights,
shadows: vec![],
shadow_texels: vec![],
env: None,
ambient: [ambient; 3],
linear_io: false,
})
}
/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be
/// encoded.
pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?)))))
}
/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded.
fn image_object(image: &Rendered) -> Option<ImageObject> {
let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?;
let mut png = vec![];
raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let blob = ImageBlob::png(png);
let cell = image.rect.width() / f64::from(image.cols);
Some(ImageObject {
key: blob.content_key(),
width: image.cols,
height: image.rows,
xf: Affine::new([cell, 0.0, 0.0, image.rect.height() / f64::from(image.rows), image.rect.x0, image.rect.y0]),
link: None,
placement: Default::default(),
pixels: Some(Arc::new(blob)),
})
}
/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with
/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the
/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits
/// without producing pixels, returning `Ok(None)` when it fits.
pub(crate) fn art(
doc: Option<&vectorcraft_doc::Document>,
id: NodeId,
lighting: &Lighting,
meshes: &[SolidMesh],
settings: RenderSettings,
check_only: bool,
) -> Result<Option<Arc<Node>>, String> {
// Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and
// apply a solid's opacity once to the whole surface.
if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) {
return Err(OPAQUE_ONLY.into());
}
let ppi = doc.map_or(72.0, |d| d.raster_ppi());
if check_only {
check(meshes, lighting, settings, ppi, &Limits::default())?;
return Ok(None);
}
let key = image_key(meshes, lighting, settings, ppi);
let made = match cached(key) {
Some(made) => made,
None => {
let made = render(meshes, lighting, settings, ppi, false, &Limits::default())
.and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string()));
keep(key, &made);
made
}
};
made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's
/// own values.
const KEPT_IMAGES: usize = 32;
const KEPT_BYTES: usize = 64 << 20;
/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]).
type Kept = Vec<(u128, Result<ImageObject, String>)>;
#[cfg(not(test))]
static KEPT: std::sync::Mutex<Kept> = std::sync::Mutex::new(Vec::new());
#[cfg(test)]
thread_local! {
/// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on
/// what other tests drew.
static KEPT: std::cell::RefCell<Kept> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Run `f` on the kept images; `None` when they can't be reached.
fn with_kept<T>(f: impl FnOnce(&mut Kept) -> T) -> Option<T> {
#[cfg(not(test))]
{
KEPT.lock().ok().map(|mut kept| f(&mut kept))
}
#[cfg(test)]
{
KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept)))
}
}
/// The image kept under `key`, moved to the newest place.
fn cached(key: u128) -> Option<Result<ImageObject, String>> {
with_kept(|kept| {
let at = kept.iter().position(|(k, _)| *k == key)?;
let entry = kept.remove(at);
let made = entry.1.clone();
kept.push(entry);
Some(made)
})
.flatten()
}
/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`].
fn keep(key: u128, made: &Result<ImageObject, String>) {
let bytes = |m: &Result<ImageObject, String>| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len());
if bytes(made) > KEPT_BYTES {
return;
}
with_kept(|kept| {
kept.retain(|(k, _)| *k != key);
kept.push((key, made.clone()));
while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::<usize>() > KEPT_BYTES {
drop(kept.remove(0));
}
});
}
/// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals,
/// texture coordinates, triangles, color, material and projection, the lights, ambient light,
/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or
/// reshaping the object, or changing any setting, changes it; panning and redrawing do not.
fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 {
use std::hash::{Hash, Hasher};
let half = |seed: u8| {
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let mut f = |v: f64| v.to_bits().hash(&mut h);
for m in meshes {
let mesh = &m.mesh;
mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v));
mesh.uvs.iter().flatten().for_each(|v| f(*v));
m.color.iter().for_each(|c| f(f64::from(*c)));
f(m.material.roughness());
f(m.material.metallic());
if let Some(p) = m.projection {
[p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f);
}
f(mesh.positions.len() as f64);
f(mesh.triangles.len() as f64);
}
for l in &lighting.lights {
[l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f);
}
lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v));
lighting.diffusion.iter().for_each(|v| f(*v));
f(lighting.diffusion.len() as f64);
[lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64]
.into_iter()
.for_each(&mut f);
[settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f);
for m in meshes {
m.mesh.triangles.hash(&mut h);
}
h.finish()
};
(u128::from(half(1)) << 64) | u128::from(half(2))
}
/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or
/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them
/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped
/// graphics, masks and blending.
pub(crate) fn takes<'a>(items: impl IntoIterator<Item = &'a vectorcraft_doc::AppearanceItem>, masked: bool) -> bool {
use vectorcraft_doc::AppearanceItem;
use vectorcraft_doc::color::Paint;
!masked
&& items.into_iter().all(|i| match i {
AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(),
AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(),
})
}
/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`])
/// for Revolve, the other effects' ([`super::view_options`]) otherwise.
pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting {
let (lights, ambient, shade) = if id == crate::REVOLVE {
let o = crate::revolve_options(p);
(o.active_lights(), o.ambient, o.shade)
} else {
let v = super::view_options(p);
(v.active_lights(), v.ambient, v.shade)
};
let lit = lights.iter().any(|l| l.intensity > 0.0);
let shadows = super::shadow::rendered_options(p, lit).is_some();
Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None }
}
/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting`
/// draws its shadow plane with; `None` with Shadows off or no light lighting the art.
pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option<vectorcraft_three_d::Shadow> {
super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0))
}
#[cfg(test)]
#[path = "rendered/tests.rs"]
mod tests;
File diff suppressed because it is too large Load Diff
+14 -2
View File
@@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
let lit = flag(p, "shade", true) && intensity > 0.0;
(lit && flag(p, "shadow", false)).then(|| Shadow {
(lit && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on
/// when any light lights the art (`lit`), not only the first.
pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
(lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The plane settings of `p`, with the softness of light `first` (the single light's without one).
fn settings(p: &Value, first: Option<vectorcraft_three_d::Light>) -> Shadow {
Shadow {
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
distance: num(p, "shadowDistance", 0.0) / 100.0,
bounds: num(p, "shadowBounds", 100.0) / 100.0,
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
})
}
}
/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind.
+3 -1
View File
@@ -398,5 +398,7 @@ fn meshes_carry_the_material() {
let mut n = square_node();
let Some(fx) = crate::new_effect(EXTRUDE, &json!({})) else { panic!("extrude") };
n.appearance.effects.push(fx);
assert!(three_d_meshes(&n).unwrap_or_default().iter().all(|m| m.material.is_default()));
let meshes = three_d_meshes(&n).unwrap_or_else(|e| panic!("extrude: {e}"));
assert!(!meshes.is_empty(), "extrude");
assert!(meshes.iter().all(|m| m.material.is_default()));
}
+1 -1
View File
@@ -356,7 +356,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
let (path, rule) = profile(&n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
};
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap();
let p = crate::merged_params(&fx.id, &fx.params);
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
+81 -12
View File
@@ -21,12 +21,84 @@ use crate::{GeomContext, is_geometry};
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
/// [`RENDER_MODES`].
/// [`RENDER_MODES`], with the rendered image's `quality` ([`RENDER_QUALITIES`]), `resolution` and
/// `background` ([`RENDER_BACKGROUNDS`]).
pub const RENDER: &str = "render";
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
/// face ([`renders_wireframe`]).
pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"];
/// face ([`renders_wireframe`]), and `rendered` an image of the lit solid with the shadows of its
/// lights ([`render_settings`]).
pub const RENDER_MODES: [&str; 3] = ["shaded", "wireframe", "rendered"];
/// The qualities of the rendered image, from fastest to finest: 1, 2 × 2 and 3 × 3 samples a pixel
/// ([`RenderSettings::samples`]). VectorCraft's own values.
pub const RENDER_QUALITIES: [&str; 3] = ["low", "medium", "high"];
/// What the rendered image shows where no surface is: nothing, or white.
pub const RENDER_BACKGROUNDS: [&str; 2] = ["transparent", "white"];
/// The index in [`RENDER_QUALITIES`] of the quality a `render` without one takes (VectorCraft's own
/// default).
const DEFAULT_QUALITY: usize = 1;
/// The settings of a 3D effect's rendered image ([`render_settings`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RenderSettings {
/// The quality, as an index into [`RENDER_QUALITIES`] (0 low, 1 medium, 2 high).
pub quality: usize,
/// Pixels per inch, 1 to 2400; `None` takes Document Raster Effects Settings › Resolution.
pub resolution: Option<f64>,
/// A white background, which makes the image opaque; otherwise it is transparent where no
/// surface or shadow is.
pub white: bool,
}
impl RenderSettings {
/// The samples a pixel takes along each side at this quality: 1, 2 or 3.
pub fn samples(&self) -> u32 {
self.quality.min(2) as u32 + 1
}
}
/// The settings of the image 3D effect `id` with parameters `p` draws, when its `render` passes
/// [`validate_render`] and sets `mode` to `rendered`; `None` otherwise, when the effect draws its
/// shaded faces or its wireframe (a loaded file whose `render` breaks the rules draws shaded).
pub fn render_settings(id: &str, p: &Value) -> Option<RenderSettings> {
let render = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id))?;
if check_render(render).is_err() || render.get("mode").and_then(Value::as_str) != Some("rendered") {
return None;
}
let quality = render.get("quality").and_then(Value::as_str).and_then(|q| RENDER_QUALITIES.iter().position(|k| *k == q));
Some(RenderSettings {
quality: quality.unwrap_or(DEFAULT_QUALITY),
resolution: render.get("resolution").and_then(Value::as_f64),
white: render.get("background").and_then(Value::as_str) == Some("white"),
})
}
/// Does effect `fx` draw as a rendered image ([`render_settings`])?
pub fn renders_image(fx: &Effect) -> bool {
render_settings(&fx.id, &fx.params).is_some()
}
/// The message a `render` that breaks the rules of [`validate_render`] is refused with.
const RENDER_RULES: &str = "`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), \
resolution (null or a number from 1 to 2400) and background (transparent or white)";
/// Check one `render` value against [`RENDER_RULES`].
fn check_render(render: &Value) -> Result<(), String> {
let one_of = |v: &Value, list: &[&str]| v.as_str().is_some_and(|s| list.contains(&s));
let valid = render.as_object().is_some_and(|fields| {
fields.iter().all(|(key, value)| match key.as_str() {
"mode" => one_of(value, &RENDER_MODES),
"quality" => one_of(value, &RENDER_QUALITIES),
"background" => one_of(value, &RENDER_BACKGROUNDS),
"resolution" => value.is_null() || value.as_f64().is_some_and(|r| (1.0..=2400.0).contains(&r)),
_ => false,
})
});
if valid { Ok(()) } else { Err(RENDER_RULES.into()) }
}
/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve,
/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface.
@@ -50,17 +122,14 @@ pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
}
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a
/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take.
/// effects in [`TAKES_RENDER`], is an object that holds only `mode` (one of [`RENDER_MODES`]),
/// `quality` (one of [`RENDER_QUALITIES`]), `resolution` (`null`, or a number from 1 to 2400 pixels
/// per inch) and `background` (one of [`RENDER_BACKGROUNDS`]). A key left out takes its default:
/// `shaded`, `medium`, the document's raster effects resolution and `transparent`. The 3D (Classic)
/// effects refuse it as a parameter they do not take.
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
let valid = render
.as_object()
.is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m))));
if !valid {
return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into());
}
Ok(())
check_render(render)
}
/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group
+26 -5
View File
@@ -418,12 +418,23 @@ fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT)));
}
/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and
/// only on the panel's four effects.
/// `render` is checked before an edit: an object holding only `mode` (shaded, wireframe or
/// rendered), `quality` (low, medium or high), `resolution` (null or 1 to 2400) and `background`
/// (transparent or white), and only on the panel's four effects.
#[test]
fn render_settings_are_validated() {
for id in WIRE {
for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] {
for good in [
json!({}),
json!({"render": {}}),
json!({"render": {"mode": "shaded"}}),
json!({"render": {"mode": "wireframe"}}),
json!({"render": {"mode": "rendered"}}),
json!({"render": {"mode": "rendered", "quality": "high", "resolution": 300, "background": "white"}}),
json!({"render": {"mode": "rendered", "quality": "low", "resolution": null, "background": "transparent"}}),
json!({"render": {"resolution": 1}}),
json!({"render": {"resolution": 2400}}),
] {
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
}
for bad in [
@@ -431,10 +442,20 @@ fn render_settings_are_validated() {
json!({"render": null}),
json!({"render": {"mode": "raytrace"}}),
json!({"render": {"mode": true}}),
json!({"render": {"mode": "wireframe", "quality": "high"}}),
json!({"render": {"mode": "rendered", "quality": "ultra"}}),
json!({"render": {"mode": "rendered", "resolution": 0.5}}),
json!({"render": {"mode": "rendered", "resolution": 2401}}),
json!({"render": {"mode": "rendered", "resolution": "300"}}),
json!({"render": {"mode": "rendered", "background": "black"}}),
json!({"render": {"mode": "rendered", "samples": 4}}),
] {
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}");
assert_eq!(
e,
"`render` must be an object holding only mode (shaded, wireframe or rendered), quality (low, medium or high), resolution (null \
or a number from 1 to 2400) and background (transparent or white)",
"{id} {bad}"
);
}
// The command check on the object refuses it too.
let n = solid_square(id, json!({}));
+7
View File
@@ -17,6 +17,11 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
# feature still recognizes the files and refuses them with a message. The apps list it beside
# `bundled-fonts`.
heif = ["dep:heic-rs", "dep:rayon"]
# Binary CGM files open and place. Off until the craft-metafile CGM reader (craft-libs#5410) merges
# and the workspace pins it; the build fails with this feature on before then. Without it, `.cgm`
# is not listed as readable or placeable anywhere. Turning it on also needs `cgm` in
# `UNASSOCIATED_EXTS` (`src/cmd/fileio/formats.rs`).
cgm = ["vectorcraft-metafile/cgm"]
[dependencies]
craft-codepage = { workspace = true }
@@ -114,6 +119,8 @@ apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
[dev-dependencies]
# DWG files for the `.dwg` open and place tests, written from DXF by craft-dwg.
craft-dwg = { workspace = true }
# JPEG XL files for the `.jxl` open and place tests.
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
+2
View File
@@ -18,6 +18,7 @@ pub mod colormgmt;
pub mod colortheme;
pub mod compositefonts;
mod compoundshape;
pub mod conceptvector;
pub(crate) mod create;
mod css;
mod cut;
@@ -365,6 +366,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(panelcmds::specs());
v.extend(artboardalign::specs());
v.extend(buildcmds::specs());
v.extend(conceptvector::specs());
v.extend(shaper::specs());
v.extend(brushsym::specs());
v.extend(patterncmds::specs());
+4
View File
@@ -16,6 +16,10 @@ mod shapes;
mod typetools;
mod units;
pub(crate) use color::screen_marks::{
LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer,
managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks,
};
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
+224 -55
View File
@@ -8,10 +8,12 @@
//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their
//! visual bounds share, Randomize Opacity gives each selected object a random
//! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object.
//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object,
//! and Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]).
//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view
//! command) are the UI's.
mod artboard_guides;
pub mod marks;
#[cfg(test)]
mod tests;
@@ -31,8 +33,8 @@ use super::super::edit::selected_roots;
use super::super::graph::{capture_series_object_opacity, series_groups_among};
use super::super::menucmds::whole_or;
use super::super::object::{
aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, scaling, transform_node,
transform_patterns,
aligned_symbol_transforms, aligned_symbols, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform,
object_bounds_transform_keeping, refit_drawn, scaling, snaps_after_edit, transform_node, transform_patterns,
};
use super::super::objects_on_path;
use super::super::typecmd::refresh_bounds_of;
@@ -75,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
exactly_two,
swap
),
@@ -84,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace with Top Object",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
has_multi,
replace
),
@@ -93,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Size of Each",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
has_selection,
size
),
@@ -102,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Match Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}",
has_multi,
match_objects
),
@@ -138,12 +140,13 @@ pub fn specs() -> Vec<CommandSpec> {
"Sort Objects",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
has_multi,
sort
),
]
.into_iter()
.chain(artboard_guides::specs())
.chain(marks::specs())
.collect()
}
@@ -173,10 +176,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose()
}
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`
/// and, when given, a width and height.
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes });
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`,
/// Scale Corners `corners` and, when given, a width and height.
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value {
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners });
if let Some((w, h)) = size {
q["width"] = json!(w);
q["height"] = json!(h);
@@ -185,14 +188,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
}
/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects
/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says.
/// When every transform is (within rounding) the identity, nothing changes.
fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern
/// tiles as the command's params `p` or Transform Pattern Tiles say. When every transform is
/// (within rounding) the identity, nothing changes.
fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
if xfs.iter().all(|(_, xf)| still(xf)) {
return Ok(());
}
let p = json!({ "strokes": strokes });
let p = scaling_params(p, strokes, corners);
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &p);
sc.patterns = transform_patterns(s, &p, &ids)?;
@@ -206,6 +210,17 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
})
}
/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, Scale
/// Corners `corners`, and the `patterns` value of the command's params `p`. That one is absent on a
/// first run, which takes the preference, and present when its journal entry is replayed.
fn scaling_params(p: &Value, strokes: bool, corners: bool) -> Value {
let mut q = json!({ "strokes": strokes, "corners": corners });
if let Some(v) = p.get("patterns").filter(|v| v.is_boolean()) {
q["patterns"] = v.clone();
}
q
}
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
@@ -214,6 +229,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
Ok(on)
}
/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value
/// joins the command's journal entry, so replaying it scales corners the same way.
fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?;
s.note_journal("corners", json!(on));
Ok(on)
}
/// The box of object `id` as `object.setBounds` measures it.
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
@@ -271,7 +294,7 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
.enumerate()
.filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center()))))
.collect();
transform_each(s, "Arrange in Grid", false, &xfs)?;
transform_each(s, "Arrange in Grid", p, false, s.prefs.scale_corners, &xfs)?;
Ok(json!({ "count": n }))
}
@@ -308,7 +331,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
if !moves {
return Ok(json!({ "count": items.len() }));
}
let p = json!({ "strokes": false });
let p = scaling_params(p, false, s.prefs.scale_corners);
let ids: Vec<NodeId> = items.iter().map(|(id, _, _)| *id).collect();
let mut sc = scaling(s, &p);
sc.patterns = transform_patterns(s, &p, &ids)?;
@@ -362,12 +385,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.swap";
let size = switch_or(p, "size", false, C)?;
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let roots = selected_roots(s)?;
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes);
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners);
let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)];
transform_each(s, "Swap Objects", strokes, &xfs)?;
transform_each(s, "Swap Objects", p, strokes, corners, &xfs)?;
Ok(json!({}))
}
@@ -375,6 +399,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.arrange.replace";
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let keep = switch_or(p, "keep", false, C)?;
let roots = selected_roots(s)?;
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
@@ -394,9 +419,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => None,
};
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?));
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?));
}
let p = json!({ "strokes": strokes });
let p = scaling_params(p, strokes, corners);
let mut sc = scaling(s, &p);
sc.patterns = transform_patterns(s, &p, &[top])?;
let ids = s.edit("Replace with Top Object", |d, sel| {
@@ -426,7 +451,8 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
let proportional = switch_or(p, "proportional", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
let corners = scale_corners(s, p, C)?;
let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) });
if let Some(w) = width {
q["width"] = json!(w);
}
@@ -439,7 +465,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
xfs.push((id, object_bounds_transform(s, &q, id)?));
}
}
transform_each(s, "Set Size of Each", strokes, &xfs)?;
transform_each(s, "Set Size of Each", p, strokes, corners, &xfs)?;
Ok(json!({ "count": xfs.len() }))
}
@@ -471,6 +497,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
let stacking = switch_or(p, "stacking", false, C)?;
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
if size == "none" && !rotate && !stacking {
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
@@ -502,6 +529,11 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
};
let angle = s.doc()?.doc.bbox_angle(&[source]);
let mut xfs = Vec::with_capacity(targets.len());
// Where each turned target's reference point is before the match; it stays there.
let mut pinned: HashMap<NodeId, Point> = HashMap::new();
// The turned targets whose reference point is checked after pixel snapping.
let mut checked: HashMap<NodeId, Point> = HashMap::new();
let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() };
for &id in &targets {
let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 };
let Some(b) = s.transform_box(&[id]) else {
@@ -518,36 +550,29 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
let mut q = q.clone();
q["reference"] = json!(reference);
q["strokes"] = json!(strokes);
xf = object_bounds_transform(s, &q, id)?;
q["corners"] = json!(corners);
// Any scale the source's size asks for, however small.
xf = object_bounds_transform_keeping(s, &q, id, 0.0)?;
}
// Rotation and the fit below keep the reference point in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
let turned = Affine::rotate_about(-turn.to_radians(), at);
if turn.abs() > 1e-9 {
// Rotation uses the reference point that sizing keeps in place.
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
xf = turned * xf;
let preview = s.bounds_measure().preview;
let d = &s.doc()?.doc;
if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) {
pinned.insert(id, at);
}
// Pixel snapping after the turn can move a pixel-aligned target: its point is checked
// too, but not put back, since that would move its aligned art off the grid.
if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) {
checked.insert(id, at);
}
}
if wanted.is_some() {
let sc = scaling(s, &json!({ "strokes": strokes }));
let d = &s.doc()?.doc;
let symbols = d.symbol_boxes();
let measure = |xf| {
d.node(id).and_then(|n| {
let mut n = n.clone();
transform_node(&mut n, xf, sc, true);
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
})
};
let misses = |measured: Option<Rect>| {
measured.is_none_or(|r| match size {
"width" => (r.width() - w).abs() > 1e-6,
"height" => (r.height() - h).abs() > 1e-6,
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
})
};
// The sized and turned object, measured in its final frame, must have the size asked for.
if misses(measure(xf)) {
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
}
let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners };
xf = fit_turned(s, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?;
}
xfs.push((id, xf));
}
@@ -564,6 +589,32 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "a clipping path can't change its place in the stacking order"));
}
let parent = d.parent_of(source);
// Each target leaves its own container, so a target's locked container refuses too.
let locked = |p: Option<NodeId>| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p));
if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) {
return Err(bad(C, "the layer or group is locked"));
}
// A blend's input objects, and art inside them, stay in the blend: the whole blend can still be
// restacked, and art can still move within the blend's input it is in.
let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. }));
let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default();
let leaves_blend = |t: &NodeId| {
let chain = d.ancestry(*t).unwrap_or_default();
chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w))
};
if targets.iter().any(leaves_blend) {
return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend"));
}
// Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place.
let in_live_paint =
|id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint));
if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) {
return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel"));
}
// The source's container takes each target only as the Layers panel would (not a blend's inputs).
if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) {
return Err(bad(C, format!("{} can't go beside the source object", n.display_name())));
}
if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
@@ -574,15 +625,30 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
if xfs.is_empty() && !restack {
return Ok(count);
}
let q = json!({ "strokes": strokes, "patterns": patterns });
let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns });
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
let mut sc = scaling(s, &q);
sc.patterns = transform_patterns(s, &q, &ids)?;
let measure = s.bounds_measure();
let before = s.doc()?.doc.clone();
s.edit("Match Objects", |d, _| {
for (id, xf) in &xfs {
if let Some(n) = d.node_mut(*id) {
transform_node(n, *xf, sc, true);
}
// A live effect that moves the art in page space (a Transform effect's offset) does
// not turn with it: the measured reference point is put back where it was.
if let Some(at) = pinned.get(id)
&& let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure)
{
let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
let off = *at - now;
if off.hypot() > 1e-9
&& let Some(n) = d.node_mut(*id)
{
transform_node(n, Affine::translate(off), sc, true);
}
}
}
if restack {
let moved = d.remove_many(&targets)?;
@@ -590,11 +656,113 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
// Targets moved out of an Intertwine group leave it as ordinary art.
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
}
if !checked.is_empty() {
// Measured on a snapped copy: the edit itself snaps once, after Global Edit.
let mut snapped = d.clone();
crate::cmd::refresh_pixel_aligned(&before, &mut snapped);
for (id, _) in &xfs {
let Some(at) = checked.get(id) else { continue };
let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure);
let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6);
let misses = !kept
|| ob.is_none_or(|b| match size {
"none" => false,
"width" => (b.rect.width() - w).abs() > 1e-6,
"height" => (b.rect.height() - h).abs() > 1e-6,
_ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6,
});
if misses {
return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0)));
}
}
}
Ok(())
})?;
Ok(count)
}
/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width
/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the
/// source's width and height.
fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] {
let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side };
match size {
"width" => [w, follow(b.height(), b.width(), w)],
"height" => [follow(b.width(), b.height(), h), h],
_ => [w, h],
}
}
/// What [`fit_turned`] fits a target of Match Objects to.
struct Fit {
/// The target's reference point, which stays in place.
at: Point,
/// That point's index on the 9-point grid.
refi: usize,
/// The width and height wanted ([`match_goal`]).
goal: [f64; 2],
/// Scale Strokes & Effects.
strokes: bool,
/// Scale Corners.
corners: bool,
}
/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within
/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object
/// ends in. When it misses, for example when a stroke or an effect does not turn with the art,
/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone,
/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to
/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size.
fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option<Affine> {
let Fit { at, refi, goal, strokes, corners } = fit;
let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners }));
let how = s.bounds_measure();
let d = &s.doc().ok()?.doc;
let symbols = d.symbol_boxes();
let n = d.node(id)?;
let moved = |xf: Affine| {
let mut n = n.clone();
n.transform(xf, sc);
n
};
// The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own).
let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) };
// The frame the turn gives; sizing can leave the art without a width or a height to show it.
let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO };
let to_local = frame.to_doc().inverse();
let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how);
let tolerances = goal.map(|side| 1e-9 * side.max(1.0));
let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t);
let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6;
let rp = frame.to_local(at);
// The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point.
let scaled = |sx: f64, sy: f64| {
frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned
};
// `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke
// or an effect that does not turn with the art moves it.
let placed = |xf: Affine| -> Option<(Affine, Rect)> {
let b = measure(xf)?;
let correction = rp - vectorcraft_geom::reference_point(b, refi);
if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 {
return Some((xf, b));
}
let xf = frame.conjugate(Affine::translate(correction)) * xf;
Some((xf, measure(xf)?))
};
let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf);
if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) {
return Some(xf);
}
// The sizing above can leave the art without a width or a height that the turned object needs,
// so the fit starts again from the object as it is, turned.
let now = measure(turned)?;
let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 };
let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height()));
let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?;
placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf)
}
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
/// open where each one starts are compared with it.
@@ -841,6 +1009,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let distribute = switch_or(p, "distribute", false, C)?;
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
let strokes = scale_strokes(s, p, C)?;
let corners = scale_corners(s, p, C)?;
let ids = checked_ids_or_selection(s, p, C)?;
if ids.len() > MAX_OBJECTS {
return Err(bad(C, "too many objects selected (at most 20000)"));
@@ -923,17 +1092,17 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
let q = match apply {
"x" => json!({ "x": v, "reference": 0 }),
"y" => json!({ "y": v, "reference": 0 }),
"width" => json!({ "width": v, "strokes": strokes }),
"height" => json!({ "height": v, "strokes": strokes }),
"width" => json!({ "width": v, "strokes": strokes, "corners": corners }),
"height" => json!({ "height": v, "strokes": strokes, "corners": corners }),
// An area: both sides in proportion; an object without one keeps its size.
_ => {
let (w, h) = (o.b.rect.width(), o.b.rect.height());
let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 };
json!({ "width": w * k, "height": h * k, "strokes": strokes })
json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners })
}
};
xfs.push((o.id, object_bounds_transform(s, &q, o.id)?));
}
transform_each(s, "Sort Objects", strokes, &xfs)?;
transform_each(s, "Sort Objects", p, strokes, corners, &xfs)?;
Ok(count)
}
@@ -0,0 +1,206 @@
//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen
//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named
//! Artboard Guides. Its dialog is the UI's.
#[cfg(test)]
mod tests;
use std::collections::HashSet;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes};
use super::super::super::panelcmds::{artboard_at, listed_artboards};
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
use super::{LIMIT, number_in};
use crate::sanity::rect_in_range;
use crate::{DocState, Result, Session};
/// The command.
pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides";
/// The top-level layer the guides go on, made when the document has none of that name.
pub(crate) const LAYER: &str = "Artboard Guides";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.arrange.artboardGuides",
"Add Artboard Guides",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}",
has_artboards,
artboard_guides
)]
}
/// A document with at least one artboard is open.
fn has_artboards(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) }
}
/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no
/// longer has it, the artboard the document opened on, else the first.
fn active_artboard(st: &DocState) -> usize {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0)
}
/// The topmost top-level layer named [`LAYER`].
fn guide_layer(d: &Document) -> Option<NodeId> {
d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id)
}
/// `r`'s corners as an exact hash key, whichever way round `r` runs.
fn rect_key(r: Rect) -> [u64; 4] {
let r = r.abs();
[r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() })
}
#[cfg(test)]
thread_local! {
static GUIDE_NODES_VISITED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn guide_rectangles(d: &Document, layer: Option<NodeId>) -> HashSet<[u64; 4]> {
let mut rects = HashSet::new();
if let Some(n) = layer.and_then(|id| d.node(id)) {
n.walk(&mut |c| {
#[cfg(test)]
GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1));
// The anchors' bounds: `traces` only accepts segments that stay between their anchors.
if let NodeKind::Path { path, guide: true, .. } = &c.kind
&& let [sp] = &path.subpaths[..]
&& let Some(first) = sp.anchors.first()
{
let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p));
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
if traces(path, &corners) {
rects.insert(rect_key(r));
}
}
});
}
rects
}
/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b`
/// without turning back? Its handles lie on that line, and the curve's position along it never reverses.
fn straight(a: &Anchor, b: &Anchor) -> bool {
let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| {
if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) {
return false;
}
let s = (f(b.p) - f(a.p)).signum();
let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s);
// The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1].
let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2);
let curve = u - 2.0 * v + w;
let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 };
u >= 0.0 && w >= 0.0 && vertex >= 0.0
};
if a.p == b.p {
return a.h_out == a.p && b.h_in == a.p;
}
along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x)
}
/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round?
fn traces(path: &PathData, corners: &[Point; 4]) -> bool {
let [sp] = &path.subpaths[..] else { return false };
if !sp.closed || sp.anchors.len() < 4 {
return false;
}
let n = sp.anchors.len();
if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) {
return false;
}
// A last anchor on the first one only closes the path: the check above has kept its handles on that
// point, so the corners are read without it.
let m = if sp.anchors[n - 1].p == sp.anchors[0].p { n - 1 } else { n };
let points: Vec<Point> = sp
.anchors
.iter()
.take(m)
.enumerate()
.filter_map(|(i, a)| {
let prev = sp.anchors[(i + m - 1) % m].p;
let next = sp.anchors[(i + 1) % m].p;
let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y))
|| (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x));
(!interior).then_some(a.p)
})
.collect();
let [first, second, _, _] = &points[..] else { return false };
let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else {
return false;
};
// 1 runs the way `corners` does, 3 the other way.
let step = (next + 4 - start) % 4;
(step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4])
}
fn artboard_guides(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?;
let all = switch_or(p, "all", false, C)?;
let listed = p.get("artboards").filter(|v| !v.is_null());
if all && listed.is_some() {
return Err(bad(C, "give `all` or `artboards`, not both"));
}
let st = s.doc()?;
let d = &st.doc;
if d.artboards.is_empty() {
return Err(bad(C, "the document has no artboards"));
}
// The active artboard: the one the app passes, else the view's, recorded for a replay.
let active = artboard_at(d, p, "artboard", C)?;
let indices: Vec<usize> = match listed {
Some(v) => listed_artboards(d, v, "artboards", C)?,
None if all => (0..d.artboards.len()).collect(),
None => vec![active.unwrap_or_else(|| active_artboard(st))],
};
if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) {
s.note_journal("artboard", json!(i));
}
let st = s.doc()?;
let d = &st.doc;
let layer = guide_layer(d);
let mut existing = guide_rectangles(d, layer);
let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0);
for i in indices {
let Some(board) = d.artboards.get(i) else { continue };
let r = board.rect.inflate(offset, offset);
if !(r.width() > 0.0 && r.height() > 0.0) {
return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name)));
}
if !rect_in_range(r) {
return Err(bad(C, "the guide would reach past the edge of the canvas"));
}
if !existing.insert(rect_key(r)) {
skipped += 1;
} else {
rects.push(r);
}
}
if rects.is_empty() {
return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped }));
}
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let (layer, ids) = s.edit("Add Artboard Guides", |d, _| {
let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER)));
let mut ids = Vec::with_capacity(rects.len());
for r in &rects {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default());
look.apply(d, &mut n);
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
ids.push(d.insert(Some(layer), usize::MAX, n)?);
}
Ok((layer, ids))
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "layer": layer.0, "skipped": skipped }))
}
@@ -0,0 +1,336 @@
//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer
//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused
//! without a change.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
use super::{COMMAND, LAYER};
use crate::Session;
/// A new document with one 400 × 300 pt artboard and a second one beside it.
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn board(s: &Session, i: usize) -> Rect {
s.doc().unwrap().doc.artboards[i].rect
}
fn ids(r: &Value) -> Vec<NodeId> {
r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect()
}
/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`.
fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect {
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path");
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer");
n.geometric_bounds().unwrap()
}
fn near(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9)
}
fn layer_names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect()
}
#[test]
fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() {
let mut s = session();
let n = steps(&s);
let before = layer_names(&s);
let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
let layer = NodeId(r["layer"].as_u64().unwrap());
assert_eq!(r["skipped"], json!(0));
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
// The active artboard is the first when the view has not picked one.
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id));
let d = &s.doc().unwrap().doc;
assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others");
assert_eq!(d.layers.last().unwrap().display_name(), LAYER);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide");
}
#[test]
fn the_active_artboard_is_the_one_the_view_keeps() {
let mut s = session();
let second = s.doc().unwrap().doc.artboards[1].id;
s.doc_mut().unwrap().active_artboard = Some(second);
let r = s.execute(COMMAND, &json!({})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges");
assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay");
// The artboard the app passes wins over the view's.
let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0)));
assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard");
}
#[test]
fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() {
let mut s = session();
let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.new", &json!({"name": "Art"})).unwrap();
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap();
let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s));
let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step for every artboard");
assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused");
assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added");
let added = ids(&r);
assert_eq!(added.len(), 2);
for (i, id) in added.into_iter().enumerate() {
assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}");
}
let l = s.doc().unwrap().doc.node(layer).unwrap().clone();
assert!(l.locked && !l.visible, "the layer keeps its lock and visibility");
}
#[test]
fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0)));
// Again: nothing to add, and no undo step.
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before);
// Both artboards: only the new one is added.
let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap();
assert_eq!(both["skipped"], json!(1));
let [first] = ids(&both)[..] else { panic!("one guide: {both}") };
assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0)));
assert_eq!(steps(&s), n + 1);
}
#[test]
fn a_guide_grouped_inside_the_layer_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group));
assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id));
let (before, n) = (d.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}));
assert_eq!(steps(&s), n, "a run that adds nothing makes no step");
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
}
#[test]
fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
let layer = NodeId(r["layer"].as_u64().unwrap());
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0).inflate(5.0, 5.0);
let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)];
// Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one.
for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] {
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
*path = PathData::single(SubPath::polyline(&points, true));
}
let n = steps(&s);
let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}");
assert_eq!(steps(&s), n);
}
}
#[test]
fn collinear_midpoints_do_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let points = [
Point::new(b.center().x, b.y0),
Point::new(b.x1, b.y0),
Point::new(b.x1, b.center().y),
Point::new(b.x1, b.y1),
Point::new(b.center().x, b.y1),
Point::new(b.x0, b.y1),
Point::new(b.x0, b.center().y),
Point::new(b.x0, b.y0),
];
for reverse in [false, true] {
let mut points = points.to_vec();
if reverse {
points.reverse();
}
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}));
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn a_closing_anchor_on_the_first_one_does_not_add_another_guide_or_history_step() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
for reverse in [false, true] {
let mut points = corners.to_vec();
if reverse {
points.reverse();
}
points.push(points[0]);
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(SubPath::polyline(&points, true));
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "reverse: {reverse}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
}
#[test]
fn handles_along_a_side_still_match_and_handles_off_it_do_not() {
let mut s = session();
let r = s.execute(COMMAND, &json!({})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
let b = board(&s, 0);
let mid = Point::new(b.center().x, b.y0);
let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)];
let corner = points[1];
let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| {
let mut sp = SubPath::polyline(&points, true);
sp.anchors[0].h_in = h_in;
sp.anchors[0].h_out = h_out;
sp.anchors[1].h_in = corner_in;
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") };
*path = PathData::single(sp);
};
// The extra anchor's handles lie along the top side: the guide still matches.
// Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths).
let eighth = (corner.x - mid.x) / 8.0;
for (h_out, corner_in) in
[(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))]
{
set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in);
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
let again = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc, before);
}
// A handle off the side bends it: the path is not that guide, so one is added.
set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner);
let other = s.execute(COMMAND, &json!({})).unwrap();
assert_eq!(other["skipped"], json!(0));
assert_eq!(ids(&other).len(), 1);
}
#[test]
fn every_artboard_shares_one_walk_of_existing_guides() {
let mut s = session();
s.execute(COMMAND, &json!({"all": true})).unwrap();
super::GUIDE_NODES_VISITED.with(|count| count.set(0));
s.execute(COMMAND, &json!({})).unwrap();
let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0));
assert!(single > 0);
let n = steps(&s);
let r = s.execute(COMMAND, &json!({"all": true})).unwrap();
assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single);
assert!(ids(&r).is_empty());
assert_eq!(r["skipped"], json!(2));
assert_eq!(steps(&s), n);
}
#[test]
fn release_guides_gives_back_a_rectangle_path() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap();
let [id] = ids(&r)[..] else { panic!("one guide: {r}") };
s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(matches!(n.kind, NodeKind::Path { guide: false, .. }));
assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0)));
}
#[test]
fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() {
let mut s = session();
let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s));
// The second artboard is 100 pt tall: an inset of 50 leaves it no height.
for p in [
json!({"offset": -50, "all": true}),
json!({"offset": -200}),
json!({"offset": "9 pt"}),
json!({"offset": 1_000_001}),
json!({"offset": -1e308}),
json!({"all": 1}),
json!({"all": true, "artboards": [0]}),
json!({"artboards": []}),
json!({"artboards": [2]}),
json!({"artboards": [-1]}),
json!({"artboards": [0.5]}),
json!({"artboards": "0"}),
] {
assert!(s.execute(COMMAND, &p).is_err(), "{p}");
}
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before, "the document is unchanged");
let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string();
assert!(e.contains("no width or height"), "{e}");
}
#[test]
fn a_guide_past_the_edge_of_the_canvas_is_refused() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap();
let n = steps(&s);
let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string();
assert!(e.contains("past the edge of the canvas"), "{e}");
assert_eq!(steps(&s), n);
s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap();
}
#[test]
fn it_is_off_without_artboards() {
let mut s = session();
let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled;
assert!(enabled(&s));
Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear();
assert!(!enabled(&s));
assert!(s.execute(COMMAND, &json!({})).is_err());
}
@@ -439,6 +439,19 @@ fn match_gives_the_others_the_key_objects_size() {
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
}
#[test]
fn match_keeps_the_proportion_of_a_very_thin_target() {
let b = Rect::new(0.0, 0.0, 1e-10, 1.0);
let [w, h] = super::match_goal("width", (1.0, 5.0), b);
assert_eq!(w, 1.0);
assert!((h - 1e10).abs() <= 1.0, "{h}");
let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10));
assert!((w - 1e10).abs() <= 1.0, "{w}");
assert_eq!(h, 1.0);
// A target with no width keeps its height.
assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]);
}
#[test]
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
let mut s = session();
@@ -512,6 +525,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() {
}
}
#[test]
fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() {
for wrap in ["path", "group", "compound"] {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
if wrap != "compound" {
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
}
let target = match wrap {
"group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()),
"compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()),
_ => target,
};
select(&mut s, &[target]);
if wrap == "compound" {
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
}
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
// Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points,
// and snapping them back to the grid would move that center.
let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
assert!(e.contains("reference point"), "{wrap}: {e}");
assert_eq!(steps(&s), n, "{wrap}: no undo step");
assert!(*s.doc().unwrap().doc == *before, "{wrap}");
}
}
#[test]
fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() {
let mut s = session();
let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0);
select(&mut s, &[aligned, loose]);
let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0);
select(&mut s, &[source]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let gap = |s: &Session| {
let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center());
b - a
};
let before = s.doc().unwrap().doc.clone();
match s.execute("addon.arrange.match", &json!({"rotate": true})) {
// Turned a quarter, the members' centers keep their distance and only change direction.
Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)),
Err(e) => {
assert!(e.to_string().contains("reference point"), "{e}");
assert!(*s.doc().unwrap().doc == *before);
}
}
}
#[test]
fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() {
for angle in [0, 30] {
@@ -638,6 +712,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
}
/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square,
/// and replaying its journal entry after the preference is turned off scales the corners the same way.
fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() {
Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0],
_ => panic!("not a live rectangle"),
};
select(&mut s, &[a, b]);
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
s.execute(cmd, &p).unwrap();
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s));
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s));
}
#[test]
fn match_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
}
#[test]
fn swap_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn match_stacking_leaves_a_clipping_path_in_place() {
let mut s = session();
@@ -664,6 +776,16 @@ fn match_size_refuses_a_target_with_no_width() {
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
}
#[test]
fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() {
let mut s = session();
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0);
select(&mut s, &[line, b]);
s.execute("select.key", &json!({"id": b.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]);
}
#[test]
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
let mut s = session();
@@ -750,6 +872,234 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() {
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_refuses_restacking_into_a_locked_container() {
for lock_ancestor in [false, true] {
let mut s = session();
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[source]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, &[group]);
let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let locked = if lock_ancestor { ancestor } else { group };
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true;
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err();
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
}
#[test]
fn match_refuses_restacking_among_a_blends_inputs() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
s.execute("object.blend.make", &json!({})).unwrap();
let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, target]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("can't go beside the source object"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn match_refuses_taking_a_target_out_of_a_locked_container() {
let mut s = session();
let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
select(&mut s, &[target]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true;
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("the layer or group is locked"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
select(&mut s, &[a, b]);
let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
assert_eq!(layer_order(&s), [blend, between, source]);
select(&mut s, &[a, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("a blend's input objects"), "{e}");
assert_eq!(steps(&s), n);
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
select(&mut s, &[blend, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [between, source, blend]);
}
#[test]
fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
select(&mut s, &[a, b]);
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0);
let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0);
assert_eq!(layer_order(&s), [g, between, target]);
let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id;
select(&mut s, &[member, target]);
s.execute("select.key", &json!({"id": member.0})).unwrap();
let n = steps(&s);
let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err();
assert!(e.to_string().contains("Live Paint art"), "{e}");
assert_eq!(steps(&s), n);
select(&mut s, &[g, target]);
s.execute("select.key", &json!({"id": g.0})).unwrap();
let before = s.doc().unwrap().doc.node(g).unwrap().clone();
s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap();
assert_eq!(steps(&s), n + 1, "one undo step");
assert_eq!(layer_order(&s), [g, target, between]);
assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before);
}
#[test]
fn match_turns_art_with_a_moving_effect_about_its_measured_point() {
let mut s = session();
s.prefs.use_preview_bounds = true;
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let center = |s: &Session| {
let bx = s.transform_box(&[b]).unwrap();
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
};
let before = center(&s);
select(&mut s, &[a, b]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
let after = center(&s);
assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}");
}
#[test]
fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() {
for size in ["none", "both"] {
for dx in [0.0, 0.25] {
let mut s = session();
s.prefs.use_preview_bounds = true;
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
select(&mut s, &[art]);
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.move", &json!({"dx": dx})).unwrap();
s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let center = |s: &Session| {
let b = s.transform_box(&[target]).unwrap();
b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4)
};
let at = center(&s);
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size}));
if dx == 0.0 {
result.unwrap();
assert!((center(&s) - at).hypot() < 1e-6, "{size}");
let b = s.transform_box(&[target]).unwrap();
assert!(b.angle.abs() < 1e-6, "{size}: {b:?}");
if size == "both" {
let wanted = s.transform_box(&[source]).unwrap();
assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}");
assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}");
}
assert_eq!(steps(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
} else {
let error = result.unwrap_err().to_string();
assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}");
}
assert_eq!(steps(&s), n, "{size}, dx={dx}");
assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}");
}
}
}
#[test]
fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() {
let mut s = session();
s.prefs.use_preview_bounds = false;
let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0);
let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
select(&mut s, &[art]);
let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap());
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
s.execute("object.move", &json!({"dx": 0.25})).unwrap();
select(&mut s, &[source, target]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let before = s.doc().unwrap().doc.clone();
let n = steps(&s);
// Turned back to its natural angle, the instance snaps to whole points, which moves its center.
let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string();
assert!(error.contains("can't keep its size and reference point as it turns"), "{error}");
assert_eq!(steps(&s), n);
assert!(*s.doc().unwrap().doc == *before);
}
#[test]
fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() {
for grouped in [false, true] {
let mut s = session();
s.prefs.use_preview_bounds = true;
let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0);
select(&mut s, &[a]);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0);
s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap();
let b = if grouped {
select(&mut s, &[b]);
NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())
} else {
b
};
let center = |s: &Session| {
let bx = s.transform_box(&[b]).unwrap();
bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4)
};
let before = center(&s);
select(&mut s, &[a, b]);
s.execute("select.key", &json!({"id": a.0})).unwrap();
s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap();
let after = center(&s);
assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}");
let d = &s.doc().unwrap().doc;
assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6);
}
}
#[test]
fn match_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
@@ -765,6 +1115,169 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() {
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them,
/// and replaying its journal entry after the preference is turned off scales them the same way.
fn replays_the_corner_shapes_it_ran_with(cmd: &str, p: Value) {
let mut s = session();
let square = |s: &mut Session, x: f64, w: f64| {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap())
};
let a = square(&mut s, 0.0, 10.0);
let b = square(&mut s, 100.0, 20.0);
let shapes = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind)));
out.sort();
out
};
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
select(&mut s, &[a, b]);
s.execute(cmd, &p).unwrap();
let ran = shapes(&s);
let (id, q) = s.journal.last().unwrap().clone();
assert_eq!(id, cmd);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
select(&mut s, &[a, b]);
s.replay(&id, &q).unwrap();
assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners");
}
#[test]
fn match_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.match", json!({"size": "both"}));
}
#[test]
fn set_size_of_each_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30}));
}
#[test]
fn swap_replays_two_rounded_squares_with_the_corners_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.swap", json!({"size": true}));
}
#[test]
fn replace_replays_with_the_corner_scaling_it_ran_with() {
replays_the_corner_shapes_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"}));
}
#[test]
fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
select(&mut s, &[target]);
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap();
let b = bounds(&s, target);
assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}");
}
#[test]
fn match_size_fits_a_transform_copy_once_the_target_is_turned() {
for size in ["width", "both"] {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
if size == "both" {
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
}
}
}
#[test]
fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap();
let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0);
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
}
#[test]
fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
let center = s.transform_box(&[target]).unwrap().center();
let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0);
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
let wanted = s.transform_box(&[source]).unwrap();
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
let measured = s.transform_box(&[target]).unwrap();
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}");
}
#[test]
fn match_size_refuses_a_width_below_a_fixed_transform_copy() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap();
let before = s.transform_box(&[target]).unwrap();
assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}");
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false}));
assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target]));
}
#[test]
fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
s.execute(
"effect.apply",
&json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}),
)
.unwrap();
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
}
#[test]
fn match_size_takes_a_huge_object_down_to_a_point() {
let mut s = session();
let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0);
let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0);
select(&mut s, &[target, source]);
s.execute("select.key", &json!({"id": source.0})).unwrap();
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
let b = bounds(&s, target);
assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}");
}
#[test]
fn match_refuses_bad_params() {
let mut s = session();
+13 -4
View File
@@ -1,9 +1,10 @@
//! Artwork Cleanup (`addon.cleanup.*`), a built-in add-on: Simplify Anchors (Keep Shape), the
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup and Rejoin Path
//! Pieces, and its text tools ([`text`]). Its panel and its submenu, Object › Plug-ins › Artwork
//! Cleanup, are the UI's.
//! Document Health Check (check, show and fix the issues it finds), Deep Ungroup, Release All
//! Containers ([`release`]) and Rejoin Path Pieces, and its text tools ([`text`]). Its panel and
//! its submenu, Object › Plug-ins › Artwork Cleanup, are the UI's.
mod checks;
mod release;
#[cfg(test)]
mod tests;
mod text;
@@ -64,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fix All Issues",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents → {scope, total, fixed: {kind: count}}",
"{scope?: \"selection\"|\"document\", kinds?: [kind…] (default: all; see addon.cleanup.check)} fix the issues addon.cleanup.check finds, in up to three rounds while a round still finds some (a fix can leave issues for another kind), as one undo step: what is empty, unpainted, invisible, duplicated or off the artboards goes, anchors merge, snap or go, tiny handles retract, paths close and needless groups, compound paths and clipping groups give way to their contents. An error, with nothing fixed, when the fixes would delete the artboard an open Create Font Sheet dialog uses → {scope, total, fixed: {kind: count}}",
has_doc,
fix
),
@@ -87,6 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
rejoin
),
];
v.extend(release::specs());
v.extend(text::specs());
v
}
@@ -260,6 +262,13 @@ fn fix(s: &mut Session, p: &Value) -> Result<Value> {
}
// With nothing to fix, the document and its undo history stay as they are.
if total > 0 {
if let Some(guard) = &s.artboard_deletion_guard {
let st = s.doc()?;
let protected = |doc: &Document| doc.artboards.iter().any(|a| a.id == guard.artboard);
if (st.uid, st.reverts) == guard.document && protected(&st.doc) && !protected(&d) {
return Err(EngineError::Other(guard.message.clone()));
}
}
sel.prune(&d);
s.edit("Fix Issues", |doc, selection| {
*doc = d;
@@ -0,0 +1,422 @@
//! Artwork Cleanup's Release All Containers (`addon.cleanup.releaseAll`): every group, clipping
//! mask and compound path in the selection, the objects named or the whole document, taken apart
//! at every level of nesting as one undo step, so that only the objects they held are left.
#[cfg(test)]
mod tests;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, LiveShape, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::checks::{MAX_OBJECTS, Scope};
use super::{named, retain_targets, scope_of};
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use crate::{EngineError, Result, Session};
/// The command.
const COMMAND: &str = "addon.cleanup.releaseAll";
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cleanup.releaseAll",
"Release All Containers…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), ids?: [id…] (the objects, groups and layers to release in, instead of `scope`; duplicate ids are an error), groups?: bool (true: groups are ungrouped), clipGroups?: bool (true: clipping groups are ungrouped and layers stop clipping unless their clipping path or clipped artwork overlaps a locked artboard, their released clipping paths kept as plain paths), compoundPaths?: bool (true: compound paths, and paths of several subpaths, become one path per subpath); at least one of the three true; `scope` and the three are never null} take apart every container of the kinds asked for, at every level of nesting, as one undo step when one goes; layers stay; each object keeps the opacity of the groups and compound paths it was in, and a compound path's paths take its paint; objects with live effects on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs, dimensions, flares, Objects on Path, generated art, Shaper Groups, Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole, including directly selected or named descendants; the entire clipping mask subtree of a clipping group or layer that stays is left as it is, including directly selected or named descendants; from the selection or the document, locked and hidden objects, and objects on a locked artboard, stay whole; named by `ids`, locked and hidden ones are taken apart too (their objects become locked or hidden as they were), but not those on a locked artboard; the selection keeps what it held, each object taken apart replaced by what it left, locked and hidden objects left out → {scope (\"selection\", \"document\" or \"ids\"), ids (the objects selected), groups, clipGroups, compoundPaths (how many of each were released)}",
has_doc,
release_all
)]
}
/// The kinds of container a request takes apart.
#[derive(Clone, Copy)]
struct Kinds {
groups: bool,
clips: bool,
compounds: bool,
}
impl Kinds {
/// Whether a group is taken apart: a clipping group (`clip`) with `clips`, another with `groups`.
fn takes_group(self, clip: bool) -> bool {
if clip { self.clips } else { self.groups }
}
}
/// One run over the objects: what it takes apart and what it found.
struct Release<'a> {
kinds: Kinds,
/// Locked and hidden objects are taken apart too.
named: bool,
/// The artwork on a locked artboard, which stays whole.
held: &'a HashSet<NodeId>,
/// Groups, clipping groups and layers, and compound paths released.
counts: [usize; 3],
/// Objects made from the containers taken apart.
made: usize,
/// Each container taken apart and the objects left in its place.
left: HashMap<NodeId, Vec<NodeId>>,
}
/// Whether `n` stays whole whatever is asked: a live object kept as a group or compound path
/// (a compound shape, Live Paint group, graph, dimension, flare, Objects on Path, generated art,
/// Shaper Group, Image Trace object, a clipping path's painted pieces), a path with Live Corners,
/// whose parts would lose their editable corners, one with an opacity mask or live effects
/// on its appearance or fill and stroke rows, or a group with fill or stroke rows of its own.
fn live(n: &Node) -> bool {
let x = n.extras();
matches!(&n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. })
|| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))
|| !n.appearance.effects.is_empty()
|| n.appearance.items.iter().any(|item| !item.effects().is_empty())
|| x.mask.is_some()
|| x.shaper.is_some()
|| x.trace.is_some()
|| x.graph.is_some()
|| x.dimension.is_some()
|| x.flare.is_some()
|| x.objects_on_path.is_some()
|| x.generated.is_some()
|| x.live_paint_gaps.is_some()
|| x.clip_pieces
|| (matches!(&n.kind, NodeKind::Group { .. }) && !n.appearance.items.is_empty())
|| n.is_compound_shape()
|| is_live_paint(n)
}
/// The artwork under `n` is added to `out`.
fn candidates(n: &Node, clips: bool, out: &mut Vec<NodeId>) {
let candidate = match &n.kind {
NodeKind::Layer { .. } => false,
NodeKind::Group { .. } | NodeKind::Compound { .. } => true,
NodeKind::Path { path, .. } => clips || path.subpaths.len() > 1,
_ => clips,
};
if candidate {
out.push(n.id);
}
if let Some(children) = n.children() {
children.iter().for_each(|c| candidates(c, clips, out));
}
}
impl Release<'_> {
fn total(&self) -> usize {
self.counts.iter().sum()
}
/// Whether `n` is left as it is: locked or hidden (unless named), on a locked artboard, or live.
fn keeps(&self, n: &Node) -> bool {
(!self.named && (n.locked || !n.visible)) || self.held.contains(&n.id) || live(n)
}
/// `n` with the containers in it released, into `out`; `member` counts what a container left.
fn node(&mut self, d: &mut Document, n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if self.keeps(&n) {
if member {
self.made(1)?;
}
out.push(n);
return Ok(());
}
match &n.kind {
NodeKind::Group { clip, .. } if self.kinds.takes_group(*clip) => {
let clip = *clip;
self.counts[usize::from(clip)] += 1;
self.take_apart(d, n, clip, false, out)
}
NodeKind::Compound { .. } if self.kinds.compounds => {
self.counts[2] += 1;
self.take_apart(d, n, false, true, out)
}
NodeKind::Path { path, clipping: false, guide: false, .. } if self.kinds.compounds && path.subpaths.len() > 1 => {
self.counts[2] += 1;
self.split(d, (*n).clone(), out)
}
NodeKind::Group { .. } | NodeKind::Layer { .. } => self.keep(d, n, member, out),
_ => {
if member {
self.made(1)?;
}
out.push(n);
Ok(())
}
}
}
/// Group or compound path `n` replaced by its members, released in turn. Members take on the
/// container's opacity, are hidden when it was hidden and locked when it was locked; a
/// compound path's take its paint; a clipping group's clipping path becomes a plain path.
fn take_apart(&mut self, d: &mut Document, n: Arc<Node>, clip: bool, compound: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(children) = n.children() else { return Ok(()) };
let mut parts = vec![];
for (k, c) in children.iter().enumerate() {
let mut c = (**c).clone();
if clip
&& k == 0
&& let NodeKind::Path { clipping, .. } = &mut c.kind
{
*clipping = false;
}
if compound {
c.appearance = n.appearance.clone();
if n.extras().pixel_aligned {
c.extras_mut().pixel_aligned = true;
}
}
c.opacity *= n.opacity;
c.visible &= n.visible;
c.locked |= n.locked;
self.node(d, Arc::new(c), true, &mut parts)?;
}
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Path `n` of several subpaths as one path per subpath with its paint, in the same stacking
/// order; the first keeps its id.
fn split(&mut self, d: &mut Document, n: Node, out: &mut Vec<Arc<Node>>) -> Result<()> {
let Some(path) = n.path_data() else { return Ok(()) };
if self.made.saturating_add(path.subpaths.len()) > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
let mut template = n.clone();
if let NodeKind::Path { path, live, .. } = &mut template.kind {
(*path, *live) = (PathData::single(Default::default()), None);
}
let mut parts = Vec::with_capacity(path.subpaths.len());
for (k, sp) in path.subpaths.iter().enumerate() {
let mut c = if k == 0 { template.clone() } else { d.reid(&template) };
if let NodeKind::Path { path, live, .. } = &mut c.kind {
(*path, *live) = (PathData::single(sp.clone()), None);
}
parts.push(Arc::new(c));
}
self.made(parts.len())?;
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
out.extend(parts);
Ok(())
}
/// Group or layer `n` kept, with the containers in it released. A layer stops clipping when
/// clipping groups are released; the clipping path of a group or layer that still clips is
/// left as it is. Unchanged, `n` itself goes to `out`.
fn keep(&mut self, d: &mut Document, mut n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
if member {
self.made(1)?;
}
let before = self.total();
let mut clips = n.clips();
if clips && n.is_layer() && self.kinds.clips && !n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) {
self.counts[1] += 1;
let n = Arc::make_mut(&mut n);
n.set_clips(false);
clips = false;
if let Some(first) = n.children_mut().and_then(|c| c.first_mut())
&& let NodeKind::Path { clipping, .. } = &mut Arc::make_mut(first).kind
{
*clipping = false;
}
}
let Some(children) = n.children() else {
out.push(n);
return Ok(());
};
let mut kept = Vec::with_capacity(children.len());
for (k, c) in children.iter().enumerate() {
if clips && k == 0 {
if member {
self.made(1)?;
}
kept.push(Arc::clone(c));
} else {
self.node(d, Arc::clone(c), member, &mut kept)?;
}
}
if self.total() != before
&& let Some(ch) = Arc::make_mut(&mut n).children_mut()
{
*ch = kept;
}
out.push(n);
Ok(())
}
fn holds_art(&self, n: &Node) -> bool {
self.held.contains(&n.id) || n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c)))
}
/// Counts the objects made, refusing a run that makes too many.
fn made(&mut self, count: usize) -> Result<()> {
self.made += count;
if self.made > MAX_OBJECTS {
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
}
Ok(())
}
/// `id`, or the objects left in its place when it was taken apart.
fn replaced(&self, id: NodeId, into: &mut Vec<NodeId>) {
match self.left.get(&id) {
Some(ids) => into.extend(ids),
None => into.push(id),
}
}
}
/// Whether shown artwork in `n` overlaps a locked artboard: a plain group that is not live
/// ([`live`]) by its shown members, anything else by its own bounds.
fn shows_on(locks: &LockedArtboards<'_>, n: &Node) -> bool {
if !n.visible {
return false;
}
match (&n.kind, n.children()) {
(NodeKind::Group { clip: false, .. }, Some(children)) if !live(n) => children.iter().any(|c| shows_on(locks, c)),
_ => locks.holds(n),
}
}
/// Whether `id` is in the clipping mask subtree of a clipping group or layer.
fn in_clipping_mask(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|chain| {
chain
.windows(2)
.any(|pair| d.node(pair[0]).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == pair[1])))
})
}
fn release_all(s: &mut Session, p: &Value) -> Result<Value> {
if !p.is_object() {
return Err(bad(COMMAND, "parameters must be an object"));
}
for key in ["groups", "clipGroups", "compoundPaths"] {
if p.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(bad(COMMAND, format!("`{key}` must be true or false")));
}
}
if p.get("scope").is_some_and(|v| !matches!(v.as_str(), Some("selection" | "document"))) {
return Err(bad(COMMAND, "`scope` must be \"selection\" or \"document\""));
}
if let Some(ids) = p.get("ids").filter(|v| !v.is_null()) {
let ids = ids.as_array().ok_or_else(|| bad(COMMAND, "`ids` must be an array of non-negative integer object ids"))?;
let mut seen = HashSet::new();
for id in ids {
let id = id.as_u64().ok_or_else(|| bad(COMMAND, "`ids` must contain non-negative integer object ids"))?;
if !seen.insert(id) {
return Err(bad(COMMAND, format!("duplicate object id {id} in `ids`")));
}
}
}
let kinds = Kinds {
groups: switch_or(p, "groups", true, COMMAND)?,
clips: switch_or(p, "clipGroups", true, COMMAND)?,
compounds: switch_or(p, "compoundPaths", true, COMMAND)?,
};
if !(kinds.groups || kinds.clips || kinds.compounds) {
return Err(bad(COMMAND, "`groups`, `clipGroups` and `compoundPaths` are all false: there is nothing to release"));
}
let named = named(p);
if named && p.get("scope").is_some() {
return Err(bad(COMMAND, "give `scope` or `ids`, not both"));
}
let (roots, name) = if named {
let mut roots = checked_ids_or_selection(s, p, COMMAND)?;
retain_targets(&s.doc()?.doc, &mut roots, true, |id| *id);
(roots, "ids")
} else {
match scope_of(s, p, COMMAND)? {
(Scope::Document, name) => (s.doc()?.doc.layers.iter().map(|l| l.id).collect(), name),
(Scope::Objects(mut roots), name) => {
retain_targets(&s.doc()?.doc, &mut roots, false, |id| *id);
(roots, name)
}
}
};
let st = s.doc()?;
let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone());
// The artwork on a locked artboard, found while nothing is changed yet.
let held: HashSet<NodeId> = if d.artboards.iter().any(|a| a.locked) {
let mut found = vec![];
for n in roots.iter().filter_map(|id| d.node(*id)) {
candidates(n, kinds.clips, &mut found);
}
let locks = d.locked_artboards();
let mut held: HashSet<NodeId> = found.iter().copied().filter(|id| locks.holds_id(*id)).collect();
// A shown clipping group whose clipped artwork overlaps a locked artboard stays whole,
// wherever its clipping path lies, when clipping groups are released; the clipping groups
// the targets are in count too.
let ancestors = roots.iter().filter_map(|id| d.ancestry(*id)).flatten();
let clip_groups: HashSet<NodeId> = found
.iter()
.copied()
.chain(ancestors)
.filter(|id| kinds.clips && d.node(*id).is_some_and(|n| matches!(&n.kind, NodeKind::Group { clip: true, .. })))
.collect();
// Pattern editing mode's art is on no artboard.
let pattern_layer = d.pattern_edit.as_ref().map(|e| e.layer);
for id in clip_groups {
let shown = d.ancestry(id).is_some_and(|chain| chain.iter().all(|a| Some(*a) != pattern_layer && d.node(*a).is_some_and(|n| n.visible)));
if shown
&& let Some(n) = d.node(id)
&& n.children().is_some_and(|c| c.iter().skip(1).any(|c| shows_on(&locks, c)))
{
held.insert(id);
}
}
held
} else {
HashSet::new()
};
let mut run = Release { kinds, named, held: &held, counts: [0; 3], made: 0, left: HashMap::new() };
let mut items = vec![];
for id in roots {
// Direct targets inside a live object or clipping mask stay whole.
let protected =
d.ancestry(id).is_some_and(|chain| chain.iter().take(chain.len().saturating_sub(1)).filter_map(|id| d.node(*id)).any(|n| run.keeps(n)));
if in_clipping_mask(&d, id) || protected {
continue;
}
let Some(n) = d.node_arc(id).cloned() else { continue };
let before = run.total();
let mut out = vec![];
run.node(&mut d, n, false, &mut out)?;
if run.total() != before {
items.push((id, out.into_iter().map(Arc::unwrap_or_clone).collect()));
}
}
let [groups, clips, compounds] = run.counts;
// With nothing to release, the document, the selection and the undo history stay as they are.
if run.total() == 0 {
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
return Ok(json!({ "scope": name, "ids": ids, "groups": 0, "clipGroups": 0, "compoundPaths": 0 }));
}
d.insert_beside(items, true)?;
let mut ids = vec![];
for id in sel.objects.iter() {
run.replaced(*id, &mut ids);
}
// Locked and hidden objects, and those in locked or hidden groups, are not selected.
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
let kept: HashSet<NodeId> = ids.iter().copied().collect();
let removed: Vec<NodeId> = sel.objects.iter().copied().filter(|id| run.left.contains_key(id) || !kept.contains(id)).collect();
sel.remove_all(removed);
let mut seen = HashSet::new();
sel.objects = ids.into_iter().filter(|id| seen.insert(*id)).collect();
sel.prune(&d);
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
s.edit("Release All Containers", |doc, selection| {
*doc = d;
*selection = sel;
Ok(())
})?;
Ok(json!({ "scope": name, "ids": ids, "groups": groups, "clipGroups": clips, "compoundPaths": compounds }))
}
@@ -0,0 +1,860 @@
//! Release All Containers: every level taken apart as one undo step, the kinds asked for only,
//! the selection, the document and named objects, clipping layers, what stays whole, and refusals.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, LiveShape, Node, NodeId, NodeKind};
use crate::Session;
const C: &str = "addon.cleanup.releaseAll";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap())
}
fn node(s: &Session, id: NodeId) -> Option<Node> {
s.doc().unwrap().doc.node(id).cloned()
}
fn change(s: &mut Session, id: NodeId, f: impl FnOnce(&mut Node)) {
s.edit("t", |d, _| {
f(d.node_mut(id).unwrap());
Ok(())
})
.unwrap();
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.select(|_, sel| sel.set(ids.iter().copied())).unwrap();
}
fn selected(s: &Session) -> Vec<NodeId> {
s.doc().unwrap().selection.objects.to_vec()
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// The objects directly in layer `k`.
fn layer(s: &Session, k: usize) -> Vec<NodeId> {
s.doc().unwrap().doc.layers[k].children().unwrap().iter().map(|n| n.id).collect()
}
fn group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.group", &json!({})).unwrap())
}
fn compound(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap())
}
/// A clipping group of `ids`, the last of them the clipping path.
fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId {
select(s, ids);
id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap())
}
fn counts(r: &Value) -> (u64, u64, u64) {
(r["groups"].as_u64().unwrap(), r["clipGroups"].as_u64().unwrap(), r["compoundPaths"].as_u64().unwrap())
}
fn plain(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).unwrap().kind, NodeKind::Path { clipping: false, ref path, .. } if path.subpaths.len() == 1)
}
fn red() -> Appearance {
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 1.0)
}
#[test]
fn release_all_takes_apart_every_level_as_one_step() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let p = rect(&mut s, 70.0, 10.0);
let q = rect(&mut s, 75.0, 15.0);
let holes = compound(&mut s, &[p, q]);
change(&mut s, holes, |n| n.appearance = red().into());
let inner = group(&mut s, &[b, holes]);
change(&mut s, inner, |n| n.opacity = 0.5);
let clipped = rect(&mut s, 110.0, 10.0);
let clip = rect(&mut s, 105.0, 5.0);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[a, inner, masked]);
select(&mut s, &[outer]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (2, 1, 1), "{r}");
assert_eq!(r["scope"], "selection");
assert_eq!(undo_steps(&s), steps + 1, "one undo step");
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Release All Containers");
assert_eq!(layer(&s, 0), [a, b, p, q, clip, clipped], "only paths are left, in their stacking order");
assert!([a, b, p, q, clip, clipped].iter().all(|id| plain(&s, *id)), "the clipping path is a plain path");
assert!(node(&s, outer).is_none() && node(&s, inner).is_none() && node(&s, holes).is_none() && node(&s, masked).is_none());
assert_eq!((node(&s, b).unwrap().opacity, node(&s, p).unwrap().opacity), (0.5, 0.5), "members keep their groups' opacity");
assert_eq!(*node(&s, q).unwrap().appearance, red(), "a compound path's paths take its paint");
assert_eq!(selected(&s), [a, b, p, q, clip, clipped], "what the selected group left is selected");
assert_eq!(r["ids"], json!([a.0, b.0, p.0, q.0, clip.0, clipped.0]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(layer(&s, 0), [outer]);
}
#[test]
fn release_all_counts_each_object_left_once() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let p = rect(&mut s, 100.0, 10.0);
let second = node(&s, p).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, p, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
let inner = group(&mut s, &[a, b, c, p]);
change(&mut s, inner, |n| n.set_clips(true));
let middle = group(&mut s, &[inner]);
let outer = group(&mut s, &[middle]);
let held = std::collections::HashSet::new();
for clips in [true, false] {
let mut d = (*s.doc().unwrap().doc).clone();
let n = d.node_arc(outer).unwrap().clone();
let mut run = super::Release {
kinds: super::Kinds { groups: true, clips, compounds: true },
named: false,
held: &held,
counts: [0; 3],
made: 0,
left: std::collections::HashMap::new(),
};
let mut out = vec![];
run.node(&mut d, n, false, &mut out).unwrap();
if clips {
assert_eq!(out.len(), 5);
assert_eq!(run.made, out.len(), "each path is counted once");
} else {
assert_eq!(out.len(), 1);
let children = out[0].children().unwrap();
assert_eq!(children.len(), 5);
assert_eq!(run.made, out.len() + children.len(), "the kept group and its paths are counted once");
}
}
}
#[test]
fn release_all_takes_only_the_kinds_asked_for() {
let mut s = session();
let p = rect(&mut s, 10.0, 10.0);
let q = rect(&mut s, 15.0, 15.0);
let holes = compound(&mut s, &[p, q]);
let clipped = rect(&mut s, 110.0, 10.0);
let e = rect(&mut s, 105.0, 5.0);
let f = rect(&mut s, 108.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let outer = group(&mut s, &[holes, masked]);
// Without groups, the group stays and what is inside it is still released, but for the
// clipping path of the clipping group that stays.
select(&mut s, &[outer]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(p), Some(outer));
assert!(d.node(holes).is_none() && d.node(clip).is_some() && d.node(masked).is_some());
assert_eq!(selected(&s), [outer]);
// Without compound paths, the groups go and the compound path stays.
let r = s.execute(C, &json!({"compoundPaths": false})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert_eq!(layer(&s, 0), [p, q, clip, clipped]);
assert!(matches!(node(&s, clip).unwrap().kind, NodeKind::Compound { .. }));
// Then only compound paths: the clipping path's paths, unpainted as it was.
select(&mut s, &[clip]);
let r = s.execute(C, &json!({"groups": false, "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
assert_eq!(layer(&s, 0), [p, q, e, f, clipped]);
}
#[test]
fn release_all_splits_paths_of_several_subpaths() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
change(&mut s, a, |n| {
if let NodeKind::Path { path, .. } = &mut n.kind {
path.subpaths.push(second);
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "{r}");
let left = layer(&s, 0);
assert_eq!(left.len(), 2);
assert_eq!(left[0], a, "the first subpath keeps the path's id");
assert!(left.iter().all(|id| plain(&s, *id)));
assert_eq!(selected(&s), left);
assert_eq!(node(&s, left[1]).unwrap().appearance, node(&s, a).unwrap().appearance, "each part keeps the path's paint");
}
#[test]
fn release_all_keeps_a_path_of_several_subpaths_with_live_corners_whole() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let plain_path = rect(&mut s, 80.0, 10.0);
let second = node(&s, b).unwrap().path_data().unwrap().subpaths[0].clone();
for id in [a, plain_path] {
let second = second.clone();
change(&mut s, id, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(second);
*live = None;
}
});
}
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
let base = path.clone();
*live = Some(Box::new(LiveShape::Path { base, radii: vec![4.0], kinds: vec![], radii_relative: false }));
}
});
s.edit("t", |d, _| Ok(d.remove_many(&[b])?)).unwrap();
select(&mut s, &[a, plain_path]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(counts(&r), (0, 0, 1), "only the plain path is split: {r}");
let kept = node(&s, a).unwrap();
assert!(matches!(kept.kind, NodeKind::Path { live: Some(_), ref path, .. } if path.subpaths.len() == 2), "Live Corners stay");
assert_eq!(layer(&s, 0).len(), 3);
}
#[test]
fn release_all_runs_on_the_document_while_nothing_is_selected() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let e = rect(&mut s, 100.0, 10.0);
let plain_group = group(&mut s, &[a]);
let locked = group(&mut s, &[b]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[c]);
change(&mut s, hidden, |n| n.visible = false);
// A second layer that clips its art by its first path.
let second = id_of(&s.execute("layer.new", &json!({})).unwrap());
let mask = rect(&mut s, 0.0, 100.0);
let art = rect(&mut s, 10.0, 110.0);
let art_group = group(&mut s, &[art]);
s.edit("t", |d, _| {
let layer = d.node_mut(second).unwrap();
layer.set_clips(true);
if let Some(NodeKind::Path { clipping, .. }) = layer.children_mut().unwrap().first_mut().map(|c| &mut std::sync::Arc::make_mut(c).kind) {
*clipping = true;
}
Ok(())
})
.unwrap();
select(&mut s, &[]);
assert!(s.execute(C, &json!({"scope": "selection"})).is_err(), "nothing selected");
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!(r["scope"], "document");
assert_eq!(counts(&r), (2, 1, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(layer(&s, 0), [a, locked, hidden, e], "locked and hidden groups stay whole");
assert!(node(&s, plain_group).is_none() && node(&s, art_group).is_none());
let d = &s.doc().unwrap().doc;
assert!(!d.node(second).unwrap().clips(), "the layer stays and stops clipping");
assert!(plain(&s, mask), "its clipping path is a plain path");
assert_eq!(layer(&s, 1), [mask, art]);
assert!(selected(&s).is_empty(), "nothing was selected");
// Asked for the document with a selection, the selection keeps what it held.
let g = group(&mut s, &[e]);
select(&mut s, &[g]);
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert_eq!(selected(&s), [e]);
}
#[test]
fn release_all_takes_named_locked_and_hidden_containers() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let locked = group(&mut s, &[a]);
change(&mut s, locked, |n| n.locked = true);
let hidden = group(&mut s, &[b]);
change(&mut s, hidden, |n| n.visible = false);
select(&mut s, &[locked, hidden]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "from the selection, they stay whole");
let r = s.execute(C, &json!({"ids": [locked.0, hidden.0]})).unwrap();
assert_eq!(r["scope"], "ids");
assert_eq!(counts(&r), (2, 0, 0), "{r}");
assert_eq!(undo_steps(&s), steps + 1);
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
assert!(na.locked && na.visible && !nb.visible && !nb.locked, "their objects become locked or hidden as they were");
assert!(selected(&s).is_empty(), "locked and hidden objects are not selected");
// On a locked artboard, a named group stays whole.
let c = rect(&mut s, 10.0, 200.0);
let on_board = group(&mut s, &[c]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [on_board.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, on_board).is_some());
// Nor does one inside a named layer.
let layer_id = s.doc().unwrap().doc.layers[0].id;
let r = s.execute(C, &json!({"ids": [layer_id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
}
#[test]
fn release_all_leaves_masked_groups_whole_and_changes_nothing_without_a_container() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let held = group(&mut s, &[a, b]);
let m = rect(&mut s, 0.0, 0.0);
s.execute("transparency.makeOpacityMask", &json!({"ids": [held.0, m.0]})).unwrap();
let masked = layer(&s, 0)[0];
assert!(node(&s, masked).unwrap().extras().mask.is_some());
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[masked, c]);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "no step when nothing is released");
assert_eq!(r["ids"], json!([masked.0, c.0]), "the selection stays");
assert_eq!(layer(&s, 0), [masked, c]);
// A compound shape is a group that stays whole too.
let e = rect(&mut s, 200.0, 10.0);
let f = rect(&mut s, 210.0, 15.0);
select(&mut s, &[e, f]);
s.execute("object.compoundShape.make", &json!({})).unwrap();
let shape = selected(&s)[0];
assert!(node(&s, shape).unwrap().is_compound_shape());
let steps = undo_steps(&s);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(node(&s, shape).unwrap().is_compound_shape());
}
#[test]
fn release_all_leaves_a_picked_clipping_path_of_a_clipping_group_that_stays() {
let mut s = session();
let clipped = rect(&mut s, 10.0, 10.0);
let e = rect(&mut s, 5.0, 5.0);
let f = rect(&mut s, 8.0, 8.0);
let clip = compound(&mut s, &[e, f]);
let masked = clip_group(&mut s, &[clipped, clip]);
let steps = undo_steps(&s);
for p in [json!({"ids": [clip.0]}), json!({"ids": [clip.0], "clipGroups": false})] {
let r = s.execute(C, &p).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps), "{p}");
}
select(&mut s, &[clip]);
let r = s.execute(C, &json!({})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(clip), Some(masked));
assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Compound { .. }));
}
#[test]
fn release_all_keeps_a_directly_named_descendant_of_a_live_object() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let inner = group(&mut s, &[a]);
let sources = group(&mut s, &[inner]);
change(&mut s, sources, |n| n.name = Some("Live Paint Sources".into()));
let live = group(&mut s, &[sources]);
change(&mut s, live, |n| n.name = Some("Live Paint Group".into()));
change(&mut s, sources, |n| n.visible = false);
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
let steps = undo_steps(&s);
for id in [sources, inner] {
let r = s.execute(C, &json!({"ids": [id.0]})).unwrap();
assert_eq!((counts(&r), undo_steps(&s)), ((0, 0, 0), steps));
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, live).unwrap()));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
#[test]
fn release_all_keeps_appearance_effects_and_directly_targeted_descendants() {
for item in [None, Some(0), Some(1)] {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 15.0, 15.0);
let inner = compound(&mut s, &[a, b]);
let c = rect(&mut s, 20.0, 20.0);
select(&mut s, &[inner, c]);
let applied = s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap();
assert_eq!(applied["grouped"], true);
let live = selected(&s)[0];
assert!(matches!(node(&s, live).unwrap().kind, NodeKind::Group { clip: false, .. }));
assert!(!node(&s, live).unwrap().is_compound_shape());
assert_eq!(node(&s, live).unwrap().appearance.effects[0].id, "pathfinder.add");
if let Some(item) = item {
change(&mut s, live, |n| {
let effects = n.appearance.effects.clone();
*n.appearance = red();
*n.appearance.effects_mut(Some(item)).unwrap() = effects;
});
}
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for (target, params) in [
(live, json!({})),
(live, json!({"scope": "document"})),
(live, json!({"ids": [live.0]})),
(inner, json!({})),
(inner, json!({"ids": [inner.0]})),
] {
select(&mut s, &[target]);
let r = s.execute(C, &params).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{item:?}: {params}: {r}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [target]);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(live));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(inner));
}
}
}
#[test]
fn release_all_keeps_a_layer_mask_over_locked_artboard_artwork() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let art = rect(&mut s, 10.0, 10.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert_eq!(layer(&s, 0), [mask, art, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_layer_mask_that_alone_overlaps_a_locked_artboard() {
for named in [false, true] {
let mut s = session();
let mask = rect(&mut s, 0.0, 0.0);
let outside = rect(&mut s, 500.0, 10.0);
let g = group(&mut s, &[outside]);
let layer_id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, layer_id, |n| n.set_clips(true));
change(&mut s, mask, |n| {
if let NodeKind::Path { clipping, .. } = &mut n.kind {
*clipping = true;
}
});
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let original_mask = s.doc().unwrap().doc.node_arc(mask).unwrap().clone();
let steps = undo_steps(&s);
let p = if named { json!({"ids": [layer_id.0]}) } else { json!({"scope": "document"}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{p}: {r}");
assert_eq!(undo_steps(&s), steps + 1);
assert!(node(&s, layer_id).unwrap().clips());
assert!(matches!(node(&s, mask).unwrap().kind, NodeKind::Path { clipping: true, .. }));
assert!(std::sync::Arc::ptr_eq(&original_mask, s.doc().unwrap().doc.node_arc(mask).unwrap()));
assert_eq!(layer(&s, 0), [mask, outside]);
assert!(node(&s, g).is_none());
}
}
#[test]
fn release_all_keeps_a_clipping_group_whose_clipped_art_overlaps_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(g));
assert!(node(&s, g).unwrap().clips());
}
#[test]
fn release_all_keeps_a_named_group_in_a_clipping_group_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let other = rect(&mut s, 40.0, 10.0);
let inner = group(&mut s, &[art, other]);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [inner.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(inner));
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_takes_apart_a_named_hidden_clipping_group_with_visible_art() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
change(&mut s, g, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [g.0]})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, art).unwrap().visible);
}
#[test]
fn release_all_takes_apart_a_clipping_group_in_a_named_hidden_group() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
let other = rect(&mut s, 40.0, 10.0);
let outer = group(&mut s, &[g, other]);
change(&mut s, outer, |n| n.visible = false);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"ids": [outer.0]})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_ignores_hidden_clipped_art_over_a_locked_artboard() {
let mut s = session();
let hidden = rect(&mut s, 10.0, 10.0);
let shown = rect(&mut s, 600.0, 10.0);
let inner = group(&mut s, &[hidden, shown]);
change(&mut s, hidden, |n| n.visible = false);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 1, 0), "{r}");
assert!(node(&s, g).is_none());
assert!(!node(&s, hidden).unwrap().visible);
}
#[test]
fn release_all_keeps_a_clipping_group_whose_group_stroke_reaches_a_locked_artboard() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
change(&mut s, inner, |n| n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 500.0).into());
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(g));
}
#[test]
fn release_all_ungroups_off_artboard_groups_in_a_kept_clipping_group() {
let mut s = session();
let a = rect(&mut s, 600.0, 10.0);
let b = rect(&mut s, 640.0, 10.0);
let inner = group(&mut s, &[a, b]);
let on = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[inner, on, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document", "clipGroups": false})).unwrap();
assert_eq!(counts(&r), (1, 0, 0), "{r}");
assert!(node(&s, inner).is_none());
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
}
#[test]
fn release_all_takes_apart_pattern_editing_art_over_a_locked_artboard() {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let mask = rect(&mut s, 500.0, 10.0);
let g = clip_group(&mut s, &[art, mask]);
select(&mut s, &[]);
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
let layer = d.layers[0].id;
d.pattern_edit = Some(vectorcraft_doc::PatternEdit { pattern: "Checks".into(), layer, original: None });
Ok(())
})
.unwrap();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 1, 0), "{r}");
assert!(node(&s, g).is_none());
}
#[test]
fn release_all_keeps_a_group_with_its_own_fill_or_stroke() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[a, b]);
change(&mut s, g, |n| n.appearance = red().into());
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{r}");
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g));
assert_eq!(*node(&s, g).unwrap().appearance, red());
}
#[test]
fn release_all_reuses_unchanged_siblings_when_rebuilding_a_layer() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let g = group(&mut s, &[b]);
let original = s.doc().unwrap().doc.node_arc(a).unwrap().clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
assert!(node(&s, g).is_none());
assert!(std::sync::Arc::ptr_eq(&original, s.doc().unwrap().doc.node_arc(a).unwrap()));
}
#[test]
fn release_all_keeps_selection_details_for_untouched_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let c = rect(&mut s, 70.0, 10.0);
let g = group(&mut s, &[c]);
s.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap();
s.select(|_, sel| {
sel.set([a, b, g]);
sel.anchors.insert(a, [(0, 0), (0, 2)].into_iter().collect());
sel.anchors.insert(b, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(b, [(0, 0)].into_iter().collect());
sel.guides.push(guide);
sel.key_anchor = Some((a, (0, 0)));
})
.unwrap();
let before = s.doc().unwrap().selection.clone();
let r = s.execute(C, &json!({"scope": "document"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0));
let after = &s.doc().unwrap().selection;
assert_eq!(after.objects, [a, b, c]);
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
assert_eq!(after.key_anchor, before.key_anchor);
assert!(!after.objects.contains(&g));
change(&mut s, c, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
s.select(|_, sel| {
sel.anchors.insert(c, [(0, 0), (0, 1)].into_iter().collect());
sel.segments.insert(c, [(0, 0)].into_iter().collect());
})
.unwrap();
let r = s.execute(C, &json!({"ids": [c.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 1));
let after = &s.doc().unwrap().selection;
assert_eq!(after.anchors, before.anchors);
assert_eq!(after.segments, before.segments);
assert_eq!(after.guides, before.guides);
}
#[test]
fn release_all_keeps_a_directly_named_blend_key() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let b = rect(&mut s, 40.0, 10.0);
let key = group(&mut s, &[a, b]);
let c = rect(&mut s, 100.0, 10.0);
select(&mut s, &[key, c]);
let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(key), Some(blend));
let before = s.doc().unwrap().doc.clone();
let selection = selected(&s);
let steps = undo_steps(&s);
let r = s.execute(C, &json!({"ids": [key.0]})).unwrap();
assert_eq!(counts(&r), (0, 0, 0));
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn release_all_keeps_a_direct_target_inside_a_compound_clipping_mask() {
for clipping_layer in [false, true] {
let mut s = session();
let art = rect(&mut s, 10.0, 10.0);
let a = rect(&mut s, 5.0, 5.0);
let b = rect(&mut s, 8.0, 8.0);
change(&mut s, a, |n| {
if let NodeKind::Path { path, live, .. } = &mut n.kind {
path.subpaths.push(path.subpaths[0].clone());
*live = None;
}
});
let mask = compound(&mut s, &[a, b]);
let container = if clipping_layer {
let id = s.doc().unwrap().doc.layers[0].id;
change(&mut s, id, |n| {
n.children_mut().unwrap().swap(0, 1);
n.set_clips(true);
});
id
} else {
clip_group(&mut s, &[art, mask])
};
assert_eq!(node(&s, container).unwrap().children().unwrap()[0].id, mask);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for named in [false, true] {
select(&mut s, &[a]);
let p = if named { json!({"ids": [a.0]}) } else { json!({"clipGroups": false}) };
let r = s.execute(C, &p).unwrap();
assert_eq!(counts(&r), (0, 0, 0), "{p}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [a]);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_null_options_without_editing_artwork() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
for selection in [vec![], vec![g]] {
select(&mut s, &selection);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for key in ["scope", "groups", "clipGroups", "compoundPaths"] {
let mut p = json!({});
p[key] = Value::Null;
let error = s.execute(C, &p).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, .. } if cmd == C), "{p}: {error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), selection);
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn release_all_rejects_duplicate_ids_before_traversal() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
let b = rect(&mut s, 50.0, 10.0);
select(&mut s, &[g]);
let before = s.doc().unwrap().doc.clone();
let steps = undo_steps(&s);
for ids in [vec![g.0, g.0], vec![b.0, b.0], vec![g.0, a.0, a.0]] {
let error = s.execute(C, &json!({"ids": ids})).unwrap_err();
assert!(matches!(error, crate::EngineError::BadParams { ref cmd, ref msg } if cmd == C && msg.contains("duplicate")), "{error}");
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));
assert_eq!(selected(&s), [g]);
assert_eq!(undo_steps(&s), steps);
}
}
#[test]
fn release_all_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0);
let g = group(&mut s, &[a]);
select(&mut s, &[g]);
let steps = undo_steps(&s);
for bad in [
json!({"groups": false, "clipGroups": false, "compoundPaths": false}),
json!({"groups": "yes"}),
json!({"compoundPaths": 1}),
json!({"scope": "layer"}),
json!({"scope": "document", "ids": [g.0]}),
json!({"ids": [999_999]}),
] {
assert!(s.execute(C, &bad).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), steps);
assert!(node(&s, g).is_some());
}
+7 -4
View File
@@ -4,15 +4,17 @@
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
//! Object › Plug-ins › Color Effects, are the UI's.
//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks
//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, Apply
//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and
//! Randomize Fill Colors ([`random_fill`]) gives each filled path its own color at random. Its
//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's.
pub mod legend;
mod nearest;
mod print_fixes;
mod random_fill;
pub mod screen_marks;
#[cfg(test)]
mod tests;
@@ -106,6 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
]
.into_iter()
.chain(legend::specs())
.chain(screen_marks::specs())
.collect()
}
@@ -0,0 +1,515 @@
//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects ›
//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an
//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot
//! inks (each name in its own ink) and give the file name with the date and time. The marks are
//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the
//! stack, so they print and export with the rest. Running it again replaces that artboard's marks,
//! in one undo step, and makes none when the marks would come out the same.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param};
use crate::{DocState, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.color.screenMarks",
"Create Screen Print Marks",
["Object", "Plug-ins", "Color Effects"],
None,
"{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}",
has_doc,
screen_marks
)]
}
/// The command.
pub const COMMAND: &str = "addon.color.screenMarks";
/// Where a target can go, in the order the command draws them.
pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"];
/// The targets drawn when `positions` is left out.
pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"];
/// The name of the layer the marks go on, and of each artboard's group.
pub const LAYER_NAME: &str = "Screen Print Marks";
/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id).
pub const KEY: &str = "vc-screen-print-marks";
/// Most spot inks one line names.
const MAX_INKS: usize = 256;
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
match p.get(key) {
None => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && range.contains(n))
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
}
}
/// One of `options` for `key`, else `default`.
fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> {
match text_param(p, key, COMMAND)? {
None => Ok(default),
Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))),
}
}
/// The target positions `p` asks for, in [`POSITIONS`] order.
fn positions(p: &Value) -> Result<Vec<&'static str>> {
let asked: Vec<&str> = match p.get("positions") {
None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()),
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")),
};
for (i, w) in asked.iter().enumerate() {
if !POSITIONS.contains(w) {
return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", "))));
}
if asked[..i].contains(w) {
return Err(bad(COMMAND, format!("`positions` names `{w}` twice")));
}
}
Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect())
}
/// The paint of ink `name`: [Registration], or a spot swatch linked to it.
fn ink_paint(doc: &Document, name: &str) -> Result<Paint> {
if name == REGISTRATION {
return Ok(Paint::registration());
}
let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?;
if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() {
return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch")));
}
super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e))
}
/// The document's spot inks in panel order, each with the paint that links to it: spot color
/// swatches that are not tints, [Registration] left out.
fn spot_inks(doc: &Document) -> Vec<(String, Paint)> {
doc.swatches_iter()
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
.map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())))
.collect()
}
/// The index of the view's active artboard: when the document no longer has it, the one the
/// document opened on, else the first.
fn active_artboard(st: &DocState) -> Option<usize> {
let d = &st.doc;
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
}
/// The settings every artboard's marks are drawn with.
struct Marks {
positions: Vec<&'static str>,
size: f64,
weight: f64,
inset: f64,
ink: Paint,
/// The lines of type, top to bottom: each a list of (text, fill) runs.
lines: Vec<Vec<(String, Paint)>>,
style: CharStyle,
system_layout: bool,
top: bool,
left: bool,
}
impl Marks {
/// The center of the target at `position` on artboard `r`.
fn center(&self, r: Rect, position: &str) -> Point {
let near = self.inset + self.size / 2.0;
let x = if position.ends_with("Left") || position == "left" {
r.x0 + near
} else if position.ends_with("Right") || position == "right" {
r.x1 - near
} else {
r.center().x
};
let y = if position.starts_with("top") {
r.y0 + near
} else if position.starts_with("bottom") {
r.y1 - near
} else {
r.center().y
};
Point::new(x, y)
}
/// The target at `c`: a circle half the target's width and a cross the target's width, stroked.
fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node {
let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight);
let (half, ring) = (self.size / 2.0, self.size / 4.0);
let paths = [
shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)),
shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)),
shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)),
];
let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect();
let mut g = Node::group(alloc(), children);
g.name = Some("Registration Target".into());
g
}
/// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or
/// its bottom corner there when `from_bottom`, with its box.
fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) {
let runs: Vec<TextRun> = runs
.iter()
.map(|(text, fill)| {
let mut style = self.style.clone();
style.fill = fill.clone();
style.stroke = Paint::None;
TextRun::new(text.clone(), style)
})
.collect();
let mut t = TextObject::point(Point::ZERO, "", self.style.clone());
t.runs = runs;
t.para = super::super::super::create::new_type_para();
t.system_layout = self.system_layout;
super::super::super::typecmd::refresh_bounds(&mut t);
let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2));
let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 };
let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 };
t.xf = Affine::translate((dx, dy));
(t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy))
}
/// The lines placed in a column from `y`, at `x`: down from `y` at the top, up
/// from it at the bottom. Each with its box.
fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> {
let gap = self.style.size * 0.25;
let mut placed = Vec::with_capacity(self.lines.len());
if self.top {
for runs in &self.lines {
let (t, b) = self.line(runs, Point::new(x, y), false);
y += b.height() + gap;
placed.push((t, b));
}
} else {
for runs in self.lines.iter().rev() {
let (t, b) = self.line(runs, Point::new(x, y), true);
y -= b.height() + gap;
placed.insert(0, (t, b));
}
}
placed
}
/// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last).
fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node {
let mut children: Vec<Arc<Node>> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect();
if !self.lines.is_empty() {
// The lines start past a target in the corner they start from.
let corner = match (self.top, self.left) {
(true, true) => "topLeft",
(true, false) => "topRight",
(false, true) => "bottomLeft",
(false, false) => "bottomRight",
};
let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 };
let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip };
let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) };
let mut placed = self.column(x, edge + sign * self.inset);
// Lines that would cross the center target on their side move in past it, unless they
// would then cross another target or leave the artboard.
let side = if self.top { "top" } else { "bottom" };
// A target's paint: its two bars and the box of its ring, each with half the stroke weight.
let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0);
let crosses = |placed: &[(TextObject, Rect)], w: &str| {
let c = self.center(r, w);
let paint = [
Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2),
Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2),
Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring),
];
placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0))
};
if self.positions.contains(&side) && crosses(&placed, side) {
let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25));
if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) {
placed = moved;
}
}
children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t))))));
}
let mut g = Node::group(alloc(), children);
g.name = Some(LAYER_NAME.into());
g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string())));
g
}
}
/// The marks layer: the top-level layer whose data says so.
fn marks_layer(doc: &Document) -> Option<&Arc<Node>> {
doc.layers.iter().find(|l| tag(l) == Some("layer"))
}
/// What `n`'s data holds under [`KEY`].
fn tag(n: &Node) -> Option<&str> {
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
}
/// The id of the artboard marks group `n` belongs to, from its data.
fn owner(n: &Node) -> Option<u32> {
tag(n)?.parse().ok()
}
/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to.
pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap<NodeId, u32> {
marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect()
}
/// The id of the marks layer of `d`, when it has one.
pub(crate) fn layer_id(d: &Document) -> Option<NodeId> {
marks_layer(d).map(|l| l.id)
}
/// Is `n` the marks group of one of the artboards with ids `boards`?
pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool {
owner(n).is_some_and(|o| boards.contains(&o))
}
/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order,
/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the
/// marks layer is locked or hidden, only with `locked_and_hidden`.
pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> {
let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden));
let kids = layer.and_then(|l| l.children()).into_iter().flatten();
kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect()
}
/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data
/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call
/// it on each copy they make. → whether `n` was such a group.
pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool {
if owner(n) != Some(from) {
return false;
}
let (from, to) = (from.to_string(), to.to_string());
n.edit_attrs(|a| {
for (k, v) in a.data.iter_mut() {
if k == KEY && *v == from {
v.clone_from(&to);
}
}
});
true
}
/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened
/// again can give a new artboard one of those ids, and its marks are drawn afresh.
pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet<u32>) {
// Groups moved off the marks layer keep their tag and count too.
let mut groups: Vec<NodeId> = vec![];
for l in &d.layers {
l.walk(&mut |n: &Node| {
if owner(n).is_some_and(|o| gone.contains(&o)) {
groups.push(n.id);
}
});
}
for id in groups {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY));
}
}
}
/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard,
/// the marks layer, when the document has none.
pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) {
if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) {
return;
}
if let Some(l) = d.node_mut(layer) {
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
}
}
/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way.
fn without_ids(n: &Node) -> Node {
let mut n = n.clone();
n.id = NodeId(0);
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(without_ids(c));
}
}
n
}
fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = COMMAND;
let positions = positions(p)?;
let size = number(p, "size", 36.0, 4.0..=1000.0)?;
let weight = number(p, "weight", 1.0, 0.1..=20.0)?;
let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?;
let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?;
let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top";
let left = choice(p, "textAlign", ["left", "right"], "left")? == "left";
let want_inks = switch_or(p, "inks", false, C)?;
let want_info = switch_or(p, "info", false, C)?;
let all = switch_or(p, "allArtboards", false, C)?;
let given_time = date_param(p, "time", C)?;
let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string();
// Defaults are for values left out; only `time` takes null (no date).
if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) {
return Err(bad(C, format!("`{key}` must not be null: leave it out for the default")));
}
let artboard = index_opt(p, "artboard", C)?;
if all && artboard.is_some() {
return Err(bad(C, "give `artboard` or `allArtboards`, not both"));
}
// The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one;
// recorded actions leave it out and use the active artboard when played.
let recorded = index_opt(p, "activeArtboard", C)?;
let artboard = match artboard {
None if !all => {
let i = match recorded {
Some(i) => Some(i),
None => active_artboard(s.doc()?),
};
if let Some(i) = i {
s.note_journal("activeArtboard", json!(i));
}
i
}
given => given,
};
let st = s.doc()?;
let doc = &st.doc;
if doc.artboards.is_empty() {
return Err(bad(C, "the document has no artboards"));
}
let boards: Vec<(Rect, u32)> = if all {
doc.artboards.iter().map(|a| (a.rect, a.id)).collect()
} else {
let i = artboard.unwrap_or(0);
let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?;
vec![(a.rect, a.id)]
};
let ink = ink_paint(doc, &ink_name)?;
let inks = if want_inks { spot_inks(doc) } else { vec![] };
if inks.len() > MAX_INKS {
return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks")));
}
let file = st
.path
.as_deref()
.and_then(|path| std::path::Path::new(path).file_name())
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_else(|| doc.title.clone());
let system_layout = doc.setup.system_layout;
if positions.is_empty() && inks.is_empty() && !want_info {
let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" };
return Err(bad(C, format!("nothing to draw: {why}")));
}
let mut lines: Vec<Vec<(String, Paint)>> = vec![];
if !inks.is_empty() {
let last = inks.len() - 1;
lines.push(
inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(),
);
}
if want_info {
let date = clock_date(s, "time", given_time).map(|t| {
let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t);
format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC")
});
let text = match date {
Some(date) => format!("{file} {date}"),
None => file,
};
lines.push(vec![(text, ink.clone())]);
}
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left };
let names: Vec<String> = inks.into_iter().map(|(name, _)| name).collect();
// The marks as they would come out, to tell whether anything changes.
let st = s.doc()?;
let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default()));
let drawn: Vec<Node> = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect();
// Only the stroked targets reach past their paths, by half the target weight. The lines of type
// have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well.
let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD);
let beyond = |n: &Node| match &n.kind {
NodeKind::Text(t) => {
n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0))
}
_ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)),
};
if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) {
return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)")));
}
// Each existing group under the artboard it belongs to, worked out once.
let mut owned: std::collections::HashMap<u32, Vec<&Arc<Node>>> = std::collections::HashMap::new();
for k in layer.iter().flat_map(|(_, kids)| kids) {
if let Some(board) = owner(k) {
owned.entry(board).or_default().push(k);
}
}
if let Some((layer, _)) = &layer {
let same = boards
.iter()
.zip(&drawn)
.all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new)));
if same {
let ids: Vec<u64> = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect();
return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names }));
}
}
let owned: std::collections::HashMap<u32, Vec<NodeId>> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect();
let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| {
let layer = match marks_layer(d).map(|l| l.id) {
Some(id) => id,
None => {
let id = d.alloc_id();
let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8);
let mut l = Node::layer(id, LAYER_NAME, color);
l.locked = true;
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
d.insert(None, 0, l)?;
id
}
};
let mut ids = Vec::with_capacity(boards.len());
for (r, board) in &boards {
let kids = d.children(Some(layer)).cloned().unwrap_or_default();
let old: Vec<NodeId> = owned.get(board).cloned().unwrap_or_default();
let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX);
// Only what the selection holds of the marks leaves it; the rest of the selection stays as it is.
let mut held = vec![];
for k in kids.iter().filter(|k| old.contains(&k.id)) {
k.walk(&mut |n: &Node| {
if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) {
held.push(n.id);
}
});
}
if !held.is_empty() {
sel.remove_all(held);
}
d.remove_many(&old)?;
let g = marks.group(*r, *board, &mut || d.alloc_id());
ids.push(g.id.0);
d.insert(Some(layer), at, g)?;
}
Ok((layer, ids))
})?;
Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names }))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,935 @@
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Node, NodeId, NodeKind};
use vectorcraft_geom::Rect;
use super::{COMMAND, LAYER_NAME};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn run(s: &mut Session, p: Value) -> Value {
s.execute(COMMAND, &p).unwrap()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn node(s: &Session, id: u64) -> Node {
s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone()
}
/// The targets of group `g`: each one's three paths.
fn targets(g: &Node) -> Vec<Vec<Node>> {
g.children()
.unwrap()
.iter()
.filter(|n| n.name.as_deref() == Some("Registration Target"))
.map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect())
.collect()
}
/// The type lines of group `g`, top to bottom as stored.
fn lines(g: &Node) -> Vec<vectorcraft_doc::TextObject> {
g.children()
.unwrap()
.iter()
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => Some((**t).clone()),
_ => None,
})
.collect()
}
fn bounds(n: &Node) -> Rect {
n.geometric_bounds().unwrap()
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
/// The swatch solid paint `p` links to.
fn swatch_of(p: &Paint) -> Option<String> {
match p {
Paint::Solid { swatch, .. } => swatch.clone(),
_ => None,
}
}
#[test]
fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() {
let mut s = session();
let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.all", &json!({})).unwrap();
let undo = undo_len(&s);
let r = run(&mut s, json!({}));
assert_eq!(r["changed"], json!(true));
assert_eq!(undo_len(&s), undo + 1, "one undo step");
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept");
let doc = &s.doc().unwrap().doc;
let layer = &doc.layers[0];
assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack");
assert_eq!(layer.name.as_deref(), Some(LAYER_NAME));
assert!(layer.locked && layer.visible, "the marks layer is locked");
assert_eq!(doc.layers.len(), 2);
let ids = r["ids"].as_array().unwrap();
assert_eq!(ids.len(), 1, "one group for the active artboard");
let g = node(&s, ids[0].as_u64().unwrap());
assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str()));
let t = targets(&g);
assert_eq!(t.len(), 4, "top, bottom, left and right by default");
assert!(lines(&g).is_empty(), "no type lines unless asked for");
for paths in &t {
assert_eq!(paths.len(), 3, "a ring and two cross lines");
for p in paths {
assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]");
assert!(p.appearance.fill_paint().is_none());
assert!(close(p.appearance.stroke_width(), 1.0));
}
}
// The top target: its 36 pt box 18 pt in from the top edge, centered across.
let top = &t[0];
let ring = bounds(&top[0]);
assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}");
let across = bounds(&top[1]);
assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}");
let down = bounds(&top[2]);
assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}");
// Left, right and bottom.
let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect();
assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]);
assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]);
assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks");
}
#[test]
fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"});
let r = run(&mut s, p);
let g = node(&s, r["ids"][0].as_u64().unwrap());
let t = targets(&g);
assert_eq!(t.len(), 2);
// Drawn in POSITIONS order: top left first. A negative inset puts the targets outside.
let tl = bounds(&t[0][0]).center();
let br = bounds(&t[1][0]).center();
assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}");
assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}");
assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width");
assert!(close(bounds(&t[0][1]).width(), 20.0));
for p in t.iter().flatten() {
assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch");
assert!(close(p.appearance.stroke_width(), 0.5));
}
}
#[test]
fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() {
let mut s = session();
let first = run(&mut s, json!({"size": 30}));
let layer = first["layer"].clone();
let undo = undo_len(&s);
let again = run(&mut s, json!({"size": 30}));
assert_eq!(again["changed"], json!(false));
assert_eq!(again["ids"], first["ids"], "the same group stays");
assert_eq!(undo_len(&s), undo, "nothing changed: no undo step");
let r = run(&mut s, json!({"size": 40, "positions": ["top"]}));
assert_eq!(r["changed"], json!(true));
assert_eq!(r["layer"], layer, "the same layer is reused");
assert_eq!(undo_len(&s), undo + 1);
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.layers.len(), 2, "no second marks layer");
let kids = doc.layers[0].children().unwrap();
assert_eq!(kids.len(), 1, "the earlier marks are replaced");
let t = targets(&kids[0]);
assert_eq!(t.len(), 1);
assert!(close(bounds(&t[0][1]).width(), 40.0));
assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone");
}
#[test]
fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() {
let mut s = session();
let p = json!({"positions": ["topLeft"]});
let first = run(&mut s, p.clone());
let before = node(&s, first["ids"][0].as_u64().unwrap());
s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap();
let undo = undo_len(&s);
let again = run(&mut s, p);
assert_eq!(again["changed"], json!(false));
assert_eq!(again["ids"], first["ids"], "the same group stays");
assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged");
assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize");
}
#[test]
fn replacing_the_marks_keeps_a_selected_slice_selected() {
let mut s = session();
run(&mut s, json!({}));
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
s.execute("object.slice.make", &json!({})).unwrap();
s.execute("select.object.slices", &json!({})).unwrap();
let before = s.doc().unwrap().selection.clone();
assert!(!before.slices.is_empty());
let r = run(&mut s, json!({"size": 50}));
assert_eq!(r["changed"], json!(true));
assert!(s.doc().unwrap().selection == before, "the selection is kept as it was");
}
#[test]
fn marks_past_the_canvas_edge_are_refused() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap();
let before = s.doc().unwrap().doc.clone();
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string();
assert!(err.contains("edge of the canvas"), "{err}");
assert!(s.doc().unwrap().doc == before);
run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
}
#[test]
fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() {
let mut s = session();
// The artboard ends 10 pt inside the canvas edge.
s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap();
let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20});
let r = run(&mut s, p);
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
}
#[test]
fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() {
let mut s = session();
// The artboard ends at the canvas edge.
s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap();
// The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that.
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15}));
assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
// 5 pt inside the edge, the stroke reaches 5 pt past it.
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string();
assert!(err.contains("edge of the canvas"), "{err}");
}
#[test]
fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap();
let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]}));
assert_eq!(r["ids"].as_array().unwrap().len(), 2);
let second = node(&s, r["ids"][1].as_u64().unwrap());
let c = bounds(&targets(&second)[0][0]).center();
assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}");
let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]}));
assert_eq!(only["ids"].as_array().unwrap().len(), 1);
let doc = &s.doc().unwrap().doc;
let kids = doc.layers[0].children().unwrap();
assert_eq!(kids.len(), 2, "the first artboard's marks stay");
assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap()));
let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center();
assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}");
}
#[test]
fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap();
// A tint swatch marked spot, as a file can hold one, is still a tint of its ink.
let st = s.doc_mut().unwrap();
let mut tints = 0;
for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) {
w.spot = true;
tints += 1;
}
assert_eq!(tints, 1);
let title = s.doc().unwrap().doc.title.clone();
// 2026-03-04 05:06 UTC.
let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760}));
assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out");
let g = node(&s, r["ids"][0].as_u64().unwrap());
assert!(targets(&g).is_empty());
let l = lines(&g);
assert_eq!(l.len(), 2);
let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect();
assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]);
assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC"));
assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate");
assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0)));
// At the bottom left by default: the file line is the lower one, both 18 pt in.
let doc = &s.doc().unwrap().doc;
let kids = g.children().unwrap();
let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect();
assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line");
assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}");
// No date without a time.
let r = run(&mut s, json!({"positions": [], "info": true, "time": null}));
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title);
}
#[test]
fn lines_at_the_top_right_start_past_a_corner_target() {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12});
let r = run(&mut s, p);
let g = node(&s, r["ids"][0].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
let target = bounds(&targets(&g)[0][1]);
// 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size).
assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}");
assert!(text.x1 < target.x0, "the line clears the corner target");
assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}");
assert!(close(lines(&g)[0].runs[0].style.size, 12.0));
}
#[test]
fn lines_move_up_past_a_bottom_center_target_they_would_cross() {
let mut s = session();
let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72});
let r = run(&mut s, p);
let g = node(&s, r["ids"][0].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}");
assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}");
}
#[test]
fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() {
let mut s = session();
s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap();
let p = json!({"positions": [], "info": true, "time": 1772600760});
let original = run(&mut s, p.clone());
let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap()));
let mut with_target = p;
with_target["positions"] = json!(["bottom"]);
let r = run(&mut s, with_target);
let g = node(&s, r["ids"][0].as_u64().unwrap());
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap();
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}");
assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}");
assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard");
}
#[test]
fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap();
let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24});
let r = run(&mut s, p);
let g = node(&s, r["ids"][0].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}");
}
#[test]
fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() {
let mut s = session();
run(&mut s, json!({}));
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks");
let copy = run(&mut s, json!({"artboard": 1, "size": 30}));
assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy");
let source = run(&mut s, json!({}));
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
assert_eq!(kids(&s), 2);
assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay");
}
#[test]
fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() {
let mut s = session();
let r = run(&mut s, json!({}));
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::<usize>();
let before = kids(&s);
run(&mut s, json!({"artboard": 1, "size": 30}));
assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy");
let source = run(&mut s, json!({}));
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
}
#[test]
fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() {
let mut s = session();
let r = run(&mut s, json!({}));
let layer = NodeId(r["layer"].as_u64().unwrap());
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked");
run(&mut s, json!({"artboard": 1, "size": 30}));
assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy");
}
#[test]
fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() {
let mut s = session();
let r = run(&mut s, json!({}));
let layer = NodeId(r["layer"].as_u64().unwrap());
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None;
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked");
}
#[test]
fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() {
let mut s = session();
run(&mut s, json!({}));
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({}));
let layer = NodeId(r["layer"].as_u64().unwrap());
let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
s.execute("edit.paste", &json!({})).unwrap();
let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer");
assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty");
}
#[test]
fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() {
for props in [json!({}), json!({"visible": false}), json!({"locked": true})] {
let mut s = session();
run(&mut s, json!({}));
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone();
let mut set = props.clone();
set["id"] = plain.clone();
s.execute("layer.setProps", &set).unwrap();
let plain = NodeId(plain.as_u64().unwrap());
s.execute("edit.paste", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.artboards.len(), 2, "{props}");
assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}");
let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect();
assert_eq!(made.len(), 1, "a marks layer is made: {props}");
assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}");
let made = made[0].id.0;
let r = run(&mut s, json!({"artboard": 1, "size": 30}));
assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}");
}
}
#[test]
fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() {
let mut s = session();
let r = run(&mut s, json!({}));
s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap();
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
for paste in 1..=2 {
s.execute("edit.paste", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let marks = super::layer_id(doc).expect("a marks layer is made");
let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}");
for l in named {
let items = l.children().unwrap().len();
assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks);
}
let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap();
assert_eq!(ordinary.children().unwrap().len(), paste, "the ordinary layer holds one rectangle per paste: paste {paste}");
assert!(
ordinary.children().unwrap().iter().all(|k| k.children().is_none()),
"only the rectangle goes into the ordinary layer: paste {paste}"
);
}
}
#[test]
fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() {
let mut s = session();
run(&mut s, json!({}));
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
for paste in 1..=2 {
s.execute("edit.paste", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let marks = super::layer_id(doc).expect("a marks layer is made");
assert_ne!(marks, ordinary);
let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::<Vec<_>>();
assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}");
assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}");
}
}
#[test]
fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() {
let mut s = session();
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}");
let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true});
s.execute("artboard.move", &p).unwrap();
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
assert_eq!(kids(&s), 2, "the copy carries a copy of the marks");
run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30}));
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
}
#[test]
fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() {
let mut s = session();
run(&mut s, json!({}));
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
let other = s.doc().unwrap().doc.layers[1].id.0;
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap();
let before = s.doc().unwrap().doc.clone();
let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string();
assert!(err.contains("locked or hidden"), "{err}");
assert!(s.doc().unwrap().doc == before, "nothing is pasted");
}
#[test]
fn marks_pasted_after_their_layer_was_deleted_are_found_again() {
let mut s = session();
let r = run(&mut s, json!({}));
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
run(&mut s, json!({"artboard": 1, "size": 30}));
let doc = &s.doc().unwrap().doc;
let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
assert_eq!(layers.len(), 1, "one marks layer");
assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy");
}
#[test]
fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
let g = node(&s, r["ids"][0].as_u64().unwrap());
let b = bounds(&g);
assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}");
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out");
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out");
let again = run(&mut s, json!({"positions": ["right"], "inset": -200}));
assert_eq!(again["changed"], json!(false));
}
#[test]
fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks");
let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30}));
assert_eq!(copy["changed"], json!(true));
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks");
}
#[test]
fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let p = json!({"positions": ["right"], "inset": -200});
run(&mut s, p.clone());
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks");
run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30}));
assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks");
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
}
/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an
/// Alt-drag for `artboard.move`, and the artboards' art for the others.
fn copy_params(command: &str, target: Value) -> Value {
let mut p = match command {
"artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}),
_ => json!({"art": true, "lockedAndHidden": true}),
};
if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) {
p.extend(t.clone());
}
p
}
#[test]
fn overlapping_artboard_copies_keep_one_marks_group_per_owner() {
for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] {
let mut s = session();
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]}));
let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
let before = s.doc().unwrap().doc.clone();
let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())];
let p = copy_params(command, json!({"indices": [0, 1]}));
s.execute(command, &p).unwrap();
if command == "artboard.copy" {
s.execute("edit.paste", &json!({})).unwrap();
}
let d = &s.doc().unwrap().doc;
let groups = d.layers[0].children().unwrap();
assert_eq!(groups.len(), 4, "{command}");
for (source, original) in originals.iter().enumerate() {
assert!(d.node(original.id).unwrap() == original, "{command}");
let copied_board = &d.artboards[source + 2];
let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
assert_eq!(copies.len(), 1, "{command}: owner {source}");
let offset = copied_board.rect.origin() - d.artboards[source].rect.origin();
assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}");
}
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks");
}
}
#[test]
fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() {
for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
let original = node(&s, r["ids"][0].as_u64().unwrap());
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
assert!(bounds(&original).y1 < 0.0);
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
let before = s.doc().unwrap().doc.clone();
let p = copy_params(command, json!({"index": 0}));
let reply = s.execute(command, &p).unwrap();
if command == "artboard.cut" {
assert_eq!(reply["copied"], json!(1));
assert!(s.doc().unwrap().doc.node(original.id).is_none());
}
if matches!(command, "artboard.copy" | "artboard.cut") {
s.execute("edit.paste", &json!({})).unwrap();
}
let d = &s.doc().unwrap().doc;
let copied_board = d.artboards.last().unwrap();
let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
assert_eq!(copies.len(), 1, "{command}");
assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged");
let offset = copied_board.rect.origin() - before.artboards[0].rect.origin();
assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}");
s.execute("edit.undo", &json!({})).unwrap();
if command == "artboard.cut" {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(s.doc().unwrap().doc == before, "{command}");
}
}
#[test]
fn moving_an_artboard_uses_marks_ownership_instead_of_containment() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
let own = node(&s, outside["ids"][0].as_u64().unwrap());
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
assert!(bounds(&own).y1 < 0.0);
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
let before = s.doc().unwrap().doc.clone();
for (move_art, all) in [(false, true), (true, false)] {
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap();
assert!(node(&s, own.id.0) == own);
assert!(node(&s, foreign.id.0) == foreign);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before);
}
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
let start = bounds(&own);
let moved = bounds(&node(&s, own.id.0));
let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0);
assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard");
let board = s.doc().unwrap().doc.artboards[0].rect;
assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved");
assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard");
assert!(node(&s, foreign.id.0) == foreign);
assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own));
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before);
}
#[test]
fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let p = json!({"positions": ["right"], "inset": -200});
run(&mut s, p.clone());
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap();
assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden");
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard");
run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30}));
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
}
#[test]
fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
let other = s.doc().unwrap().doc.layers[1].id.0;
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len();
let before = kids(&s);
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group");
}
#[test]
fn marks_of_a_deleted_artboard_are_copied_like_other_art() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
run(&mut s, json!({"positions": ["right"], "inset": -200}));
s.execute("artboard.delete", &json!({"indices": [0]})).unwrap();
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks");
}
#[test]
fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() {
let mut s = session();
run(&mut s, json!({}));
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap();
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
let source = run(&mut s, json!({}));
assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's");
assert_eq!(kids(&s), 2);
run(&mut s, json!({"artboard": 1}));
assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy");
}
#[test]
fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() {
let mut s = session();
let original = run(&mut s, json!({}));
let id = original["ids"][0].as_u64().unwrap();
let before = node(&s, id);
s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap();
run(&mut s, json!({"artboard": 1}));
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group");
assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged");
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
run(&mut s, json!({"artboard": 0}));
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group");
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
}
#[test]
fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
let ids = r["ids"].as_array().unwrap();
assert_eq!(ids.len(), 2);
for id in ids {
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept");
}
let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
assert_eq!(again["changed"], json!(false));
}
#[test]
fn bad_params_are_refused_and_leave_the_document_unchanged() {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
let before = s.doc().unwrap().doc.clone();
let undo = undo_len(&s);
for bad in [
json!({"positions": ["middle"]}),
json!({"positions": ["top", "top"]}),
json!({"positions": "top"}),
json!({"positions": [1]}),
json!({"size": 2}),
json!({"size": "36"}),
json!({"weight": 0}),
json!({"inset": 5000}),
json!({"textSize": 100}),
json!({"textPlace": "middle"}),
json!({"textAlign": 1}),
json!({"ink": "Nope"}),
json!({"ink": "Process"}),
json!({"ink": 3}),
json!({"inks": "yes"}),
json!({"info": 1}),
json!({"time": "today", "info": true}),
json!({"artboard": 5}),
json!({"artboard": -1}),
json!({"artboard": 0, "allArtboards": true}),
json!({"positions": null}),
json!({"artboard": null}),
json!({"size": null}),
json!({"positions": [], "inks": false, "info": false}),
json!({"positions": [], "inks": true}),
] {
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
}
assert!(s.doc().unwrap().doc == before);
assert_eq!(undo_len(&s), undo);
// An ink line with no spot inks draws the targets and no line.
let r = run(&mut s, json!({"inks": true}));
assert_eq!(r["inks"], json!([]));
assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty());
}
#[test]
fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
let gone = s.doc().unwrap().doc.artboards[1].id;
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art");
// A reopened file does not remember the deleted id, so a new artboard can take it.
assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard");
}
#[test]
fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
let other = s.doc().unwrap().doc.layers[1].id.0;
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None);
}
#[test]
fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
let own = node(&s, r["ids"][0].as_u64().unwrap());
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard");
}
#[test]
fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]);
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled");
}
#[test]
fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
let own = node(&s, r["ids"][0].as_u64().unwrap());
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]);
s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap();
assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began");
s.execute("edit.undo", &json!({})).unwrap();
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]);
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap();
assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too");
}
#[test]
fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() {
let mut s = session();
for _ in 0..2 {
s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap();
}
let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]}));
// A file saved before deleting an artboard cleared its marks' tag.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2);
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]);
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed");
}
#[test]
fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap();
let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap();
let (own, foreign) = (node(&s, own), node(&s, foreign));
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
let start = bounds(&own);
let moved = bounds(&node(&s, own.id.0));
assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it");
assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay");
}
#[test]
fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
let second = s.doc().unwrap().doc.artboards[1].id;
s.doc_mut().unwrap().active_artboard = Some(second);
let start = s.journal.len();
run(&mut s, json!({"positions": ["right"]}));
let (cmd, recorded) = s.journal.last().unwrap().clone();
assert_eq!(cmd, COMMAND);
assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on");
// A replay on another active artboard marks the recorded one.
let first = s.doc().unwrap().doc.artboards[0].id;
s.doc_mut().unwrap().active_artboard = Some(first);
let replayed = run(&mut s, recorded);
assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same");
// A recorded action leaves it out and marks the artboard active when it plays.
let action = s.journal_for_action(start);
assert_eq!(action.len(), 2, "the action holds the first run and the replay");
assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none()));
}
+1 -1
View File
@@ -298,7 +298,7 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
pie,
arc_mode,
};
insert_custom(s, "Star", None, cs)
insert_custom(s, "Star", cs.to_live_shape(), cs)
}
fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
@@ -144,6 +144,68 @@ fn shape_of(s: &Session, id: NodeId) -> CustomShape {
CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()).unwrap()
}
#[test]
fn configuring_a_live_star_keeps_its_live_shape() {
let mut s = new_session();
for cmd in ["shape.star", "addon.shapes.star"] {
let id = id_of(&mut s, cmd, json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5}));
let n = s.doc().unwrap().doc.node(id).unwrap();
assert!(matches!(&n.kind, NodeKind::Path { live: Some(live), .. } if matches!(live.as_ref(), LiveShape::Star { points: 5, .. })));
assert!(matches!(CustomShape::read(n), Some(CustomShape::Polygon { sides: 5, spoke_ratio: Some(_), .. })));
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 7})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. }));
assert_eq!(path, &live.to_path());
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "spokeRatio": 0.4})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
assert!(matches!(live.as_ref(), LiveShape::Star { points: 7, .. }));
assert!((live.star_ratio().unwrap() - 0.4).abs() < 1e-9);
assert_eq!(path, &live.to_path());
}
}
/// A live star with a ratio below 0.01, which `object.setLiveShape` accepts, keeps its inner
/// radius and stays live when it is configured without a ratio.
#[test]
fn configuring_a_live_star_keeps_a_small_ratio() {
let mut s = new_session();
let id = id_of(&mut s, "shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 60.0, "radius2": 30.0, "points": 5}));
s.execute("object.setLiveShape", &json!({"id": id.0, "ratio": 0.0001})).unwrap();
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "sides": 6})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("expected live star") };
assert!(matches!(live.as_ref(), LiveShape::Star { r1, r2, points: 6, .. } if *r1 == 60.0 && (r2 - 0.006).abs() < 1e-9), "{live:?}");
assert_eq!(path, &live.to_path());
}
/// Angles configured on a whole shape stay live and are kept for a later arc mode.
#[test]
fn angles_configured_on_a_whole_shape_are_kept_for_a_later_arc_mode() {
let mut s = new_session();
let shapes = [
("shape.star", json!({"cx": 50.0, "cy": 50.0, "radius1": 40.0, "radius2": 20.0, "points": 5})),
("shape.polygon", json!({"cx": 50.0, "cy": 50.0, "radius": 40.0, "sides": 5})),
("shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 100.0, "height": 50.0})),
("shape.ellipse", json!({"x": 0.0, "y": 0.0, "width": 80.0, "height": 60.0})),
];
for (cmd, p) in shapes {
let id = id_of(&mut s, cmd, p);
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "startAngle": 0.0, "endAngle": 90.0})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap();
assert!(matches!(&n.kind, NodeKind::Path { live: Some(_), .. }), "{cmd} stays live");
s.execute("addon.shapes.configure", &json!({"ids": [id.0], "arcMode": "pie"})).unwrap();
let pie = match CustomShape::read(s.doc().unwrap().doc.node(id).unwrap()) {
Some(CustomShape::Rectangle { pie, .. } | CustomShape::Ellipse { pie, .. } | CustomShape::Polygon { pie, .. }) => pie,
other => panic!("{cmd}: {other:?}"),
};
assert_eq!(pie, (0.0, 90.0), "{cmd}");
}
}
/// Runs `cmd` with `p`, which must fail with `msg` and leave the document and its history as they
/// were.
fn refused(s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str) {
+6 -1
View File
@@ -5,8 +5,10 @@
//! (<https://helpx.adobe.com/illustrator/using/formatting-type.html>). Release Type on a Path
//! splits type on a path into point type holding the same text and the plain path it was set on
//! (#5532). The reference app has no command for it, so it goes beyond parity and changes no
//! parity score. Its submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
//! parity score. Create Font Sheet ([`font_sheet`]) sets a line of sample text in every font. Its
//! submenu (Object › Plug-ins › Type Tools) and dialogs are the UI's.
pub mod font_sheet;
pub mod numbers;
#[cfg(test)]
mod tests;
@@ -76,6 +78,9 @@ pub fn specs() -> Vec<CommandSpec> {
numbers::make_numbers
),
]
.into_iter()
.chain(font_sheet::specs())
.collect()
}
/// Release Type on a Path's command (the id in [`specs`]).
@@ -0,0 +1,376 @@
//! Create Font Sheet (`addon.type.fontSheet`; Object › Plug-ins › Type Tools › Create Font
//! Sheet…): a line of sample text set once in each font the font menus list (or in the fonts a
//! filter or a list names), each labeled with its font's name, flowed down columns on the active
//! artboard and on new artboards to its right when it fills, as one group made in one undo step.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeKind, TextObject, TextRun};
use vectorcraft_geom::{Affine, Point, Rect, Shape};
use vectorcraft_text::{FontDb, FontMatch};
use super::super::super::create::{new_type_para, new_type_style};
use super::super::super::panelcmds::artboard_at;
use super::super::super::typecmd::refresh_bounds;
use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or};
use crate::{Result, Session};
/// The command.
pub const COMMAND: &str = "addon.type.fontSheet";
/// The sample text when none is given.
pub const DEFAULT_TEXT: &str = "The quick brown fox jumps over the lazy dog";
/// Most fonts one sheet sets.
pub const MAX_FONTS: usize = 5000;
/// Most characters the sample text has.
pub const MAX_CHARS: usize = 1000;
/// The largest size a label is set at; a smaller sample's label is set at the sample's size.
const LABEL_SIZE: f64 = 9.0;
/// The space between the artboards the sheet adds, as `artboard.new` leaves it.
const ARTBOARD_GAP: f64 = 20.0;
/// The page a document without artboards lays the sheet out on (US Letter).
const LETTER: Rect = Rect { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.type.fontSheet",
"Create Font Sheet",
["Object", "Plug-ins", "Type Tools"],
None,
"{text?: one line of sample text of at most 1000 characters without line or paragraph breaks or other control characters (\"The quick brown fox jumps over the lazy dog\"), size?: pt 1..1296 (12), filter?: text (only the families whose name contains it, in any case; empty: every family), families?: [family name…] (instead of filter: these families, in this order; each must be available and named once; an error with any filter, an empty one included), allStyles?: false (true: one entry for each style of each family; false: the family's Regular, else its closest style), labels?: true (each entry starts with a line naming its font, at the sample's size up to 9 pt, in the document's normal type font), columns?: 1..50 (2), gap?: pt 0..1000 (12, between entries and between columns), margin?: pt 0..1000 (36, inside each page), newArtboards?: true (false: the pages after the first are laid out in the same places without artboards), artboard?: n (0-based; the artboard the first page is; default: the active one), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it)} set the sample text once in every family the font menus list (the bundled, added and installed fonts), as point type labeled with the font's name, every line aligned left (right-to-left samples too), flowed down the columns of the active artboard, or artboard `artboard` (inset by `margin`) and on to new artboards of the same size to the right of the rightmost artboard when it fills, as one group named Font Sheet in the current layer (else the topmost layer shown and unlocked), in one undo step; the group is selected. Each row is as tall as the tallest laid-out entry. A sample wider than its column runs on past it. A family whose font can't be loaded, or with allStyles a style that can't, or a composite font with a part setting the sample whose font or style can't, is left out, listed in `skipped` and named in `warning`. An entry whose font lacks a glyph needed by the sample stays on the sheet, and is listed in `fallback` and named in `warning`. An error, with nothing changed, when no font matches, when there are more than 5000 entries, when no font loads, or when the margin, gap and columns leave no room for an entry → {id, count, skipped: [family, or family and style…], fallback: [entry name…], artboards: [index…] (the artboards added), warning?}",
has_doc,
font_sheet
)]
}
/// `key` of `p`: `default` when omitted, else a number in `range`.
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
match p.get(key) {
None | Some(Value::Null) => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && range.contains(n))
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
}
}
/// The sample text of `p`: one line, not empty, at most [`MAX_CHARS`] characters.
fn sample_text(p: &Value) -> Result<String> {
let text = match p.get("text") {
None | Some(Value::Null) => return Ok(DEFAULT_TEXT.into()),
Some(Value::String(t)) => t.clone(),
Some(_) => return Err(bad(COMMAND, "`text` must be a string")),
};
if text.trim().is_empty() {
return Err(bad(COMMAND, "`text` must not be empty"));
}
// The line and paragraph separators break a line too.
if text.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
return Err(bad(COMMAND, "`text` must be one line, without line breaks or other control characters"));
}
if text.chars().count() > MAX_CHARS {
return Err(bad(COMMAND, format!("`text` must be at most {MAX_CHARS} characters")));
}
Ok(text)
}
/// The families the sheet sets, in order: those `families` names, else those the font menus of
/// `db` list whose name contains `filter`.
fn families(p: &Value, db: &FontDb) -> Result<Vec<String>> {
let filter = match p.get("filter") {
None | Some(Value::Null) => None,
Some(Value::String(f)) => Some(f.trim().to_lowercase()).filter(|f| !f.is_empty()),
Some(_) => return Err(bad(COMMAND, "`filter` must be a string")),
};
let listed = match p.get("families") {
None | Some(Value::Null) => {
let menu = db.menu_family_list();
let wanted = |f: &&String| filter.as_ref().is_none_or(|w| f.to_lowercase().contains(w.as_str()));
let found: Vec<String> = menu.iter().filter(wanted).cloned().collect();
if found.is_empty() {
return Err(bad(COMMAND, "no font family matches `filter`"));
}
return Ok(found);
}
Some(_) if p.get("filter").is_some_and(|f| !f.is_null()) => return Err(bad(COMMAND, "give `families` or `filter`, not both")),
Some(Value::Array(a)) => a,
Some(_) => return Err(bad(COMMAND, "`families` must be a list of font family names")),
};
if listed.is_empty() {
return Err(bad(COMMAND, "`families` must name at least one family"));
}
let mut out: Vec<String> = Vec::with_capacity(listed.len());
for f in listed {
let f = f.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(COMMAND, "`families` must be a list of font family names"))?;
if !db.has_family(f) {
return Err(bad(COMMAND, format!("font family `{f}` is not available")));
}
// The name as the font menus spell it, looked up as the database compares names.
let name = match db.composite_font(f) {
Some(c) => c.name.clone(),
None => db.canonical(f, "").0,
};
if out.iter().any(|o| o.to_lowercase() == name.to_lowercase()) {
return Err(bad(COMMAND, format!("`families` names `{name}` twice")));
}
out.push(name);
}
Ok(out)
}
/// The index of the artboard the view has active, else the one the document opened on, else the first.
fn active_artboard(st: &crate::DocState) -> usize {
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
}
fn font_sheet(s: &mut Session, p: &Value) -> Result<Value> {
font_sheet_in(s, p, FontDb::global())
}
/// [`font_sheet`] over the fonts of `db`.
fn font_sheet_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = COMMAND;
let text = sample_text(p)?;
let size = number(p, "size", 12.0, 1.0..=1296.0)?;
let columns = number(p, "columns", 2.0, 1.0..=50.0)?;
if columns.fract() != 0.0 {
return Err(bad(C, "`columns` must be a whole number 1..50"));
}
let columns = columns as usize;
let gap = number(p, "gap", 12.0, 0.0..=1000.0)?;
let margin = number(p, "margin", 36.0, 0.0..=1000.0)?;
let all_styles = switch_or(p, "allStyles", false, C)?;
let labels = switch_or(p, "labels", true, C)?;
let new_artboards = switch_or(p, "newArtboards", true, C)?;
let families = families(p, db)?;
// Each entry's font: (family, style); no style for the family's Regular or closest style.
let mut fonts: Vec<(String, Option<String>)> = vec![];
for f in &families {
let styles = if all_styles { db.styles(f) } else { vec![] };
if styles.is_empty() {
fonts.push((f.clone(), None));
} else {
fonts.extend(styles.into_iter().map(|st| (f.clone(), Some(st))));
}
if fonts.len() > MAX_FONTS {
return Err(bad(C, format!("a sheet sets at most {MAX_FONTS} fonts: give `filter` or `families`")));
}
}
let label = size.min(LABEL_SIZE);
// The artboard named, else `activeArtboard` (a replay of the journal), else the view's active
// one, which the journal entry then records as `activeArtboard` so a replay uses the same artboard.
let named = artboard_at(&s.doc()?.doc, p, "artboard", C)?;
let active = match named.or(artboard_at(&s.doc()?.doc, p, "activeArtboard", C)?) {
Some(i) => i,
None => {
let st = s.doc()?;
let i = active_artboard(st);
if i < st.doc.artboards.len() {
s.note_journal("activeArtboard", json!(i));
}
i
}
};
let st = s.doc()?;
let d = &st.doc;
let template = d.artboards.get(active).cloned();
let page = template.as_ref().map_or(LETTER, |a| a.rect);
let right = d.artboards.iter().map(|a| a.rect.x1).fold(page.x1, f64::max);
let system_layout = d.setup.system_layout;
let parent = st.target_parent()?;
// An entry's first baseline is at least one line's size below its top, and the entry at least
// this tall; the fonts are only laid out when the page has room for that.
let (least_above, least_height) = (if labels { label } else { size }, if labels { label } else { 0.0 } + size * 1.5);
let (inner_w, inner_h) = (page.width() - 2.0 * margin, page.height() - 2.0 * margin);
let column_w = (inner_w - gap * (columns - 1) as f64) / columns as f64;
let no_room = || bad(C, "the margin, gap and columns leave no room for a font on the artboard");
if column_w <= 0.0 || inner_h < least_height {
return Err(no_room());
}
let label_style = {
let mut style = new_type_style(s, &json!({ "size": label }), C)?;
style.leading = Some(label * 1.2);
style
};
// Each entry laid out at the origin, and how far its laid-out ink reaches above and below its first baseline.
let mut laid: Vec<(String, TextObject, (f64, f64))> = Vec::with_capacity(fonts.len());
let mut skipped: Vec<String> = vec![];
// The entries whose font lacks a glyph needed by the sample.
let mut fallback: Vec<String> = vec![];
for (family, style) in fonts {
let mut sample = new_type_style(s, &json!({ "size": size, "font": family, "style": style }), C)?;
sample.leading = Some(size * 1.2);
let name = match &style {
Some(st) => format!("{family} {st}"),
None => family.clone(),
};
// A font that doesn't load is drawn in the fallback font, and a style that doesn't in the
// family's closest style: either is left out. A composite font is left out when a part
// that sets the sample names a font or style that doesn't load.
let composite = db.composite_font(&family).is_some();
// Layout picks a font for each character as typed, then draws All Caps type, and the
// lowercase letters of Small Caps type, in capitals in that font, so coverage is checked on both.
let caps = sample.all_caps || sample.small_caps.is_some();
let (loads, covers) = if composite {
// Glyph coverage is checked on the characters layout draws, in the sample's numeral system.
let covers = db.composite_cased_coverage(&family, &[text.as_str()], sample.digits, caps).is_none_or(|c| c.lacking.is_empty());
(db.composite_coverage(&family, &[text.as_str()]).is_some_and(|c| c.status == FontMatch::Exact), covers)
} else {
let wanted = db.canonical(&family, "").0;
match db.face(&sample.font_family, &sample.font_style) {
Some(face) if face.family.eq_ignore_ascii_case(&wanted) && style.as_ref().is_none_or(|st| face.style.eq_ignore_ascii_case(st)) => {
let drawn = |t: &str| vectorcraft_text::drawn_chars(t, sample.digits).all(|c| face.covers(c));
let capitals = || text.chars().flat_map(char::to_uppercase).collect::<String>();
(true, drawn(&text) && (!caps || drawn(&capitals())))
}
_ => (false, true),
}
};
if !loads {
skipped.push(name);
continue;
}
if !covers {
fallback.push(name.clone());
}
let (first, more) = if labels {
(TextRun::new(format!("{name}\n"), label_style.clone()), Some(TextRun::new(text.clone(), sample)))
} else {
(TextRun::new(text.clone(), sample), None)
};
let t = laid_out(first, more, system_layout);
let extent = ink_extent(&t);
laid.push((name, t, extent));
}
if laid.is_empty() {
return Err(bad(C, "none of the fonts could be loaded"));
}
// Each page's layout: each entry's first baseline as far below its top as its ink reaches above
// it, a row as tall as the tallest entry with the gap below it, and the rows that fit inside the margin.
let height = laid.iter().map(|(.., (a, b))| a.max(least_above) + b).fold(least_height, f64::max);
let pitch = height + gap;
if inner_h < height {
return Err(no_room());
}
let rows = (((inner_h + gap) / pitch).floor() as usize).max(1);
let per_page = rows * columns;
// Where page `k` starts: the active artboard, then to the right of every artboard.
let page_x = |k: usize| if k == 0 { page.x0 } else { right + ARTBOARD_GAP + (k - 1) as f64 * (page.width() + ARTBOARD_GAP) };
let mut entries: Vec<(String, TextObject)> = Vec::with_capacity(laid.len());
for (i, (name, mut t, (above, _))) in laid.into_iter().enumerate() {
let (k, j) = (i / per_page, i % per_page);
let (col, row) = (j / rows, j % rows);
let x = page_x(k) + margin + col as f64 * (column_w + gap);
let baseline = page.y0 + margin + row as f64 * pitch + above.max(least_above);
// The layout is in text space, so moving the type keeps it.
t.xf = Affine::translate((x, baseline));
entries.push((name, t));
}
let count = entries.len();
let pages = count.div_ceil(per_page);
let boards: Vec<Rect> = (1..pages).map(|k| Rect::new(page_x(k), page.y0, page_x(k) + page.width(), page.y1)).collect();
let template = template.filter(|_| new_artboards);
let (gid, added) = s.edit("Create Font Sheet", |d, sel| {
let mut added = vec![];
if let Some(template) = template {
for rect in boards {
let mut a = template.clone();
a.id = d.next_artboard_id();
a.name = format!("Artboard {}", d.artboards.len() + 1);
a.rect = rect;
a.locked = false;
d.artboards.push(a);
added.push(d.artboards.len() - 1);
}
}
let children: Vec<Arc<Node>> = entries
.into_iter()
.map(|(name, t)| {
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
n.name = Some(name);
Arc::new(n)
})
.collect();
let gid = d.alloc_id();
let mut g = Node::new(gid, NodeKind::Group { children, clip: false });
g.name = Some("Font Sheet".into());
d.insert(parent, usize::MAX, g)?;
sel.set([gid]);
Ok((gid, added))
})?;
let mut out = json!({ "id": gid.0, "count": count, "skipped": skipped, "fallback": fallback, "artboards": added });
let warnings: Vec<String> = skipped_warning(&skipped).into_iter().chain(fallback_warning(&fallback)).collect();
if !warnings.is_empty() {
out["warning"] = json!(warnings.join("; "));
}
Ok(out)
}
/// The warning a sheet with entries whose font lacks a glyph of the sample gives, naming the first few.
fn fallback_warning(fallback: &[String]) -> Option<String> {
const NAMED: usize = 5;
let (first, more) = (fallback.iter().take(NAMED).cloned().collect::<Vec<_>>(), fallback.len().saturating_sub(NAMED));
match (first.is_empty(), more) {
(true, _) => None,
(false, 0) => Some(format!("{} font(s) lack glyphs for the sample: {}", fallback.len(), first.join(", "))),
(false, more) => Some(format!("{} font(s) lack glyphs for the sample: {} and {more} more", fallback.len(), first.join(", "))),
}
}
/// Point type set in `first` and then `more`, with its first baseline at the origin, laid out.
fn laid_out(first: TextRun, more: Option<TextRun>, system_layout: bool) -> TextObject {
let mut t = TextObject::point(Point::ZERO, "", first.style.clone());
t.runs = std::iter::once(first).chain(more).collect();
// Every paragraph is aligned left, right-to-left ones too, so each starts at the column's edge.
t.para = vectorcraft_doc::ParaStyle { justify: vectorcraft_doc::Justify::Left, ..new_type_para() };
t.system_layout = system_layout;
t.normalize_paras();
let layout = vectorcraft_text::layout(FontDb::global(), &t);
t.cached_bounds = Some(layout.bounds);
t.cached_baselines = layout.baselines();
let mut ink = layout.run_ink_bounds.clone();
for (run, bar) in vectorcraft_text::decorations(&layout, FontDb::global(), &t) {
if let Some(bounds) = ink.get_mut(run) {
let bar = bar.bounding_box();
*bounds = Some(bounds.map_or(bar, |bounds| bounds.union(bar)));
}
}
t.cached_ink = Some((layout.bounds, ink.iter().copied().flatten().reduce(|a, b| a.union(b))));
if t.runs.len() == 2
&& let (Some(label), Some(sample)) = (ink[0], ink[1])
{
let overlap = label.y1 - sample.y0;
if overlap > 0.0
&& let Some(run) = t.runs.get_mut(1)
{
run.style.leading = Some(run.style.leading.unwrap_or(run.style.size * 1.2) + overlap);
refresh_bounds(&mut t);
}
}
t
}
/// How far the ink of laid-out type `t` reaches above and below its first baseline, underline and
/// strikethrough bars included; none when nothing draws.
fn ink_extent(t: &TextObject) -> (f64, f64) {
t.cached_ink.and_then(|(_, ink)| ink).map_or((0.0, 0.0), |b| ((-b.y0).max(0.0), b.y1.max(0.0)))
}
/// The warning a sheet that left fonts out gives, naming the first few.
fn skipped_warning(skipped: &[String]) -> Option<String> {
const NAMED: usize = 5;
let (first, more) = (skipped.iter().take(NAMED).cloned().collect::<Vec<_>>(), skipped.len().saturating_sub(NAMED));
match (first.is_empty(), more) {
(true, _) => None,
(false, 0) => Some(format!("{} font(s) could not be loaded and were left out: {}", skipped.len(), first.join(", "))),
(false, more) => Some(format!("{} font(s) could not be loaded and were left out: {} and {more} more", skipped.len(), first.join(", "))),
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,636 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
use vectorcraft_text::FontDb;
use super::{COMMAND, DEFAULT_TEXT, MAX_CHARS};
use crate::Session;
/// The bundled families, available on every platform.
const BUNDLED: [&str; 3] = ["Inter", "Source Serif 4", "JetBrains Mono"];
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn group(s: &Session, r: &Value) -> Node {
s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone()
}
/// Each entry of the sheet `g`: its name and its type.
fn entries(g: &Node) -> Vec<(String, TextObject)> {
g.children()
.unwrap()
.iter()
.map(|n| match &n.kind {
NodeKind::Text(t) => (n.name.clone().unwrap_or_default(), (**t).clone()),
_ => panic!("a font sheet holds only type"),
})
.collect()
}
/// Where the first baseline of `t` starts.
fn origin(t: &TextObject) -> (f64, f64) {
let [.., x, y] = t.xf.as_coeffs();
(x, y)
}
#[test]
fn a_sheet_sets_the_text_in_each_family_labeled_in_columns_in_one_undo_step() {
let mut s = session();
let undo = steps(&s);
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 2, "size": 12, "gap": 10, "margin": 20, "text": "Hamburgefonstiv"})).unwrap();
assert_eq!(r["count"], 3);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["artboards"], json!([]), "three entries fit on the artboard");
assert_eq!(steps(&s), undo + 1, "one undo step");
let g = group(&s, &r);
assert_eq!(g.name.as_deref(), Some("Font Sheet"));
assert_eq!(s.doc().unwrap().selection.objects, [g.id], "the sheet is selected");
let e = entries(&g);
assert_eq!(e.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), BUNDLED, "in the order given, each named after its font");
for ((name, t), family) in e.iter().zip(BUNDLED) {
assert_eq!(t.plain_text(), format!("{name}\nHamburgefonstiv"), "a label line, then the sample");
let [label, sample] = &t.runs[..] else { panic!("a label run and a sample run: {:?}", t.runs.len()) };
assert_eq!(sample.style.font_family, family);
assert!((sample.style.size - 12.0).abs() < 1e-9 && (label.style.size - 9.0).abs() < 1e-9, "the label is set at 9 pt");
assert_eq!(label.style.font_family, "Source Sans 3", "the label is in the normal type font");
}
// Down the first column, 9 + 18 + 10 pt apart, inside the 20 pt margin, the first baseline one label below the top.
let board = s.doc().unwrap().doc.artboards[0].rect;
let (a, b) = (origin(&e[0].1), origin(&e[1].1));
assert!((a.0 - board.x0 - 20.0).abs() < 1e-9 && (a.1 - board.y0 - 29.0).abs() < 1e-9, "{a:?}");
assert!((b.0 - a.0).abs() < 1e-9 && (b.1 - a.1 - 37.0).abs() < 1e-9, "{b:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g.id).is_none(), "undo removes the sheet");
}
#[test]
fn a_full_artboard_continues_on_new_artboards_to_the_right() {
let mut s = session();
let undo = steps(&s);
// 400 pt tall less 2 × 100 pt of margin: 200 pt, room for two 72 pt entries (9 + 54 + 9).
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100})).unwrap();
assert_eq!(r["count"], 3);
assert_eq!(r["artboards"], json!([1]), "the third entry goes on a new artboard");
assert_eq!(steps(&s), undo + 1, "the new artboard is in the same undo step");
let doc = &s.doc().unwrap().doc;
let (first, added) = (doc.artboards[0].rect, doc.artboards[1].rect);
assert!((added.x0 - first.x1 - 20.0).abs() < 1e-9 && (added.y0 - first.y0).abs() < 1e-9, "{added:?}");
assert!((added.width() - first.width()).abs() < 1e-9 && (added.height() - first.height()).abs() < 1e-9, "the same size");
let e = entries(&group(&s, &r));
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9, "inset by the margin on the new artboard");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "undo removes the artboard too");
// Without new artboards, the page after the first is laid out in the same place with none.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 1, "size": 36, "gap": 9, "margin": 100, "newArtboards": false})).unwrap();
assert_eq!(r["artboards"], json!([]));
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
let e = entries(&group(&s, &r));
assert!((origin(&e[2].1).0 - added.x0 - 100.0).abs() < 1e-9);
}
#[test]
fn a_filter_picks_families_and_all_styles_lists_each_style() {
let mut s = session();
let r = s.execute(COMMAND, &json!({"filter": " sOURCE s ", "labels": false})).unwrap();
let e = entries(&group(&s, &r));
let names: Vec<&str> = e.iter().map(|(n, _)| n.as_str()).collect();
assert!(e.len() >= 2 && names.len() == e.len(), "{names:?}");
assert!(names.contains(&"Source Sans 3") && names.contains(&"Source Serif 4"), "{names:?}");
assert!(names.iter().all(|n| n.to_lowercase().contains("source s")), "{names:?}");
assert!(e.iter().all(|(_, t)| t.runs.len() == 1 && t.plain_text() == DEFAULT_TEXT), "no labels: the sample alone");
let r = s.execute(COMMAND, &json!({"families": ["Source Sans 3"], "allStyles": true})).unwrap();
let e = entries(&group(&s, &r));
let styles: Vec<String> = vectorcraft_text::FontDb::global().styles("Source Sans 3");
assert!(styles.len() > 1, "{styles:?}");
assert_eq!(e.len(), styles.len(), "one entry for each style");
for ((name, t), style) in e.iter().zip(&styles) {
assert_eq!(name, &format!("Source Sans 3 {style}"));
assert_eq!(&t.runs[1].style.font_style, style);
}
}
/// Columns sit side by side, each `gap` apart and as wide as the room inside the margin allows.
#[test]
fn columns_share_the_room_inside_the_margin() {
let mut s = session();
// 400 pt less 2 × 50 pt of margin leaves 300 pt: eight 39 pt entries (9 + 18 + 12) fit in a column.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12})).unwrap();
let board = s.doc().unwrap().doc.artboards[0].rect;
let e = entries(&group(&s, &r));
// The first column fills before the second starts, so all three share it.
let xs: Vec<f64> = e.iter().map(|(_, t)| origin(t).0).collect();
assert!(!xs.is_empty(), "the sheet has entries");
assert!(xs.iter().all(|x| (x - board.x0 - 50.0).abs() < 1e-9), "{xs:?}");
// One row per column: each entry starts a column, (500 − 2 × 12) / 3 wide plus the gap apart.
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "size": 150})).unwrap();
let e = entries(&group(&s, &r));
let step = (500.0 - 24.0) / 3.0 + 12.0;
for (i, (_, t)) in e.iter().enumerate() {
let (x, y) = origin(t);
assert!((x - board.x0 - 50.0 - i as f64 * step).abs() < 1e-9 && (y - board.y0 - 59.0).abs() < 1e-9, "entry {i}: {x}, {y}");
}
assert_eq!(r["artboards"], json!([]));
}
/// The journal records the active artboard, so a replay in a new session lays the sheet out on the
/// same one; an action leaves it out, and a named artboard goes ahead of it.
#[test]
fn the_journal_records_the_artboard_the_sheet_was_laid_out_on() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
let second = s.doc().unwrap().doc.artboards[1].clone();
s.doc_mut().unwrap().active_artboard = Some(second.id);
let start = s.journal.len();
let params = json!({"families": ["Inter"], "margin": 10});
let r = s.execute(COMMAND, &params).unwrap();
let e = entries(&group(&s, &r));
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "on the active artboard");
let (id, recorded) = s.journal.last().unwrap().clone();
assert_eq!((id.as_str(), &recorded["activeArtboard"]), (COMMAND, &json!(1)));
assert_eq!(s.journal_for_action(start)[0].1.get("activeArtboard"), None, "an action uses the artboard active when it plays");
// A replay in a session whose view has no active artboard uses the recorded one.
let mut fresh = session();
fresh.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 300, "height": 300})).unwrap();
let r = fresh.replay(COMMAND, &recorded).unwrap();
let e = entries(&group(&fresh, &r));
assert!((origin(&e[0].1).0 - second.rect.x0 - 10.0).abs() < 1e-9, "the replay lays it out on the recorded artboard");
// A named artboard goes ahead of the recorded one.
let r = fresh.execute(COMMAND, &json!({"families": ["Inter"], "margin": 10, "artboard": 0, "activeArtboard": 1})).unwrap();
let e = entries(&group(&fresh, &r));
let first = fresh.doc().unwrap().doc.artboards[0].rect;
assert!((origin(&e[0].1).0 - first.x0 - 10.0).abs() < 1e-9);
assert!(fresh.execute(COMMAND, &json!({"families": ["Inter"], "artboard": 5})).is_err(), "no such artboard");
}
/// A right-to-left sample starts at its column's left edge like any other, so it stays inside its column.
#[test]
fn a_right_to_left_sample_stays_inside_its_column() {
let mut s = session();
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
let board = s.doc().unwrap().doc.artboards[0].rect;
// Alone, and under a left-to-right label: each line starts at the column's left edge.
for labels in [false, true] {
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "columns": 3, "margin": 50, "gap": 12, "labels": labels, "text": rtl})).unwrap();
assert_eq!(r["fallback"], json!(BUNDLED), "no bundled font has Hebrew glyphs, so each entry is named");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
for (name, t) in &entries(&group(&s, &r)) {
let x = origin(t).0;
assert!((x - board.x0 - 50.0).abs() < 1e-9, "{name}: {x}");
let layout = vectorcraft_text::layout(FontDb::global(), t);
for line in &layout.lines {
let left = x + line.x0;
assert!(left > board.x0 + 50.0 - 1e-6, "{name}, labels {labels}: a line starts at {left}, left of the column's edge");
}
}
}
}
#[test]
fn a_variation_selector_does_not_require_a_separate_glyph() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
assert!(face.covers('A'));
assert!(!face.covers('\u{fe0f}'));
let text = "A\u{fe0f}";
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
assert_eq!(r["count"], 1);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["fallback"], json!([]));
assert!(r.get("warning").is_none(), "{r}");
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 1);
assert_eq!(e[0].1.plain_text(), text);
}
#[test]
fn coverage_uses_the_samples_numeral_system() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
assert!(face.covers('1'));
assert!(!face.covers('\u{661}'));
for (digits, text, missing) in [("hindi", "1", true), ("arabic", "\u{661}", false)] {
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": digits}}))
.unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": text})).unwrap();
assert_eq!(r["count"], 1);
assert_eq!(r["skipped"], json!([]));
assert_eq!(r["fallback"], if missing { json!(["Inter"]) } else { json!([]) }, "{digits}: {r}");
if missing {
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("Inter")), "{r}");
} else {
assert!(r.get("warning").is_none(), "{r}");
}
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 1);
assert_eq!(e[0].1.plain_text(), text);
assert_eq!(e[0].1.runs[0].style.digits.id(), digits);
}
}
/// All Caps in the normal character style draws the sample in capitals, so a font with a lowercase
/// letter but not its capital is named in `fallback`, plain and composite fonts alike.
#[test]
fn coverage_checks_the_capitals_all_caps_draws() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
let lower = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let mut up = c.to_uppercase();
face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
let font = json!({"name": "CF Sheet Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let text = lower.to_string();
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"all_caps": true}})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter", "CF Sheet Caps"], "labels": false, "text": text})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
assert_eq!(r["fallback"], json!(["Inter", "CF Sheet Caps"]), "{lower:?}: {r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs")), "{r}");
let e = entries(&group(&s, &r));
assert!(e[0].1.runs[0].style.all_caps);
assert_eq!(e[0].1.plain_text(), text, "the sample keeps its own case");
// Layout picks the font for the character as typed, so one the font lacks still falls back
// when the font has its capitals.
let uncased = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let up: String = c.to_uppercase().collect();
!face.covers(c) && up != c.to_string() && up.chars().all(|u| face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has every character whose capitals it has"));
let r = s.execute(COMMAND, &json!({"families": ["Inter"], "labels": false, "text": uncased.to_string()})).unwrap();
assert_eq!(r["fallback"], json!(["Inter"]), "{uncased:?}: {r}");
}
/// Small Caps in the normal character style draws lowercase letters as capitals too, so a font with
/// a lowercase letter but not its capital is named in `fallback`, plain and composite fonts alike.
#[test]
fn coverage_checks_the_capitals_small_caps_draws() {
let mut s = session();
let face = FontDb::global().face("Inter", "Regular").unwrap();
let lower = (0x80..0x3000u32)
.filter_map(char::from_u32)
.find(|&c| {
let mut up = c.to_uppercase();
c.is_lowercase() && face.covers(c) && up.len() == 1 && up.next().is_some_and(|u| u != c && !face.covers(u))
})
.unwrap_or_else(|| panic!("Inter has no lowercase letter without its capital"));
let font = json!({"name": "CF Sheet Small Caps", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let text = lower.to_string();
let families = json!(["Inter", "CF Sheet Small Caps"]);
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
assert_eq!(r["fallback"], json!([]), "{lower:?}: {r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"small_caps": 70}})).unwrap();
let r = s.execute(COMMAND, &json!({"families": families, "labels": false, "text": text})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
let e = entries(&group(&s, &r));
assert_eq!(e.len(), 2);
assert!(e[0].1.runs[0].style.small_caps.is_some());
assert_eq!(r["fallback"], families, "{lower:?}: {r}");
}
#[test]
fn bad_params_are_refused_without_a_change() {
let mut s = session();
let before = steps(&s);
let long = "x".repeat(MAX_CHARS + 1);
for bad in [
json!({"text": ""}),
json!({"text": " "}),
json!({"text": "two\nlines"}),
json!({"text": "two\u{2028}lines"}),
json!({"text": "two\u{2029}paragraphs"}),
json!({"text": long}),
json!({"text": 5}),
json!({"size": 0.5}),
json!({"size": "12"}),
json!({"columns": 0}),
json!({"columns": 1.5}),
json!({"gap": -1}),
json!({"margin": 2000}),
json!({"margin": 300}),
json!({"columns": 50, "gap": 1000}),
json!({"filter": "no family is called this"}),
json!({"filter": 3}),
json!({"families": []}),
json!({"families": "Inter"}),
json!({"families": ["Inter", "inter"]}),
json!({"families": ["No Such Family Anywhere"]}),
json!({"families": [""]}),
json!({"families": ["Inter"], "filter": "Inter"}),
json!({"families": ["Inter"], "filter": ""}),
json!({"families": ["Inter"], "filter": " "}),
json!({"labels": "yes"}),
json!({"allStyles": 1}),
json!({"newArtboards": "no"}),
] {
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
}
assert_eq!(steps(&s), before);
let layers = &s.doc().unwrap().doc.layers;
assert!(!layers.is_empty(), "the document keeps its layers");
assert!(layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())), "nothing was drawn");
}
/// Fonts left out are named in the warning, the first five of them, with a count of the rest.
#[test]
fn fonts_left_out_are_named_in_a_warning() {
let names = |n: usize| (1..=n).map(|i| format!("Font {i}")).collect::<Vec<_>>();
assert_eq!(super::skipped_warning(&[]), None);
assert_eq!(super::skipped_warning(&names(2)).as_deref(), Some("2 font(s) could not be loaded and were left out: Font 1, Font 2"));
assert_eq!(
super::skipped_warning(&names(7)).as_deref(),
Some("7 font(s) could not be loaded and were left out: Font 1, Font 2, Font 3, Font 4, Font 5 and 2 more")
);
let mut s = session();
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
assert!(r.get("warning").is_none(), "nothing left out: no warning");
}
/// A family the font menus list whose file no longer reads as a font is left out, as is a style
/// that would be drawn in another style of its family; the rest of the sheet is made.
#[test]
fn fonts_that_do_not_load_are_left_out_and_named() {
use vectorcraft_text::test_fonts::named_copy;
let dir = vectorcraft_testkit::temp_dir("font-sheet-unreadable");
let file = |family: &str, style: &str| dir.join(format!("{}-{style}.ttf", family.replace(' ', "")));
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Regular"), ("Sheet Half", "Bold")] {
let postscript = format!("{}-{style}", family.replace(' ', ""));
std::fs::write(file(family, style), named_copy(false, (family, style, "Version 1.000", &postscript)).unwrap()).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir.clone()]);
// Cataloged while every file reads; then two of them stop reading as fonts.
assert_eq!(db.styles("Sheet Half").len(), 2, "{:?}", db.styles("Sheet Half"));
assert!(db.menu_family_list().iter().any(|f| f == "Sheet Gone"));
for (family, style) in [("Sheet Gone", "Regular"), ("Sheet Half", "Bold")] {
std::fs::write(file(family, style), b"not a font").unwrap();
}
let mut s = session();
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone", "Inter"]}), &db).unwrap();
assert_eq!(r["skipped"], json!(["Sheet Gone"]), "drawn in the fallback font, it is left out: {r}");
assert_eq!(r["count"], 1);
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: Sheet Gone");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
let r = super::font_sheet_in(&mut s, &json!({"families": ["Sheet Half"], "allStyles": true}), &db).unwrap();
assert_eq!(r["skipped"], json!(["Sheet Half Bold"]), "drawn in its Regular, the Bold is left out: {r}");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Sheet Half Regular"]);
// Nothing that loads: an error, with nothing changed.
let before = steps(&s);
assert!(super::font_sheet_in(&mut s, &json!({"families": ["Sheet Gone"]}), &db).is_err());
assert_eq!(steps(&s), before);
}
/// Where the ink of `t` starts and ends down the page.
fn ink_rows(t: &TextObject) -> (f64, f64) {
let (_, y) = origin(t);
let b = vectorcraft_text::layout(FontDb::global(), t).ink_bounds().unwrap();
(y + b.y0, y + b.y1)
}
/// A composite font whose Roman part sets the sample at four times its size gets rows as tall as
/// its laid-out ink: the first entry stays inside the margin, the second starts below the first,
/// and each sample starts below its own label.
#[test]
fn rows_fit_the_laid_out_ink_of_a_composite_font() {
let mut s = session();
let big = |name: &str| json!({"name": name, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter", "size": 400}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [big("CF Sheet Big A"), big("CF Sheet Big B")]})).unwrap();
let p = json!({"families": ["CF Sheet Big A", "CF Sheet Big B"], "columns": 1, "size": 12, "gap": 10, "margin": 20, "text": "Hamburg"});
let r = s.execute(COMMAND, &p).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(2), &json!([])), "{r}");
let board = s.doc().unwrap().doc.artboards[0].rect;
let e = entries(&group(&s, &r));
let ((top0, bottom0), (top1, _)) = (ink_rows(&e[0].1), ink_rows(&e[1].1));
assert!(top0 >= board.y0 + 20.0 - 1e-6, "the first entry reaches into the margin: {top0}");
assert!(top1 >= bottom0 - 1e-6, "the second entry overlaps the first: {top1} < {bottom0}");
for (name, t) in &e {
let mut label = t.clone();
label.runs.truncate(1);
let mut sample = t.clone();
sample.runs.remove(0);
let (y0, y1) = (t.cached_baselines[0].0.y, t.cached_baselines[1].0.y);
let label_bottom = y0 + vectorcraft_text::layout(FontDb::global(), &label).ink_bounds().unwrap().y1;
let sample_top = y1 + vectorcraft_text::layout(FontDb::global(), &sample).ink_bounds().unwrap().y0;
assert!(sample_top >= label_bottom - 1e-6, "{name}: the sample reaches into its label: {sample_top} < {label_bottom}");
}
}
/// A composite font named in other letter case, accented letters included, is found by its own name.
#[test]
fn a_composite_font_named_in_other_case_is_set() {
let mut s = session();
let font = json!({"name": "\u{c9}preuve Sheet", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["\u{e9}preuve sheet"], "text": "Hamburg"})).unwrap();
assert_eq!((r["skipped"].clone(), r["count"].clone()), (json!([]), json!(1)), "{r}");
assert_eq!(entries(&group(&s, &r))[0].0, "\u{c9}preuve Sheet");
let twice = s.execute(COMMAND, &json!({"families": ["\u{c9}preuve Sheet", "\u{e9}PREUVE SHEET"]})).unwrap_err().to_string();
assert!(twice.contains("twice"), "{twice}");
}
/// A composite font whose part setting the sample names a font that doesn't load is left out and
/// named, as a family that doesn't load is.
#[test]
fn a_composite_font_with_a_missing_part_is_left_out() {
let mut s = session();
let font = json!({"name": "CF Sheet Gone", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Sheet Font"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Gone", "Inter"], "text": "Hamburg"})).unwrap();
assert_eq!(r["skipped"], json!(["CF Sheet Gone"]), "{r}");
assert_eq!(r["count"], 1);
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
}
#[test]
fn a_composite_font_with_an_unavailable_part_style_is_left_out() {
let mut s = session();
let font = json!({
"name": "CF Sheet Missing Style",
"parts": {
"kanji": {"font": "Source Sans 3"},
"roman": {"font": "Inter", "style": "No Such Sheet Style"}
}
});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let coverage = FontDb::global().composite_coverage("CF Sheet Missing Style", &["Hamburg"]).unwrap();
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Style);
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style", "Inter"], "text": "Hamburg"})).unwrap();
assert_eq!(r["skipped"], json!(["CF Sheet Missing Style"]));
assert_eq!(r["count"], 1);
assert_eq!(r["warning"], "1 font(s) could not be loaded and were left out: CF Sheet Missing Style");
assert_eq!(entries(&group(&s, &r)).iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Inter"]);
let before = (s.doc().unwrap().doc.clone(), steps(&s));
assert!(s.execute(COMMAND, &json!({"families": ["CF Sheet Missing Style"], "text": "Hamburg"})).is_err());
assert_eq!(s.doc().unwrap().doc, before.0);
assert_eq!(steps(&s), before.1);
}
/// A composite font whose parts load but lack a glyph the sample needs stays on the sheet and is
/// named in `fallback`, as a plain font is.
#[test]
fn a_composite_font_lacking_a_sample_glyph_is_named_as_a_fallback() {
let mut s = session();
let font = json!({"name": "CF Sheet Lacking", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
let rtl = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
let coverage = FontDb::global().composite_coverage("CF Sheet Lacking", &[rtl]).unwrap();
assert_eq!(coverage.status, vectorcraft_text::FontMatch::Exact);
assert!(!coverage.lacking.is_empty());
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": rtl})).unwrap();
assert_eq!((&r["count"], &r["skipped"]), (&json!(1), &json!([])), "{r}");
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
assert!(r["warning"].as_str().is_some_and(|w| w.contains("lack glyphs") && w.contains("CF Sheet Lacking")), "{r}");
// A variation selector needs no glyph of its own, and digits are checked in the sample's numeral system.
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "A\u{fe0f}"})).unwrap();
assert_eq!(r["fallback"], json!([]), "{r}");
s.execute("charStyle.edit", &json!({"name": "[Normal Character Style]", "to": "[Normal Character Style]", "attrs": {"digits": "hindi"}}))
.unwrap();
let r = s.execute(COMMAND, &json!({"families": ["CF Sheet Lacking"], "text": "1"})).unwrap();
assert_eq!(r["fallback"], json!(["CF Sheet Lacking"]), "{r}");
}
#[test]
fn labels_without_overlap_need_no_additional_layouts() {
use vectorcraft_text::test_fonts::{ink_work_on_this_thread, layouts_on_this_thread};
let mut counts = vec![];
for labels in [false, true] {
let mut s = session();
let before = layouts_on_this_thread();
let ink_before = ink_work_on_this_thread();
let r = s.execute(COMMAND, &json!({"families": BUNDLED, "text": "Hamburg", "labels": labels})).unwrap();
let ink_after = ink_work_on_this_thread();
counts.push(layouts_on_this_thread() - before);
assert_eq!(r["count"], BUNDLED.len());
let mut outlines = 0;
for (_, t) in entries(&group(&s, &r)) {
assert!(t.cached_ink.unwrap().1.is_some());
assert_eq!(t.cached_baselines.len(), if labels { 2 } else { 1 });
let layout = vectorcraft_text::layout(FontDb::global(), &t);
outlines += layout.glyphs.iter().chain(&layout.ruby).filter(|glyph| !glyph.outline.elements().is_empty()).count() as u64;
assert_eq!(t.cached_ink.unwrap().1, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
}
assert_eq!(ink_after.0 - ink_before.0, outlines, "each glyph outline is measured once");
assert_eq!(ink_after.1 - ink_before.1, BUNDLED.len() as u64, "decorations are measured once per entry");
}
assert!(counts[0] > 0);
assert_eq!(counts[1], counts[0], "labels that fit must not cause separate label and sample layouts");
}
#[test]
fn reused_font_sheet_ink_includes_decorations_and_handles_blank_runs() {
use vectorcraft_doc::{CharStyle, TextRun};
for text in ["Hamburg", " "] {
for labels in [false, true] {
let style = CharStyle { font_family: "Inter".into(), size: 12.0, underline: true, strikethrough: true, ..Default::default() };
let sample = TextRun::new(text, style.clone());
let (first, more) = if labels { (TextRun::new("Font\n", style), Some(sample)) } else { (sample, None) };
let t = super::laid_out(first, more, false);
let layout = vectorcraft_text::layout(FontDb::global(), &t);
let bars = vectorcraft_text::decorations(&layout, FontDb::global(), &t);
assert!(!bars.is_empty(), "the entry includes underline and strikethrough bars");
let ink = t.cached_ink.unwrap().1;
assert_eq!(ink, vectorcraft_render::effects::preview::laid_out_ink(&layout, &t));
let ink = ink.unwrap();
for (_, bar) in bars {
let bounds = vectorcraft_geom::Shape::bounding_box(&bar);
assert!(ink.x0 <= bounds.x0 && ink.y0 <= bounds.y0 && ink.x1 >= bounds.x1 && ink.y1 >= bounds.y1);
}
}
}
}
#[test]
fn an_artboard_deletion_guard_checks_the_document_and_artboard_ids() {
let mut s = Session::new();
s.execute("file.new", &json!({"artboards": 3})).unwrap();
let state = s.doc().unwrap();
let document = (state.uid, state.reverts);
let artboard = state.doc.artboards[1].id;
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
let before = (s.doc().unwrap().doc.clone(), steps(&s));
for params in [json!({"index": 0}), json!({"indices": [1, 0]})] {
let error = s.execute("artboard.delete", &params).unwrap_err();
assert_eq!(error.to_string(), "The artboard is in use.");
assert_eq!(s.doc().unwrap().doc, before.0);
assert_eq!(steps(&s), before.1);
}
s.execute("file.new", &json!({"artboards": 2})).unwrap();
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "another document is not protected");
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.doc_mut().unwrap().reverts += 1;
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "a reverted drawing is not protected");
}
/// Cut Artboard, Delete Empty Artboards and Artwork Cleanup's Empty Artboards keep the guarded artboard too.
#[test]
fn an_artboard_deletion_guard_covers_every_command_that_deletes_artboards() {
let mut s = Session::new();
s.execute("file.new", &json!({"artboards": 3})).unwrap();
let state = s.doc().unwrap();
let document = (state.uid, state.reverts);
let artboard = state.doc.artboards[1].id;
s.artboard_deletion_guard = Some(crate::ArtboardDeletionGuard { document, artboard, message: "The artboard is in use.".into() });
let before = (s.doc().unwrap().doc.clone(), steps(&s));
for (command, params) in [
("artboard.cut", json!({"index": 1})),
("artboard.deleteEmpty", json!({})),
("addon.cleanup.fix", json!({"kinds": ["emptyArtboards"], "scope": "document"})),
] {
let error = s.execute(command, &params).unwrap_err();
assert_eq!(error.to_string(), "The artboard is in use.", "{command}");
assert_eq!(s.doc().unwrap().doc, before.0, "{command}");
assert_eq!(steps(&s), before.1, "{command}");
}
s.execute("artboard.cut", &json!({"index": 2})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2, "another artboard is cut");
}
#[test]
fn it_needs_a_document() {
let mut s = Session::new();
assert!(s.execute(COMMAND, &json!({})).is_err());
}
#[test]
fn a_locked_layer_takes_no_sheet() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
let before = steps(&s);
assert!(s.execute(COMMAND, &json!({"families": ["Inter"]})).is_err());
assert_eq!(steps(&s), before);
}
#[test]
fn a_locked_current_layer_sends_the_sheet_to_the_topmost_editable_layer() {
let mut s = session();
let editable = s.doc().unwrap().doc.layers[0].id;
let locked = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
let r = s.execute(COMMAND, &json!({"families": ["Inter"]})).unwrap();
let gid = NodeId(r["id"].as_u64().unwrap());
let doc = &s.doc().unwrap().doc;
let holds = |layer: NodeId| doc.children(Some(layer)).is_some_and(|c| c.iter().any(|n| n.id == gid));
assert!(holds(editable), "the sheet goes to the layer that is shown and unlocked");
assert!(!holds(locked));
}
+18 -12
View File
@@ -1118,7 +1118,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
return Err(EngineError::Cancelled);
}
let id = s.edit(label, |d, sel| {
let src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
let mut src = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
let mut image = if is_trace_group(&src) {
src.children()
.and_then(|c| c.first())
@@ -1225,17 +1225,23 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
let gid = d.alloc_id();
let mut g = Node::group(gid, children);
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
// Tracing again keeps the tracing's own object settings: opacity, blend mode, its
// appearance items, visibility and lock.
if !expand && is_trace_group(&src) {
g.visible = src.visible;
g.locked = src.locked;
g.opacity = src.opacity;
g.blend = src.blend;
g.isolate = src.isolate;
g.knockout = src.knockout;
g.knockout_shape = src.knockout_shape;
g.appearance = src.appearance.clone();
// Tracing again keeps the tracing's note, tags and URL, including when expanding.
// Without expansion, it also keeps the tracing's other object settings.
if is_trace_group(&src) {
// The attributes move from `src`, this edit's own copy of the tracing, without another copy.
if src.extras().attrs.is_some() {
g.extras_mut().attrs = src.extras_mut().attrs.take();
}
if !expand {
g.visible = src.visible;
g.locked = src.locked;
g.opacity = src.opacity;
g.blend = src.blend;
g.isolate = src.isolate;
g.knockout = src.knockout;
g.knockout_shape = src.knockout_shape;
g.appearance = src.appearance.clone();
}
}
if !expand {
// Tracing again keeps the object's view unless another is asked for, and the Split
+3 -1
View File
@@ -22,7 +22,9 @@ use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
pub use flavours::{
AI, BITMAP, DWG, DXF, EMF, EPS, FILE_HEAD, Flavour, HPGL, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture,
};
pub use flavours::{ImageRead, read_image, read_pixels};
pub(crate) use resources::SwatchChoices;
pub use resources::{ArtResources, SymbolOptions, art_resources};
+57 -14
View File
@@ -1,5 +1,6 @@
//! Clipboard flavours: what Copy offers other apps besides SVG (PNG, PDF and plain text) and what
//! Paste takes from them (bitmaps, plain text, PDF, EPS and Windows metafiles).
//! Paste takes from them (bitmaps, plain text, PDF, EPS, Windows metafiles, and copied CAD drawing
//! and plot files).
//!
//! The UI owns the platform clipboard (`Services::system_clipboard` in the egui frontend): on Copy
//! it publishes [`Session::clipboard_flavours`]; before a Paste it turns what another app put on
@@ -34,9 +35,20 @@ pub const EPS: &str = "application/postscript";
/// reads it as `document.open` does, from its editing data. The type is VectorCraft's own: no
/// system clipboard carries it, and Paste asks for [`PDF`] to get it.
pub const AI: &str = "application/x-ai";
/// A DXF drawing file copied in a file manager ([`file_flavour`]): Paste reads it with
/// `clipboard.importCad`. No system clipboard carries it, and Paste takes it when it asks for any
/// vector art.
pub const DXF: &str = "image/vnd.dxf";
/// A DWG drawing file copied in a file manager, read as [`DXF`] is.
pub const DWG: &str = "image/vnd.dwg";
/// An HP-GL plot file (`.plt`, `.hpgl`…) copied in a file manager, read as [`DXF`] is.
pub const HPGL: &str = "application/vnd.hp-hpgl";
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
/// (word processors offer a picture of copied text too).
pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP];
/// The types Paste asks for that a copied CAD drawing or plot file ([`DXF`], [`DWG`], [`HPGL`])
/// pastes as.
const VECTOR_ART: [&str; 4] = [SVG, PDF, EPS, EMF];
/// Is `text` only an address (a web page's, an image's, a file's)? A browser's Copy Image puts the
/// image's address as text next to the picture: then the picture is what Paste takes (#597). An
/// address alone pastes as text, and nothing is fetched.
@@ -76,25 +88,31 @@ pub const FILE_HEAD: usize = 4096;
/// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap):
/// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first
/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file is [`AI`] when its bytes are a PDF (it
/// pastes when PDF is asked for) and EPS when they are PostScript. The file's bytes are that
/// flavour's data.
/// pastes when PDF is asked for) and EPS when they are PostScript. A DXF or DWG drawing or an
/// HP-GL plot file is [`DXF`], [`DWG`] or [`HPGL`], and pastes when any vector art (SVG, PDF, EPS
/// or EMF) is asked for. The file's bytes are that flavour's data.
pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> {
let f = fileio::detect(name, head)?;
let (asked, mime) = match f.id {
"svg" => (SVG, SVG),
let (asked, mime): (&[&str], _) = match f.id {
"svg" => (&[SVG], SVG),
// `detect` names gzip data SVGZ (a compressed native file aside); `clipboard.importSvg`
// reads SVGZ data.
"svgz" if unpacks_to_svg(head) => (SVG, SVG),
"pdf" => (PDF, PDF),
"ps" => (EPS, EPS),
"eps" => (EPS, EPS),
"ai" | "ait" if head.starts_with(b"%PDF") => (PDF, AI),
"ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (EPS, EPS),
"emf" | "wmf" => (EMF, EMF),
_ if f.raster => (BITMAP, f.mime),
"svgz" if unpacks_to_svg(head) => (&[SVG], SVG),
"pdf" => (&[PDF], PDF),
"ps" => (&[EPS], EPS),
"eps" => (&[EPS], EPS),
"ai" | "ait" if head.starts_with(b"%PDF") => (&[PDF], AI),
"ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (&[EPS], EPS),
"emf" | "wmf" => (&[EMF], EMF),
// A file with a drawing's or a plot file's name may hold something else (`.plt` is also a
// chart program's script): it pastes only when its bytes are a drawing or a plot.
"dxf" if vectorcraft_cad::is_dxf(head) => (&VECTOR_ART, DXF),
"dwg" if vectorcraft_cad::is_dwg(head) => (&VECTOR_ART, DWG),
"hpgl" if vectorcraft_cad::hpgl::is_named_hpgl(head) => (&VECTOR_ART, HPGL),
_ if f.raster => (&[BITMAP], f.mime),
_ => return None,
};
mimes.contains(&asked).then_some(mime)
mimes.iter().any(|m| asked.contains(m)).then_some(mime)
}
/// Does gzip data `head` (a file's first bytes, often a stream cut short) unpack to SVG markup?
@@ -222,6 +240,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
import_eps
),
cmd!(
query "clipboard.importCad",
"Load CAD Drawing into Clipboard",
[],
None,
"{dataBase64 (a DXF or DWG drawing, or an HP-GL plot file), format: dxf|dwg|hpgl (what the data is; data of another format is refused), center?: [x, y]} replace the clipboard with the drawing's objects as document.open reads the file (DXF and DWG: the Model layout at 1:1 in its own unit), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste. The app runs it for a .dxf, .dwg or HP-GL file copied in a file manager",
has_doc,
import_cad
),
]
}
@@ -565,6 +592,22 @@ fn import_eps(s: &mut Session, p: &Value) -> Result<Value> {
import_picture(s, p, C, "Clipboard.eps", &bytes)
}
fn import_cad(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "clipboard.importCad";
let (is_it, name, not_it): (fn(&[u8]) -> bool, _, _) = match p.get("format").and_then(Value::as_str) {
Some("dxf") => (vectorcraft_cad::is_dxf, "Clipboard.dxf", "the data isn't a DXF drawing"),
Some("dwg") => (vectorcraft_cad::is_dwg, "Clipboard.dwg", "the data isn't a DWG drawing"),
Some("hpgl") => (vectorcraft_cad::hpgl::is_named_hpgl, "Clipboard.plt", "the data isn't an HP-GL plot file"),
_ => return Err(bad(C, "format must be dxf, dwg or hpgl")),
};
let bytes = data_param(p, C)?;
// Data of another format is refused, not read as the format its name gives.
if !is_it(&bytes) {
return Err(bad(C, not_it));
}
import_picture(s, p, C, name, &bytes)
}
/// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is
/// opened (command `cmd`).
fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result<Value> {
+70 -7
View File
@@ -99,12 +99,19 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
note(family);
}
}
let mut graphs = Vec::new();
let (mut graphs, mut dimensions) = (Vec::new(), Vec::new());
view.visit_stored(|node, _| {
// A dimension's options name the family its label is redrawn in.
if let Some(dimension) = &node.extras().dimension {
dimensions.push(dimension.options.font_family.clone());
}
if node.extras().graph.is_some() {
graphs.push(node.id);
}
});
for mut family in dimensions {
note(&mut family);
}
for id in graphs {
if let Some(node) = view.stored_node_mut(id) {
graph_families(node, &mut note);
@@ -112,6 +119,9 @@ fn family_names(d: &Document) -> Result<BTreeSet<String>> {
}
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
graph_families(node, note);
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
note(&mut dimension.options.font_family);
}
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
brush_graphs(Arc::make_mut(&mut mask.art), note);
}
@@ -140,6 +150,20 @@ pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)
for run in &mut text.runs {
visit(&mut run.style.font_family);
}
// The fonts the file carried for this type are found by the family its runs name.
for font in text.file_fonts.iter_mut().flat_map(|fonts| fonts.fonts.iter_mut()) {
visit(&mut font.family);
}
}
// A dimension redraws its label from its own options, so they follow the label's family.
// A spelling that already names the same font, or one too long for the options, is kept.
if let Some(dimension) = node.extras_if_any().and_then(|extras| extras.dimension.as_mut()) {
let family = &mut dimension.options.font_family;
let mut renamed = family.clone();
visit(&mut renamed);
if !CompositeFont::same_name(&renamed, family) && renamed.len() <= ALIAS_BYTES_MAX {
*family = renamed;
}
}
graph_families(node, visit);
}
@@ -162,12 +186,22 @@ impl CompositeImport {
}
}
/// The longest family name in bytes that a dimension's options keep (`DimensionOptions::validate`).
const ALIAS_BYTES_MAX: usize = 256;
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
let db = FontDb::global();
let mut number = 2_u64;
loop {
let suffix = format!(" {number}");
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
let bytes = ALIAS_BYTES_MAX.saturating_sub(suffix.len());
let mut stem = String::new();
for c in base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())) {
if stem.len() + c.len_utf8() > bytes {
break;
}
stem.push(c);
}
let name = format!("{}{suffix}", stem.trim_end());
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
&& !reserved.contains(&name.to_lowercase())
@@ -181,7 +215,13 @@ fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result
/// Plan used incoming definitions before changing either document or the font database.
/// Keep existing meanings even for an uninstalled family that destination art still names.
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
pub(super) fn plan_import(
source: Vec<CompositeFont>,
source_families: BTreeSet<String>,
dimension_families: BTreeSet<String>,
target: &Document,
cmd: &str,
) -> Result<CompositeImport> {
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
@@ -198,6 +238,20 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
target_taken.insert(font.name.to_lowercase());
target_taken.extend(font.part_fonts().map(str::to_lowercase));
}
// Families the source names without defining them as composite fonts, which the target does
// define: they stay undefined under a free name instead of taking the target's meaning.
let undefined: Vec<String> = source_families
.iter()
.filter(|family| !source_names.contains(*family) && !FontDb::global().has_installed_family(family))
.filter_map(|family| CompositeFont::named(&target.composite_fonts, family).map(|font| font.name.clone()))
.collect();
// Their alias may be a family the target's art already names without defining it, as an
// earlier placement of the same art left it, so that placement and this one share resources.
let mut alias_reserved = source_families.clone();
for font in source.iter().chain(target.composite_fonts.iter()) {
alias_reserved.insert(font.name.to_lowercase());
alias_reserved.extend(font.part_fonts().map(str::to_lowercase));
}
let mut reserved = source_families;
reserved.extend(target_families);
for font in source.iter().chain(target.composite_fonts.iter()) {
@@ -208,12 +262,15 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
let mut names = BTreeMap::new();
let mut combined = target.composite_fonts.to_vec();
for font in source {
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
let dimension = dimension_families.contains(&font.name.to_lowercase());
let equal = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
// A dimension keeps its own spelling of a reused name of the same font, so only an alias
// under another name has to fit the bytes its options keep.
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equal);
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
if needs_alias {
// A repeated import reuses its already-installed equal alias.
reused = target.composite_fonts.iter().find(equivalent);
reused = target.composite_fonts.iter().find(|other| equal(other) && (!dimension || other.name.len() <= ALIAS_BYTES_MAX));
}
let name = match reused {
Some(other) => other.name.clone(),
@@ -226,12 +283,18 @@ pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<
combined.push(CompositeFont { name, ..font });
}
}
alias_reserved.extend(names.values().map(|name| name.to_lowercase()));
for family in undefined {
let name = composite_alias(&family, &alias_reserved, cmd)?;
alias_reserved.insert(name.to_lowercase());
names.insert(family.to_lowercase(), name);
}
// A source document may currently lend fonts to the database. Validate the prospective
// document, not composite names temporarily registered by a different document.
if combined.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
if let Some(font) = combined.iter().skip(target.composite_fonts.len()).find(|font| db.has_installed_family(&font.name)) {
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
}
if CompositeFont::usable(&combined).is_some() {
+830
View File
@@ -0,0 +1,830 @@
//! Concept to Vector (`conceptVector.*`): vector variations of one selected image, made by a
//! provider ([`crate::concept_vector`]), compared, and inserted beside the image.
//!
//! `conceptVector.generate` asks the named provider for one variation per style and keeps them as a
//! job of this session; it changes nothing in the document. `conceptVector.insert` puts the chosen
//! variations to the right of the image as one undo step. A job is kept until it is canceled, its
//! document closes, or [`KEEP_JOBS`] newer ones replace it; it is never saved.
use std::collections::VecDeque;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
use vectorcraft_doc::{Appearance, ImageObject, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, Rect};
use super::buildcmds::TRACE_NAME;
use super::edit::selected_roots;
use super::pathops::shape_node;
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_id, cmd, has_doc, text_param};
use crate::concept_vector::{self as cv, MAX_STYLES, Output, Provider, ProviderError, Request, Variation};
/// The most jobs a session keeps; a new one drops the oldest.
pub const KEEP_JOBS: usize = 4;
/// The gap, in points, between the image and the first inserted variation, and between variations.
pub const GAP: f64 = 24.0;
/// A job's variations, or that it was canceled.
#[derive(Clone)]
enum Outcome {
Done(Arc<Vec<Variation>>),
Canceled,
}
/// What `conceptVector.generate` made, and what it was made of.
#[derive(Clone)]
pub(crate) struct Job {
id: u64,
/// The document ([`crate::DocState::uid`]) and the object (an image or an Image Trace object).
doc: u64,
source: NodeId,
image: ImageObject,
bytes: Arc<Vec<u8>>,
provider: String,
outcome: Outcome,
}
/// The session's providers and jobs.
pub(crate) struct ConceptState {
pub(crate) registry: cv::Registry,
jobs: VecDeque<Job>,
next: u64,
}
impl Default for ConceptState {
fn default() -> Self {
Self { registry: cv::Registry::default(), jobs: VecDeque::new(), next: 1 }
}
}
impl Session {
/// The Concept to Vector providers this session calls by id.
pub fn concept_providers(&self) -> &cv::Registry {
&self.concept.registry
}
/// The providers, to register another ([`cv::Registry::register`]).
pub fn concept_providers_mut(&mut self) -> &mut cv::Registry {
&mut self.concept.registry
}
/// Job `job`'s variations and the size in pixels of the image they were made of; `None` for a
/// job this session does not keep, or one that was canceled.
pub fn concept_variations(&self, job: u64) -> Option<(&[Variation], (u32, u32))> {
let j = self.concept.jobs.iter().find(|j| j.id == job)?;
match &j.outcome {
Outcome::Done(v) => Some((v.as_slice(), (j.image.width, j.image.height))),
Outcome::Canceled => None,
}
}
/// The document ([`crate::DocState::uid`]) job `job` was made in; `None` for a job this session
/// does not keep.
pub fn concept_job_doc(&self, job: u64) -> Option<u64> {
self.concept.jobs.iter().find(|j| j.id == job).map(|j| j.doc)
}
/// The jobs, for a batch to put back when a step fails. Job numbers are not reused.
pub(crate) fn concept_jobs_snapshot(&self) -> VecDeque<Job> {
self.concept.jobs.clone()
}
/// Puts back the jobs that [`Self::concept_jobs_snapshot`] took.
pub(crate) fn restore_concept_jobs(&mut self, jobs: VecDeque<Job>) {
self.concept.jobs = jobs;
}
/// Exchanges the jobs with `jobs`: a script works on a copy of them, which becomes the
/// session's only when the script ends without an error.
pub(crate) fn swap_concept_jobs(&mut self, jobs: &mut VecDeque<Job>) {
std::mem::swap(&mut self.concept.jobs, jobs);
}
/// The number the next job gets.
pub(crate) fn next_concept_job(&self) -> u64 {
self.concept.next
}
/// Takes in what the app did to the jobs while a script ran, `others` being the jobs as the app
/// left them: a job canceled there is canceled here too, and the jobs numbered `from` or higher
/// that this session does not keep (those the app made) are added. Then keeps the
/// [`KEEP_JOBS`] newest of open documents.
pub(crate) fn merge_concept_jobs(&mut self, others: VecDeque<Job>, from: u64) {
for j in others {
match self.concept.jobs.iter_mut().find(|k| k.id == j.id) {
Some(k) if matches!(j.outcome, Outcome::Canceled) => k.outcome = Outcome::Canceled,
Some(_) => {}
None if j.id >= from => self.concept.jobs.push_back(j),
None => {}
}
}
self.concept.jobs.make_contiguous().sort_by_key(|j| j.id);
self.prune_concept_jobs();
while self.concept.jobs.len() > KEEP_JOBS {
self.concept.jobs.pop_front();
}
}
/// Drops the jobs of document `doc` (its `uid`), when it closes.
pub(crate) fn forget_concept_jobs(&mut self, doc: u64) {
self.concept.jobs.retain(|j| j.doc != doc);
}
/// Drops the jobs whose document is closed.
/// In a batch, nothing is dropped until the batch ends without an error.
pub(crate) fn prune_concept_jobs(&mut self) {
if self.batch_stash.is_some() {
return;
}
let open: Vec<u64> = self.documents().iter().map(|d| d.uid).collect();
self.concept.jobs.retain(|j| open.contains(&j.doc));
}
}
/// The image `n` shows: its own, or the source image of an Image Trace object that wasn't expanded.
fn shown_image(n: &Node) -> Option<&ImageObject> {
match &shown_image_node(n)?.kind {
NodeKind::Image(i) => Some(i),
_ => None,
}
}
/// The image object [`shown_image`] reads: `n` itself, or the first member of its Image Trace object.
fn shown_image_node(n: &Node) -> Option<&Node> {
match &n.kind {
NodeKind::Image(_) => Some(n),
NodeKind::Group { clip: false, .. } if n.name.as_deref() == Some(TRACE_NAME) => {
n.children()?.first().map(|i| &**i).filter(|i| matches!(i.kind, NodeKind::Image(_)))
}
_ => None,
}
}
/// Is `n` a group whose members are made or placed from data it holds (a graph, an Objects on
/// Path, Shaper, dimension, flare or Live Paint group, a compound shape, a plug-in's generated
/// art), so that a member added to it would be placed again, replaced or combined with the others?
fn generated(n: &Node) -> bool {
let e = n.extras();
e.generated.is_some()
|| e.graph.is_some()
|| e.objects_on_path.is_some()
|| e.shaper.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.compound_shape
|| vectorcraft_tools::builder::is_live_paint(n)
}
const NO_SOURCE: &str = "select one image or an unexpanded Image Trace object";
const LOCKED: &str = "the image is locked or hidden";
/// The object `id` names, else the one selected: an image or an unexpanded Image Trace object,
/// shown and unlocked with every layer and group around it, and not on a locked artboard → it, its
/// image and the image's bytes.
fn source(s: &Session, c: &str, p: &Value) -> Result<(NodeId, ImageObject, Arc<Vec<u8>>)> {
let id = match p.get("id").filter(|v| !v.is_null()) {
Some(v) => checked_id(s, v, c)?,
None => match selected_roots(s)?.as_slice() {
[one] => *one,
_ => return Err(bad(c, NO_SOURCE)),
},
};
let d = &s.doc()?.doc;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let image = shown_image(n).ok_or_else(|| bad(c, NO_SOURCE))?;
if !d.is_editable(id) {
return Err(bad(c, LOCKED));
}
let blob = d.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
Ok((id, image.clone(), Arc::clone(&blob.bytes)))
}
/// A generation prepared from the session, which runs without it ([`ConceptRun::run`]), on any
/// thread, and is kept as a job with [`ConceptRun::finish`].
pub struct ConceptRun {
provider: Arc<dyn Provider>,
/// The provider's id, as it was registered.
provider_id: &'static str,
request: Request,
doc: u64,
source: NodeId,
image: ImageObject,
}
impl ConceptRun {
/// What `conceptVector.generate` with params `p` makes in the active document, checked as the
/// command checks it.
pub fn prepare(s: &Session, p: &Value) -> Result<ConceptRun> {
const C: &str = "conceptVector.generate";
let name = text_param(p, "provider", C)?.ok_or_else(|| bad(C, "missing `provider` (see conceptVector.providers)"))?;
let found =
s.concept.registry.get(name).ok_or_else(|| bad(C, format!("no Concept to Vector provider `{name}` (see conceptVector.providers)")))?;
let (caps, pid, provider) = (&found.capabilities, found.id, Arc::clone(&found.provider));
let styles_error = || bad(C, format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)"));
// The count is checked before any id is copied or scanned for repeats.
let styles: Vec<String> = match p.get("styles") {
Some(Value::Array(a)) if (1..=MAX_STYLES).contains(&a.len()) => {
a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<_>>().ok_or_else(styles_error)?
}
_ => return Err(styles_error()),
};
let known = |id: &String| caps.styles.iter().any(|st| st.id == id);
let unique = styles.iter().enumerate().all(|(i, id)| !styles.get(..i).unwrap_or_default().contains(id));
if !unique || !styles.iter().all(known) {
return Err(styles_error());
}
let prompt = text_param(p, "prompt", C)?.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);
// Results are vector paths, inserted as vector art, whatever else a provider makes.
let output = match text_param(p, "output", C)? {
None | Some("vector") => Output::Vector,
Some(_) => return Err(bad(C, "`output` must be \"vector\"")),
};
if !caps.image_input {
return Err(bad(C, format!("`{pid}` does not take an image")));
}
if !caps.vector_output {
return Err(bad(C, format!("`{pid}` does not make vector art")));
}
if prompt.is_some() && !caps.prompt {
return Err(bad(C, format!("`{pid}` takes no prompt")));
}
let detail = match p.get("detail") {
None => 50,
Some(v) => v.as_u64().filter(|d| *d <= 100).ok_or_else(|| bad(C, "`detail` must be a whole number from 0 to 100"))? as u8,
};
let (source, image, bytes) = source(s, C, p)?;
let request = Request { image: bytes, width: image.width, height: image.height, prompt, styles, detail, output };
Ok(ConceptRun { provider, provider_id: pid, request, doc: s.doc()?.uid, source, image })
}
/// The document it was prepared in ([`crate::DocState::uid`]).
pub fn doc(&self) -> u64 {
self.doc
}
/// The image or Image Trace object it makes variations of.
pub fn source(&self) -> NodeId {
self.source
}
/// Asks the provider for the variations and checks them ([`cv::check_result`]), telling `steps`
/// how far it has got; it touches no document. A panic in the provider is an error.
pub fn run(&self, steps: cv::Steps) -> std::result::Result<Vec<Variation>, ProviderError> {
let made = crate::guard::catch_panic(|| self.provider.generate(&self.request, steps)).map_err(ProviderError::Internal)??;
cv::check_result(&self.request, &made)?;
Ok(made)
}
/// How many styles it makes.
pub fn style_count(&self) -> usize {
self.request.styles.len()
}
/// Does the next part of the run kept in `run`, for a caller with no thread for
/// [`ConceptRun::run`] (the web build), which can run other work, or stop, between the parts
/// → whether every style is made ([`PartRun::made`]). A provider that makes parts
/// ([`cv::Provider::parts`]) does one of its own; the others make one style alone, and the
/// styles made so far are checked together ([`cv::check_result`]) after each one, so the
/// totals stop the run as soon as they are passed. A panic in the provider is an error.
pub fn run_part(&self, run: &mut PartRun, steps: cv::Steps) -> std::result::Result<bool, ProviderError> {
let guard = ProviderError::Internal;
if run.parts.is_none() {
run.parts = Some(crate::guard::catch_panic(|| self.provider.parts(&self.request)).map_err(guard)?);
}
if let Some(Some(parts)) = &mut run.parts {
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
if !steps(run.done as u64, self.style_count() as u64) {
return Err(ProviderError::Canceled);
}
let Some(made) = crate::guard::catch_panic(|| parts.step()).map_err(guard)?? else {
run.done = crate::guard::catch_panic(|| parts.styles_done()).map_err(guard)?;
return Ok(false);
};
cv::check_result(&self.request, &made)?;
run.made = made;
return Ok(true);
}
let Some(style) = self.request.styles.get(run.made.len()) else { return Ok(true) };
let one = Request { styles: vec![style.clone()], ..self.request.clone() };
let next = crate::guard::catch_panic(|| self.provider.generate(&one, steps)).map_err(guard)??;
cv::check_result(&one, &next)?;
// A style that takes the totals past their limits is dropped, so `run` keeps only the
// styles that passed.
let kept = run.made.len();
run.made.extend(next);
let so_far = Request { styles: self.request.styles.get(..run.made.len()).unwrap_or_default().to_vec(), ..one };
if let Err(e) = cv::check_result(&so_far, &run.made) {
run.made.truncate(kept);
return Err(e);
}
Ok(run.made.len() == self.request.styles.len())
}
/// Keeps `variations` as a new job of `s` → the job, as `conceptVector.results` gives it;
/// `None`, keeping nothing, when the document it was prepared in has closed.
pub fn finish(self, s: &mut Session, variations: Vec<Variation>) -> Option<Value> {
s.prune_concept_jobs();
if !s.documents().iter().any(|d| d.uid == self.doc) {
return None;
}
let id = s.concept.next;
s.concept.next += 1;
let job = Job {
id,
doc: self.doc,
source: self.source,
image: self.image,
bytes: self.request.image,
provider: self.provider_id.to_string(),
outcome: Outcome::Done(Arc::new(variations)),
};
let out = job_json(&s.concept.registry, &job);
s.concept.jobs.push_back(job);
while s.concept.jobs.len() > KEEP_JOBS {
s.concept.jobs.pop_front();
}
Some(out)
}
}
/// How far a run made a part at a time ([`ConceptRun::run_part`]) has got.
#[derive(Default)]
pub struct PartRun {
/// The provider's parts, once asked for (`None` inside: it makes one style at a time).
parts: Option<Option<Box<dyn cv::Parts>>>,
/// The styles the provider's parts had made when last asked, inside the panic guard.
done: usize,
made: Vec<Variation>,
}
impl PartRun {
/// The styles made so far.
pub fn styles_done(&self) -> usize {
if self.made.is_empty() { self.done } else { self.made.len() }
}
/// The variations made: all of them once [`ConceptRun::run_part`] has said so.
pub fn made(self) -> Vec<Variation> {
self.made
}
}
/// `e` as the engine's error.
pub fn provider_error(e: ProviderError) -> EngineError {
match e {
ProviderError::Canceled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
}
}
/// The English name of style `style` of provider `provider`, else the id.
fn style_label(registry: &cv::Registry, provider: &str, style: &str) -> String {
let caps = registry.get(provider).map(|p| &p.capabilities);
caps.and_then(|c| c.styles.iter().find(|s| s.id == style).map(|s| s.label.to_string())).unwrap_or_else(|| style.to_string())
}
/// Where `style` comes in the styles `provider` lists; after them when it lists no such style.
fn style_rank(registry: &cv::Registry, provider: &str, style: &str) -> usize {
let caps = registry.get(provider).map(|p| &p.capabilities);
caps.and_then(|c| c.styles.iter().position(|s| s.id == style)).unwrap_or(usize::MAX)
}
/// Where `image`'s pixels lie in the document.
fn image_rect(image: &ImageObject) -> Option<Rect> {
let r = Rect::new(0.0, 0.0, f64::from(image.width.max(1)), f64::from(image.height.max(1)));
let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| image.xf * kurbo::Point::new(x, y));
let mut out = Rect::from_points(pts[0], pts[0]);
for q in &pts[1..] {
out = out.union_pt(*q);
}
[out.x0, out.y0, out.x1, out.y1].iter().all(|v| v.is_finite()).then_some(out)
}
fn job_json(registry: &cv::Registry, j: &Job) -> Value {
let (state, variations) = match &j.outcome {
Outcome::Done(v) => ("done", v.as_slice()),
Outcome::Canceled => ("canceled", &[][..]),
};
let variations: Vec<Value> = variations
.iter()
.map(|v| {
let bounds = v.paths.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b));
json!({
"style": v.style,
"label": style_label(registry, &j.provider, &v.style),
"paths": v.paths.len(),
"anchors": v.anchors(),
"bounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]),
"warnings": v.warnings,
})
})
.collect();
json!({ "job": j.id, "provider": j.provider, "source": j.source.0, "state": state, "variations": variations })
}
/// The `job` param of command `c`.
fn job_param(c: &str, p: &Value) -> Result<u64> {
p.get("job").and_then(Value::as_u64).ok_or_else(|| bad(c, "`job` must be a job number from conceptVector.generate"))
}
/// The error of command `c` for a job the session does not keep.
fn no_job(c: &str, job: u64) -> EngineError {
bad(c, format!("no Concept to Vector job {job}: it was never made, or was dropped (see conceptVector.results)"))
}
/// The index of job `job` among those `s` keeps.
fn job_index(s: &mut Session, c: &str, job: u64) -> Result<usize> {
s.prune_concept_jobs();
s.concept.jobs.iter().position(|j| j.id == job).ok_or_else(|| no_job(c, job))
}
fn providers(s: &mut Session, _: &Value) -> Result<Value> {
let list: Vec<Value> = s
.concept
.registry
.iter()
.map(|p| {
let c = &p.capabilities;
json!({
"id": p.id,
"name": p.name,
"available": true,
"offline": c.offline,
"imageInput": c.image_input,
"vectorOutput": c.vector_output,
"prompt": c.prompt,
"rasterOutput": c.raster_output,
"maxStyles": MAX_STYLES,
"styles": c.styles,
})
})
.collect();
let selected = s.concept.registry.iter().next().map(|p| p.id);
Ok(json!({ "providers": list, "selected": selected }))
}
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
let run = ConceptRun::prepare(s, p)?;
// A script's run stops when the script is asked to stop, and keeps no job.
let stop = s.script_in_run.then(|| s.script_interrupt());
let stopped = || stop.as_ref().is_some_and(|i| i.is_set());
let made = run.run(&|_, _| !stopped()).map_err(provider_error)?;
if stopped() {
return Err(EngineError::Cancelled);
}
run.finish(s, made).ok_or(EngineError::NoDocument)
}
fn results(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.results";
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
Ok(job_json(&s.concept.registry, j))
}
/// The error of an insert or cancel played from recorded steps: a job lives only in this session,
/// and a job number from another one may name other results.
const REPLAYED: &str = "Concept to Vector jobs are not saved, so a recorded insert or cancel does not play again: generate again";
fn cancel(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.cancel";
if s.replaying() {
return Err(bad(C, REPLAYED));
}
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
if let Some(j) = s.concept.jobs.get_mut(at) {
j.outcome = Outcome::Canceled;
}
Ok(json!({ "job": job, "state": "canceled" }))
}
/// The appearance of variation path `p`, its widths scaled by `unit` (points per pixel).
fn appearance_of(p: &cv::VectorPath, unit: f64) -> Appearance {
let solid = |c: [u8; 3]| Paint::solid(Color::rgb8(c[0], c[1], c[2]));
let mut items = vec![];
if let Some(c) = p.fill {
items.push(AppearanceItem::Fill(FillLayer::new(solid(c))));
}
if let Some((c, w)) = p.stroke {
let cap = if p.square_caps { LineCap::Square } else { LineCap::Round };
items.push(AppearanceItem::Stroke(StrokeLayer { cap, join: LineJoin::Round, ..StrokeLayer::new(solid(c), w * unit) }));
}
Appearance { items, ..Default::default() }
}
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "conceptVector.insert";
if s.replaying() {
return Err(bad(C, REPLAYED));
}
let job = job_param(C, p)?;
let at = job_index(s, C, job)?;
let list_error = || bad(C, format!("`variations` must list different style ids of job {job}"));
let listed = match p.get("variations") {
Some(Value::Array(a)) if !a.is_empty() => a,
_ => return Err(list_error()),
};
let stale = || bad(C, format!("job {job} no longer applies: its document, image or image placement changed, so generate again"));
let (doc, source, image, bytes, picked, label_of) = {
let j = s.concept.jobs.get(at).ok_or_else(|| no_job(C, job))?;
let Outcome::Done(all) = &j.outcome else { return Err(bad(C, format!("job {job} has no results to insert: it was canceled"))) };
// The count is checked before the ids are read or scanned for repeats.
if listed.len() > all.len() {
return Err(list_error());
}
let chosen: Vec<&str> = listed.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(list_error)?;
let unique = chosen.iter().enumerate().all(|(i, id)| !chosen.get(..i).unwrap_or_default().contains(id));
let mut picked: Vec<Variation> = all.iter().filter(|v| chosen.contains(&v.style.as_str())).cloned().collect();
if !unique || picked.len() != chosen.len() {
return Err(list_error());
}
// In the provider's order, whatever order they were listed or generated in.
picked.sort_by_key(|v| style_rank(&s.concept.registry, &j.provider, &v.style));
let labels: Vec<String> = picked.iter().map(|v| style_label(&s.concept.registry, &j.provider, &v.style)).collect();
(j.doc, j.source, j.image.clone(), Arc::clone(&j.bytes), picked, labels)
};
// The same document, the same object showing the same pixels where they were.
let st = s.doc()?;
let now = st.doc.node(source).and_then(shown_image);
let same_pixels = || st.doc.images.get(&image.key).is_some_and(|b| Arc::ptr_eq(&b.bytes, &bytes) || *b.bytes == *bytes);
let current = st.uid == doc && now.is_some_and(|i| i.key == image.key && i.xf == image.xf && i.width == image.width && i.height == image.height);
if !current || !same_pixels() {
return Err(stale());
}
if !st.doc.is_editable(source) {
return Err(bad(C, LOCKED));
}
// The results go above the outermost group around the image that clips or masks it, so that
// it hides none of them, and above the outermost envelope, blend, repeat or other live object,
// the outermost group whose members it makes or places ([`generated`]), and the outermost
// group with effects or fills and strokes of its own, so that its content and the place its
// effects measure from stay as they are. A layer that clips or masks its art, or has effects,
// fills or strokes of its own, leaves them nowhere to go. An effect that moves or reshapes
// the image, its own or a group's around it, shows it away from its placement, which the
// results are placed by.
let ancestry = st.doc.ancestry(source).ok_or_else(stale)?;
let moves = |id: &NodeId| st.doc.node(*id).is_some_and(|n| !n.is_layer() && vectorcraft_render::effects::has_geometry(&n.appearance.effects));
if ancestry.iter().any(moves) {
return Err(bad(C, "the image or a group around it has effects that move or reshape it, so the results would not go beside it"));
}
// A distorted image ([`Node::image_quad`]) is drawn at its corners, not by its transform.
if st.doc.node(source).and_then(shown_image_node).is_some_and(Node::is_distorted_image) {
return Err(bad(C, "the image is distorted, so the results would not go beside it"));
}
let mut anchor = source;
for &id in ancestry.iter().rev().skip(1) {
let n = st.doc.node(id).ok_or_else(stale)?;
let masked = n.extras().mask.as_ref().is_some_and(|m| !m.disabled);
if matches!(n.kind, NodeKind::Layer { clip: true, .. }) {
return Err(bad(C, "the image is on a layer with a clipping mask, which would hide the results"));
}
if n.is_layer() && masked {
return Err(bad(C, "the image is on a layer with an opacity mask, which would hide the results"));
}
let styled = !n.appearance.items.is_empty() || !n.appearance.effects.is_empty();
if n.is_layer() && !n.appearance.effects.is_empty() {
return Err(bad(C, "the image is on a layer with effects of its own, which would apply to the results"));
}
// A layer's fills and strokes paint over its members, the results included.
if n.is_layer() && !n.appearance.items.is_empty() {
return Err(bad(C, "the image is on a layer with fills or strokes of its own, which would apply to the results"));
}
let live = !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || generated(n);
if !n.is_layer() && (masked || live || styled || matches!(n.kind, NodeKind::Group { clip: true, .. })) {
anchor = id;
}
}
let src = image_rect(&image).ok_or_else(stale)?;
// A variation with no paths adds nothing: it is left out, and with none left nothing changes.
let (picked, label_of): (Vec<Variation>, Vec<String>) = picked.into_iter().zip(label_of).filter(|(v, _)| !v.paths.is_empty()).unzip();
if picked.is_empty() {
return Ok(json!({ "ids": [] }));
}
let unit = image.xf.determinant().abs().sqrt();
// Each chosen variation's box over the image: the image's box and the variation's painted
// bounds, which may reach past it. A square cap's corner lies half the width along the path
// and half across it from the end, so up to √2 times half the width past it on an axis.
let boxes: Vec<Rect> = picked
.iter()
.map(|v| {
v.paths
.iter()
.filter_map(|vp| {
let reach = if vp.square_caps { std::f64::consts::SQRT_2 } else { 1.0 };
let half = vp.stroke.map_or(0.0, |(_, w)| w * unit / 2.0 * reach);
vp.path.transformed(image.xf).bounds().map(|b| b.inflate(half, half))
})
.fold(src, |a, b| a.union(b))
})
.collect();
// How far each variation's box is moved past the first's: each box starts GAP to the right of
// the one before it (`width + GAP` further right for boxes the image's size).
let mut offsets = Vec::with_capacity(boxes.len());
let mut next = 0.0;
for (k, b) in boxes.iter().enumerate() {
if let Some(prev) = k.checked_sub(1).and_then(|j| boxes.get(j)) {
next += prev.x1 - b.x0 + GAP;
}
offsets.push(next);
}
// The first box's left edge, which may lie left of the image's where its variation paints there.
let first = boxes.first().map_or(src.x0, |b| b.x0);
// The boxes with the first one's left edge moved to `x0`, the others after it.
let row = |x0: f64| -> Vec<Rect> {
boxes
.iter()
.zip(&offsets)
.map(|(b, off)| {
let dx = x0 + off - first;
Rect::new(b.x0 + dx, b.y0, b.x1 + dx, b.y1)
})
.collect()
};
// The painted bounds of every visible object (the source's too: an Image Trace object's traced
// art and effects can reach past the image), and the image's own box. A layer or group that
// paints nothing of its own is measured by its members (an opacity mask only hides them); one
// that clips, by its members after the clipping path, cut to what it paints.
let mut obstacles: Vec<Rect> = vec![src];
// One lookup of the symbols for the whole walk, so each symbol's art is measured once.
let symbols = st.doc.symbol_boxes();
let mut stack: Vec<(&Arc<Node>, Option<Rect>)> = st.doc.layers.iter().map(|l| (l, None)).collect();
while let Some((node, within)) = stack.pop() {
if !node.visible {
continue;
}
let cut = |b: Rect| match within {
Some(w) => Some(b.intersect(w)).filter(|i| i.width() > 0.0 && i.height() > 0.0),
None => Some(b),
};
let painted = || vectorcraft_render::painted_bounds_with(&symbols, node).and_then(cut);
if node.id == source {
obstacles.extend(painted());
continue;
}
let clips = matches!(node.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
let by_members = (node.is_layer() || matches!(node.kind, NodeKind::Group { .. }))
&& node.appearance.items.is_empty()
&& node.appearance.effects.is_empty();
if by_members {
// A clipping path paints its fills and strokes when they are set (`Node::clip_paint`),
// its strokes outside the clip too, whether or not it is shown.
if clips && let Some(path) = node.children().into_iter().flatten().next() {
let paint = path.clip_paint();
for part in [paint.fill, paint.stroke].into_iter().flatten() {
if let Some(b) = vectorcraft_render::painted_bounds_with(&symbols, &part).and_then(cut) {
obstacles.push(b);
}
}
}
let within = if clips {
// Nothing of a clipping group shows outside what it paints.
let Some(shown) = painted() else { continue };
Some(shown)
} else {
within
};
stack.extend(node.children().into_iter().flatten().skip(usize::from(clips)).map(|c| (c, within)));
} else if let Some(b) = painted() {
obstacles.push(b);
}
}
let placed = place_row(&row, src.x1 + GAP, &obstacles);
let room = || bad(C, "there is no room for the results to the right of the image");
let Some(x0) = placed.filter(|x0| x0.is_finite()) else {
return Err(room());
};
let right = row(x0).iter().map(|r| r.x1).fold(f64::NEG_INFINITY, f64::max);
if right > crate::MAX_COORD {
return Err(room());
}
let ids = s.edit("Concept to Vector", |d, sel| {
let mut groups = vec![];
for ((v, label), off) in picked.into_iter().zip(label_of).zip(&offsets) {
let dx = x0 + off - first;
let xf = Affine::translate((dx, 0.0)) * image.xf;
let mut members = Vec::with_capacity(v.paths.len());
for vp in &v.paths {
let path = vp.path.transformed(xf);
if path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().any(|c| c.abs() > crate::MAX_COORD)) {
return Err(room());
}
let mut node = shape_node(d, path, None);
node.appearance = appearance_of(vp, unit).into();
members.push(Arc::new(node));
}
let mut g = Node::group(d.alloc_id(), members);
g.name = Some(label);
groups.push(g);
}
let ids: Vec<NodeId> = groups.iter().map(|g| g.id).collect();
d.insert_beside(vec![(anchor, groups)], false)?;
sel.set(ids.iter().copied());
Ok(ids)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
#[cfg(test)]
thread_local! {
/// How many times [`place_row`] has looked at an object on this thread.
pub(crate) static LOOKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Where the left edge of the row's first box goes, from `start` rightward, so that no box meets
/// one of `obstacles`: a box in the way moves GAP past the rightmost object it meets. `row(x0)`
/// gives the boxes with the first one's left edge at `x0`. `None` when the moves run out.
pub(crate) fn place_row(row: &dyn Fn(f64) -> Vec<Rect>, start: f64, obstacles: &[Rect]) -> Option<f64> {
// Each box's objects: those level with it, by their left edges. The row only moves right, so
// each object joins its box's list once, when the box's right edge passes its left edge, and
// stays: of those joined, only the rightmost right edge matters, and the box meets that object
// exactly when the edge is right of the box's left edge.
let lanes: Vec<Vec<Rect>> = row(start)
.iter()
.map(|b| {
let mut lane: Vec<Rect> = obstacles.iter().filter(|o| o.y0 < b.y1 && b.y0 < o.y1).copied().collect();
lane.sort_by(|a, b| a.x0.total_cmp(&b.x0));
lane
})
.collect();
let mut joined = vec![0usize; lanes.len()];
let mut reach = vec![f64::NEG_INFINITY; lanes.len()];
let mut x0 = start;
// Each move takes a box past every object joined to it, so another move of that box needs a
// new object to join.
for _ in 0..=lanes.iter().map(Vec::len).sum::<usize>() {
let mut shift = None;
for ((r, lane), (j, far)) in row(x0).iter().zip(&lanes).zip(joined.iter_mut().zip(reach.iter_mut())) {
while let Some(o) = lane.get(*j).filter(|o| o.x0 < r.x1) {
#[cfg(test)]
LOOKS.with(|n| n.set(n.get() + 1));
*far = far.max(o.x1);
*j += 1;
}
// The first box in the way, moved past the rightmost object it meets.
if shift.is_none() && *far > r.x0 {
shift = Some(*far + GAP - r.x0);
}
}
match shift {
None => return Some(x0),
Some(by) => x0 += by,
}
}
None
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "conceptVector.providers",
"Concept to Vector Providers",
[],
None,
"{} → {providers: [{id, name, available, offline, imageInput, vectorOutput, prompt, rasterOutput, maxStyles: 8, styles: [{id, label}]}], selected: the id the panel uses} the providers conceptVector.generate can call by id; the built-in offline.traceStyles makes its styles with Image Trace on this computer (outline, inkLines, flatColor, detailedColor, grayTones), takes no prompt and makes vector art only",
always,
providers
),
cmd!(
query "conceptVector.generate",
"Generate Concept to Vector Styles",
[],
None,
"{id?: image or unexpanded Image Trace object (default: the one selected object), provider: id (conceptVector.providers; no other provider is used in its place), styles: [style id…] (1 to 8 different ids of that provider), detail?: 0-100 (50: how much of the image's detail each style keeps), prompt?: text (an error for a provider without prompts unless empty), output?: \"vector\" (the only output; any other value is an error)} one variation of the image for each style, kept by this session as a job and not put in the document; a provider that takes no image, makes no vector art or takes no prompt when one is given is refused with that reason; an object that is locked or hidden, itself or by a layer or group around it, or on a locked artboard, is refused → {job, provider, source: id, state: \"done\", variations: [{style, label, paths, anchors, bounds: [x0,y0,x1,y1] in the image's pixels, warnings: [text…]}]}",
has_doc,
generate
),
cmd!(
query "conceptVector.results",
"Concept to Vector Results",
[],
None,
"{job} a job conceptVector.generate made, as it returned it, or with state \"canceled\" and no variations; the session keeps the 4 newest jobs, until their document closes → {job, provider, source, state, variations}",
has_doc,
results
),
cmd!(
query "conceptVector.cancel",
"Cancel Concept to Vector Job",
[],
None,
"{job} drop a job's variations, so that it can't be inserted; canceling it again does the same; an error when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved → {job, state: \"canceled\"}",
has_doc,
cancel
),
cmd!(
"conceptVector.insert",
"Insert Concept to Vector Styles",
[],
None,
"{job, variations: [style id…] (different styles of the job)} put a group of each chosen variation, named after its style and in the provider's order, in a row to the right of the job's image, each the image's size with 24 pt between them, moved further right past other visible art in their way, where a variation reaches past its box too (the next one then starts 24 pt past what it paints); the groups go above the outermost clip group or opacity-masked group around the image, and above the outermost envelope, blend, repeat or other live object, the outermost group whose members it makes or places (a graph, an Objects on Path, Shaper, dimension, flare or Live Paint group, a compound shape) and the outermost group with effects or fills and strokes of its own around it; the image and other art stay as they are; one undo step; a variation with no paths is left out, and when every chosen one has none nothing changes (no undo step, ids []); an error when the job's document is not the active one, the object, its image or its placement changed, the object is now locked or hidden, or it is on a layer with a clipping mask, an opacity mask, or effects, fills or strokes of its own, or it or a group around it has effects that move or reshape it, or its image is distorted (Perspective Distort or Free Distort), and when it plays from recorded steps (an action, a replayed journal or a step of a replayed batch), since jobs are not saved →{ids: the groups, selected}",
has_doc,
insert
),
]
}
+41 -15
View File
@@ -65,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Star",
[],
None,
"{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
"{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}: a live star whose points and ratio object.setLiveShape changes",
has_doc,
star
),
@@ -174,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on. When new art's template is more than one plain fill and stroke (New Art Has Basic Appearance off) or comes from a graphic style picked with nothing selected, the type takes its fills, strokes and effects, and with Override Character Color on its characters lose the fill and stroke those paint (a `color` given keeps the fill); type with a style's look also takes the style's opacity and blend mode and is linked to it (in the document the style was picked in; elsewhere it is not linked), and its placed gradients fit the frame text wrap gives it",
has_doc,
text_create
),
@@ -255,6 +255,7 @@ fn insert_look_turned(
}
n.name = name;
n.bbox_angle = bbox_angle;
let pre = wrap_snapshot(d, &n, &look);
let mut into = None;
match (mode, inside) {
(crate::DrawMode::Inside, Some(target)) if d.node(target).is_some() => {
@@ -274,6 +275,7 @@ fn insert_look_turned(
d.insert(parent, usize::MAX, n)?;
}
}
place_after_wrap(d, pre, id, &look);
if select {
sel.set([id]);
}
@@ -655,14 +657,11 @@ fn star(s: &mut Session, p: &Value) -> Result<Value> {
let r2 = f64_or(p, "radius2", r1 / 2.0).abs();
let n = count_or(p, "points", 5, "shape.star")?.clamp(2, 1000) as u32;
let rot = f64_or(p, "rotation", 0.0);
let turn = vectorcraft_geom::rotate_deg(rot);
// A quarter or whole turn (a Constrain Angle of 90°, say) turns the upright star exactly.
let path = if rot != 0.0 && turn.as_coeffs()[..4].iter().all(|c| c.fract() == 0.0) {
shapes::star(Point::ZERO, r1, r2, n, 0.0).transformed(Affine::translate(c.to_vec2()) * turn)
} else {
shapes::star(c, r1, r2, n, rot)
};
add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot))
let xf = Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(rot);
// The star stays live: its point count and ratio can change later (`object.setLiveShape`).
let live = LiveShape::Star { r1, r2, points: n, xf, radii: vec![], kinds: vec![], radii_relative: false };
add_art_turned(s, "Star", path_kind(live.to_path(), Some(live)), constrained_turn(s, rot))
}
fn line(s: &mut Session, p: &Value) -> Result<Value> {
@@ -991,20 +990,42 @@ fn text_parent(s: &Session, p: &Value) -> Result<Option<NodeId>> {
}
/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected.
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result<Value> {
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, look: NewArt, bbox_angle: f64) -> Result<Value> {
let id = s.edit("Type", |d, sel| {
let id = d.alloc_id();
let mut n = Node::new(id, kind);
NewArt::plain(Appearance::default()).apply(d, &mut n);
look.apply(d, &mut n);
super::object::align_new_object(d, &mut n);
n.bbox_angle = bbox_angle;
let pre = wrap_snapshot(d, &n, &look);
d.insert(Some(parent), usize::MAX, n)?;
place_after_wrap(d, pre, id, &look);
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
/// The document before new type `n` goes in, when `look` places gradients on it: text wrap can
/// reflow the type once it is in ([`place_after_wrap`]).
fn wrap_snapshot(d: &vectorcraft_doc::Document, n: &Node, look: &NewArt) -> Option<vectorcraft_doc::Document> {
(matches!(n.kind, NodeKind::Text(_)) && look.places_gradients()).then(|| d.clone())
}
/// New type `id` just inserted into `d` (`pre`: `d` before, from [`wrap_snapshot`]): text wrap
/// reflows it now, and when that changes its bounds (an Auto Size frame below a wrap object grows),
/// `look`'s gradients are placed on the bounds it ends with.
fn place_after_wrap(d: &mut vectorcraft_doc::Document, pre: Option<vectorcraft_doc::Document>, id: NodeId, look: &NewArt) {
let Some(pre) = pre else { return };
let placed_on = d.node(id).and_then(Node::geometric_bounds);
super::textwrap::refresh(&pre, d);
if let Some(n) = d.node_mut(id)
&& n.geometric_bounds() != placed_on
{
look.place(n);
}
}
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let parent = text_parent(s, p)?;
let x = f64_req(p, "x", "text.create")?;
@@ -1043,11 +1064,16 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
// Lays the text out (and sizes an Auto Size frame).
super::typecmd::refresh_bounds(&mut t);
}
// New art's fills, strokes and effects (New Art Has Basic Appearance off, or a graphic style
// picked with nothing selected), with the characters' paint under Override Character Color as
// graphicStyle.apply gives type; a `color` given keeps the characters' fill.
let look = s.new_type_look();
if s.prefs.override_char_color {
super::style::override_text_chars(&mut t, &look.appearance, p.get("color").and_then(color_value).is_none());
}
let made = match parent {
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?,
None => {
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?
}
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), look, bbox_turn(rotation))?,
None => insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), look, None, true, bbox_turn(rotation), true)?,
};
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
+3 -1
View File
@@ -26,7 +26,9 @@ pub use perspective::perspective_click;
use perspective::{
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
};
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
pub(crate) use perspective::{
finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again,
};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -24,6 +24,37 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
}
/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it
/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the
/// changes [`silent`] makes without an undo step.
pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool {
let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY));
if a == b {
return false;
}
let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before));
g.visible = was.visible;
g.plane = was.plane;
g.inferred = was.inferred;
g.locked = was.locked;
g.lock_station = was.lock_station;
g.snap = was.snap;
g.rulers = was.rulers;
g.attached.clear();
was.attached.clear();
if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() {
return false;
}
let mut rest = now.clone();
let mut normalized_before = before.clone();
PerspectiveGrid::current(before).store(&mut normalized_before);
match normalized_before.unknown.get(persp::DOC_KEY) {
Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()),
None => rest.unknown.remove(persp::DOC_KEY),
};
rest == normalized_before
}
/// Change view state of the grid without an undo step.
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
let st = s.doc_mut()?;

Some files were not shown because too many files have changed in this diff Show More