mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 01:14:23 +01:00
Merge main into fix/symbol-drop-across-documents
This commit is contained in:
commit
ee10fbc9f6
322 files changed
+27239
-2196
No files matched your search
Generated
+39
-9
@@ -1204,9 +1204,19 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1214,6 +1224,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
@@ -1239,6 +1257,15 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
@@ -1253,7 +1280,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -2507,7 +2534,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -2516,7 +2543,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -2534,7 +2561,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -2552,12 +2579,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -3357,7 +3384,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -3466,7 +3493,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6701,6 +6728,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-plotter",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde_json",
|
||||
@@ -6856,6 +6884,7 @@ dependencies = [
|
||||
"craft-eps",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-pdf",
|
||||
"craft-ps",
|
||||
"craft-stream-codecs",
|
||||
"encoding_rs",
|
||||
"fax",
|
||||
@@ -7088,6 +7117,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)",
|
||||
"craft-mime",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
"flate2",
|
||||
|
||||
+12
-9
@@ -11,7 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", default-features = false, features = ["interpret", "write"] }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] }
|
||||
@@ -28,9 +28,11 @@ craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "431f704478962677ec47e512754464d372901830", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
@@ -38,8 +40,9 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a93
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] }
|
||||
# internal
|
||||
@@ -181,13 +184,13 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
|
||||
@@ -137,6 +137,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
|
||||
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
|
||||
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
|
||||
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(windows)]
|
||||
use super::windows_screen_color;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
@@ -354,7 +356,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
@@ -413,6 +415,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
#[cfg(windows)]
|
||||
screen_color: Some(windows_screen_color::sampler(sampled_ui)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -77,6 +77,7 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_screen_color;
|
||||
mod windows_stylus;
|
||||
mod xwayland;
|
||||
|
||||
@@ -590,14 +591,15 @@ fn main() -> std::process::ExitCode {
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
let hint = if chosen_gpu {
|
||||
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
));
|
||||
} else {
|
||||
""
|
||||
};
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
|
||||
));
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
|
||||
));
|
||||
}
|
||||
} else if let Some(crash) = &crash {
|
||||
app.status(match crash {
|
||||
gpu::Crash::Adapter { name, .. } => format!(
|
||||
|
||||
@@ -54,6 +54,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) ->
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
@@ -9,9 +9,8 @@ impl PrintService for SystemPrint {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,6 +28,15 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
@@ -38,7 +46,7 @@ mod system {
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +135,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -0,0 +1,655 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-dxf = { workspace = true }
|
||||
craft-plotter = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
|
||||
+2
-428
@@ -1,428 +1,2 @@
|
||||
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
|
||||
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
|
||||
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
|
||||
//! with the data their escapes carry.
|
||||
|
||||
/// The end-of-text character, the default label terminator.
|
||||
pub(super) const ETX: u8 = 3;
|
||||
const ESC: u8 = 0x1b;
|
||||
|
||||
/// The most digits of a number that count: longer ones are read as their first digits.
|
||||
const MAX_DIGITS: usize = 18;
|
||||
|
||||
/// What the bytes being read hold.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
/// HP-GL instructions.
|
||||
Hpgl,
|
||||
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
|
||||
Pcl,
|
||||
/// After a Universal Exit Language: PJL lines until a language starts.
|
||||
Pjl,
|
||||
}
|
||||
|
||||
/// One item of a PE (Polyline Encoded) instruction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum PeItem {
|
||||
/// Select pen.
|
||||
Pen(i64),
|
||||
/// Rectangle mode: the following coordinates come in fours.
|
||||
Rect,
|
||||
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
|
||||
Point { x: f64, y: f64, up: bool, absolute: bool },
|
||||
}
|
||||
|
||||
/// The state of one PE instruction being read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct Pe {
|
||||
seven_bit: bool,
|
||||
fraction_bits: u32,
|
||||
up: bool,
|
||||
absolute: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Lexer<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
mode: Mode,
|
||||
/// The file holds HP RTL or PCL raster image data.
|
||||
pub raster: bool,
|
||||
}
|
||||
|
||||
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
|
||||
fn separator(c: u8) -> bool {
|
||||
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.at).copied()
|
||||
}
|
||||
|
||||
/// Whether everything has been read.
|
||||
pub fn done(&self) -> bool {
|
||||
self.at >= self.b.len()
|
||||
}
|
||||
|
||||
/// How many bytes have been read.
|
||||
pub fn pos(&self) -> usize {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
|
||||
/// escape sequences may come before it (anything else gives `None`, as the end does).
|
||||
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if c == ESC {
|
||||
self.escape();
|
||||
continue;
|
||||
}
|
||||
match self.mode {
|
||||
Mode::Pcl => {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
Mode::Pjl => {
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c == b'@' {
|
||||
self.pjl_line();
|
||||
} else {
|
||||
self.mode = Mode::Hpgl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Mode::Hpgl => {}
|
||||
}
|
||||
let next = self.b.get(self.at + 1).copied();
|
||||
if c.is_ascii_alphabetic()
|
||||
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
|
||||
{
|
||||
self.at += 2;
|
||||
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
|
||||
}
|
||||
if strict && !(separator(c) || c == b';' || c < 0x20) {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
|
||||
fn pjl_line(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
|
||||
// A command names its language within its first 256 bytes; longer lines aren't copied.
|
||||
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
|
||||
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
|
||||
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
|
||||
}
|
||||
self.at += end;
|
||||
}
|
||||
|
||||
/// An escape sequence at the current byte, with the data it carries.
|
||||
fn escape(&mut self) {
|
||||
self.at += 1;
|
||||
let Some(c) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
match c {
|
||||
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
|
||||
// `ESC%#A` to PCL or HP RTL).
|
||||
b'%' => {
|
||||
let (_, end) = self.value();
|
||||
match end {
|
||||
Some(b'X') => self.mode = Mode::Pjl,
|
||||
Some(b'B') => self.mode = Mode::Hpgl,
|
||||
Some(b'A') => self.mode = Mode::Pcl,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Reset: PCL follows, until a language switch.
|
||||
b'E' => self.mode = Mode::Pcl,
|
||||
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
|
||||
b'.' => {
|
||||
let Some(kind) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
if !b"()YZBEJKLORUX".contains(&kind) {
|
||||
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
|
||||
if let Some(n) = rest.iter().position(|&c| c == b':')
|
||||
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
|
||||
{
|
||||
self.at += n + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parameterized PCL: a group character, then values each ending in a letter (upper case
|
||||
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
|
||||
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
|
||||
// `ESC)0N`), one value and the letter ending it.
|
||||
0x21..=0x2f => {
|
||||
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
|
||||
self.value();
|
||||
return;
|
||||
};
|
||||
self.at += 1;
|
||||
loop {
|
||||
let (v, end) = self.value();
|
||||
let Some(end) = end else { return };
|
||||
let upper = end.to_ascii_uppercase();
|
||||
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
|
||||
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
|
||||
if (c, group) == (b'*', b'b') && n > 0 {
|
||||
self.raster = true;
|
||||
}
|
||||
self.at += n;
|
||||
}
|
||||
if (c, group, end) == (b'*', b'r', b'A') {
|
||||
self.raster = true;
|
||||
}
|
||||
if !end.is_ascii_lowercase() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A two-character escape.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
|
||||
/// when that is not a letter or `@` (which is then left unread).
|
||||
fn value(&mut self) -> (f64, Option<u8>) {
|
||||
let v = self.number_here().unwrap_or(0.0);
|
||||
match self.peek() {
|
||||
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
|
||||
self.at += 1;
|
||||
(v, Some(c))
|
||||
}
|
||||
_ => (v, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
|
||||
/// (its sign and point are read all the same).
|
||||
fn number_here(&mut self) -> Option<f64> {
|
||||
let mut neg = false;
|
||||
if let Some(c @ (b'+' | b'-')) = self.peek() {
|
||||
neg = c == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
|
||||
let mut point = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
if digits < MAX_DIGITS {
|
||||
if point {
|
||||
scale /= 10.0;
|
||||
v += f64::from(c - b'0') * scale;
|
||||
} else {
|
||||
v = v * 10.0 + f64::from(c - b'0');
|
||||
}
|
||||
} else if !point {
|
||||
// Past the digits that count, an integer part keeps its size.
|
||||
v *= 10.0;
|
||||
}
|
||||
digits += 1;
|
||||
} else if c == b'.' && !point {
|
||||
point = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
let v = v.min(f64::MAX);
|
||||
(digits > 0).then_some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
|
||||
/// ending it is read).
|
||||
pub fn number(&mut self) -> Option<f64> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
|
||||
if let Some(v) = self.number_here() {
|
||||
return Some(v);
|
||||
}
|
||||
} else {
|
||||
if c == b';' {
|
||||
self.at += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
|
||||
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
|
||||
let mut n = 0;
|
||||
while let Some(v) = self.number() {
|
||||
if let Some(slot) = out.get_mut(n) {
|
||||
*slot = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
n.min(out.len())
|
||||
}
|
||||
|
||||
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
|
||||
pub fn params(&mut self) {
|
||||
loop {
|
||||
while self.number().is_some() {}
|
||||
if self.peek() != Some(b'"') {
|
||||
return;
|
||||
}
|
||||
self.quoted();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
|
||||
/// doesn't know, written out in full).
|
||||
pub fn closed_params(&mut self) -> bool {
|
||||
while self.number().is_some() {}
|
||||
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
|
||||
}
|
||||
|
||||
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
|
||||
/// is one.
|
||||
pub fn comment(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => self.quoted(),
|
||||
Some(b';') => {
|
||||
self.at += 1;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a label, up to and including `terminator` (or the end).
|
||||
pub fn label(&mut self, terminator: u8) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
|
||||
/// there was one.
|
||||
pub fn quoted(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
let found = self.peek() == Some(b'"');
|
||||
if found {
|
||||
self.at += 1;
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
if self.peek() == Some(b';') {
|
||||
self.at += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
|
||||
/// (the semicolon is read).
|
||||
pub fn char(&mut self) -> Option<u8> {
|
||||
let c = self.peek()?;
|
||||
self.at += 1;
|
||||
(c != b';').then_some(c)
|
||||
}
|
||||
|
||||
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
|
||||
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = raw & 0x7f;
|
||||
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b';' => {
|
||||
self.at += 1;
|
||||
return None;
|
||||
}
|
||||
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
|
||||
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
|
||||
self.at += 1;
|
||||
match c {
|
||||
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
|
||||
b'<' => st.up = true,
|
||||
b'>' => match self.pe_value(st) {
|
||||
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
|
||||
None => return self.end_pe(),
|
||||
},
|
||||
b'=' => st.absolute = true,
|
||||
b'7' => st.seven_bit = true,
|
||||
_ => return Some(PeItem::Rect),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let scale = 0.5f64.powi(st.fraction_bits as i32);
|
||||
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
|
||||
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
|
||||
(st.up, st.absolute) = (false, false);
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
|
||||
fn end_pe(&mut self) -> Option<PeItem> {
|
||||
self.skip_pe();
|
||||
None
|
||||
}
|
||||
|
||||
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
|
||||
/// read as instructions.
|
||||
pub fn skip_pe(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
|
||||
/// digit comes first, which is read).
|
||||
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
|
||||
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
|
||||
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
|
||||
let (mut v, mut place) = (0u64, 1u64);
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = if st.seven_bit { raw & 0x7f } else { raw };
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b';' {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
let (digit, last) = if low.contains(&c) {
|
||||
(u64::from(c - 63), false)
|
||||
} else if high.contains(&c) {
|
||||
(u64::from(c - high.start()), true)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
v = v.saturating_add(digit.saturating_mul(place));
|
||||
place = place.saturating_mul(base);
|
||||
if last {
|
||||
// The low bit is the sign.
|
||||
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
|
||||
return Some(if v & 1 == 1 { -n } else { n });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//! Shared HP-GL byte lexer; drawing interpretation remains local.
|
||||
pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem};
|
||||
@@ -294,13 +294,19 @@ impl GuideOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
|
||||
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
|
||||
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
|
||||
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
|
||||
}
|
||||
|
||||
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
|
||||
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
|
||||
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
|
||||
if step == 0 {
|
||||
return c;
|
||||
}
|
||||
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
|
||||
let f = step_fraction(opts, step);
|
||||
let v = match opts.variation {
|
||||
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
|
||||
Variation::WarmCool => {
|
||||
|
||||
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
let stop = |&(t, c, o): &(f32, Color, f32)| {
|
||||
let at = if mirrored { 1.0 - t } else { t };
|
||||
format!("{} {}%", css_color(&c, o), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
// Stops that repeat or reflect run that many times across the box. CSS mixes
|
||||
// hex colors evenly in sRGB between two stops
|
||||
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
|
||||
// midpoint and the curve of a Perceptual or hue gradient are written as stops
|
||||
// of their own, each with its color and opacity. A gradient that would need
|
||||
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
|
||||
unrolled.expanded_stops()
|
||||
} else {
|
||||
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
|
||||
};
|
||||
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
|
||||
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
|
||||
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
|
||||
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
|
||||
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
|
||||
/// last the end colors hold.
|
||||
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
|
||||
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
|
||||
let stops: Vec<([f64; 3], f64, f64)> = list
|
||||
.split(", ")
|
||||
.map(|stop| {
|
||||
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
|
||||
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
|
||||
let at: f64 = at.trim_end_matches('%').parse().unwrap();
|
||||
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
|
||||
})
|
||||
.collect();
|
||||
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
|
||||
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
|
||||
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
|
||||
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
|
||||
let a = a0 + (a1 - a0) * w;
|
||||
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
|
||||
(c, a)
|
||||
}
|
||||
|
||||
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
|
||||
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
|
||||
/// own, also on a reflected and a mirrored conic swatch.
|
||||
#[test]
|
||||
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
|
||||
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
|
||||
for i in 0..64 {
|
||||
let p = (f64::from(i) + 0.5) / 64.0;
|
||||
let (css, css_alpha) = css_gradient_at(value, p);
|
||||
let (color, opacity) = gp.gradient.sample(at(p) as f32);
|
||||
let want = color.to_rgb();
|
||||
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
|
||||
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
|
||||
}
|
||||
};
|
||||
let ramp = |method| Gradient {
|
||||
method,
|
||||
..Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
|
||||
)
|
||||
};
|
||||
for method in crate::GradientMethod::ALL {
|
||||
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
|
||||
}
|
||||
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
|
||||
let fade = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
|
||||
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
|
||||
],
|
||||
);
|
||||
check("fade", GradientPaint::new(fade), &|p| p);
|
||||
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
|
||||
let spread = reflected.spreader();
|
||||
check("reflect", GradientPaint::new(reflected), &spread);
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
check("mirrored conic", conic, &|p| 1.0 - p);
|
||||
}
|
||||
|
||||
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
|
||||
/// own stops.
|
||||
#[test]
|
||||
fn css_gradient_swatches_keep_their_stop_count_bounded() {
|
||||
let n = 4000;
|
||||
let stops = (0..n)
|
||||
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
|
||||
.collect();
|
||||
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
|
||||
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
|
||||
}
|
||||
|
||||
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
|
||||
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
|
||||
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
|
||||
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
|
||||
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
|
||||
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
|
||||
let rail = Rail::new(keys, spec);
|
||||
keys.windows(2).enumerate().all(|(i, w)| {
|
||||
let [a, b] = w else { return true };
|
||||
match spec.spacing {
|
||||
BlendSpacing::Steps(_) => true,
|
||||
// The count is `len / d` rounded, which grows with `len`.
|
||||
BlendSpacing::Distance(d) => {
|
||||
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
|
||||
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
|
||||
count(len - length) == count(len + length)
|
||||
}
|
||||
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
|
||||
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
|
||||
/// between their edges in key sizes), so the pair is settled when the least and the most of
|
||||
/// these ask for the same count.
|
||||
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ, but by too little to count, or by little more: moving them may cross
|
||||
// where they stop counting as the same. (The same colors stay the same.)
|
||||
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach =
|
||||
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
// The centers and sizes move by up to twice `length`.
|
||||
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
|
||||
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
|
||||
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
|
||||
reach.is_finite() && least == most
|
||||
}
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
|
||||
(_, Some((ba, bb))) => {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
if w <= 4.0 * length || h <= 4.0 * length {
|
||||
return false;
|
||||
}
|
||||
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
|
||||
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
|
||||
// Each edge moves by up to `length`: the distances between them by up to twice that,
|
||||
// and the mean sizes too.
|
||||
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
|
||||
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
|
||||
let m = 2.0 * length;
|
||||
let least = q(dx - m, dy - m, w + m, h + m);
|
||||
let most = q(dx + m, dy + m, w - m, h - m);
|
||||
least.is_finite() && most.is_finite() && count(least) == count(most)
|
||||
}
|
||||
(_, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
|
||||
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
|
||||
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
@@ -3535,4 +3599,46 @@ mod tests {
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
|
||||
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
|
||||
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
|
||||
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
|
||||
/// color difference or the keys' reach sits where its count changes, or keys of the same color
|
||||
/// are at most four times 0.01 pt wide.
|
||||
#[test]
|
||||
fn steps_settle_unless_rounding_can_change_their_count() {
|
||||
let (length, color) = (0.01, 0.001);
|
||||
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
|
||||
let spec = BlendSpec { spacing, ..Default::default() };
|
||||
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
|
||||
};
|
||||
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
|
||||
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
|
||||
|
||||
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
|
||||
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
|
||||
|
||||
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
|
||||
// (settled) and by 51.5 (where the count changes).
|
||||
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
|
||||
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
|
||||
// 10.0625 pt (80.5 steps) is not.
|
||||
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
|
||||
assert!(near(10.0));
|
||||
assert!(!near(10.0625));
|
||||
// Keys without bounds are counted by their colors alone.
|
||||
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
|
||||
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
|
||||
// are never settled.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
}
|
||||
}
|
||||
+107
-16
@@ -15,7 +15,8 @@ use crate::{AppearanceItem, Document, Node, NodeKind};
|
||||
pub struct Inks {
|
||||
/// Process inks C, M, Y, K (0..1).
|
||||
pub cmyk: [f32; 4],
|
||||
/// Spot ink (swatch name, tint 0..1).
|
||||
/// Spot ink (swatch name, tint 0..1). A spot ink named like a process plate ("Cyan",
|
||||
/// "Magenta", "Yellow", "Black") prints on that plate: its tint is in `cmyk` too.
|
||||
pub spot: Option<(String, f32)>,
|
||||
/// Registration: the tint (every process ink's) prints on every spot plate too.
|
||||
pub registration: bool,
|
||||
@@ -49,7 +50,20 @@ pub struct Plate {
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch.
|
||||
/// Spot swatch `name` as art links to it: [`Document::swatch`] `name` when that is a spot swatch of
|
||||
/// a solid colour.
|
||||
fn spot_swatch<'a>(doc: &'a Document, name: &str) -> Option<&'a vectorcraft_color::Swatch> {
|
||||
doc.swatch(name).filter(|s| s.spot && s.paint.color().is_some())
|
||||
}
|
||||
|
||||
/// The index in [`PROCESS_PLATES`] of the process plate named `name`.
|
||||
fn process_plate(name: &str) -> Option<usize> {
|
||||
PROCESS_PLATES.iter().position(|p| *p == name)
|
||||
}
|
||||
|
||||
/// The plates of `doc`: the four process plates plus one per spot swatch that art can link to. A
|
||||
/// link names a swatch, which is the first swatch of that name ([`Document::swatch`]), so a spot
|
||||
/// swatch after another of its name, or named like a process plate, gets no plate.
|
||||
pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let mut v: Vec<Plate> = PROCESS_PLATES
|
||||
@@ -61,20 +75,29 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
|
||||
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
|
||||
})
|
||||
.collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for sw in doc.swatches_iter() {
|
||||
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
|
||||
&& !v.iter().any(|p| p.name == sw.name)
|
||||
// Only the first swatch of a name is the one [`spot_swatch`] finds.
|
||||
if !seen.insert(sw.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let (true, Some(color)) = (sw.spot, sw.paint.color())
|
||||
&& !PROCESS_PLATES.contains(&sw.name.as_str())
|
||||
{
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
|
||||
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
|
||||
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
|
||||
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
|
||||
/// prints on that plate.
|
||||
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
let s = doc.swatch(name).filter(|s| s.spot)?;
|
||||
s.paint.color().map(|c| doc.linked_color(c, true))
|
||||
if process_plate(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
|
||||
}
|
||||
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
@@ -86,16 +109,22 @@ fn ink_amount(v: f32) -> f32 {
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
|
||||
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
|
||||
/// tint on every plate. A tint that is not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
&& spot_swatch(doc, name).is_some()
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
|
||||
let tint = ink_amount(tint);
|
||||
let mut cmyk = [0.0; 4];
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = tint;
|
||||
}
|
||||
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -106,11 +135,18 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
|
||||
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
|
||||
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
|
||||
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
|
||||
/// prints as [`inks`] separates it. A spot ink named like a process plate prints its tint layered
|
||||
/// over that plate's amount; EPS export can't write that ink beside process plates in one DeviceN
|
||||
/// space, so it writes such a gradient in process colors with a warning. A plate amount that is
|
||||
/// not a finite number prints no ink.
|
||||
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
|
||||
let mut ink = inks(doc, c, color, link, intent);
|
||||
if let (Some(p), Some(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
if let (Some(p), Some((name, tint))) = (plates, &ink.spot) {
|
||||
let mut cmyk = p.map(ink_amount);
|
||||
if let Some(i) = process_plate(name) {
|
||||
cmyk[i] = 1.0 - (1.0 - cmyk[i]) * (1.0 - tint);
|
||||
}
|
||||
ink.cmyk = cmyk;
|
||||
}
|
||||
ink
|
||||
}
|
||||
@@ -201,7 +237,7 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{NodeId, SymbolOverride};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
|
||||
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch, SwatchGroup};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
/// A document with spot swatch `Gold` and process swatch `Teal`.
|
||||
@@ -233,6 +269,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of `doc`'s spot plates, in order.
|
||||
fn spot_plates(doc: &Document) -> Vec<String> {
|
||||
plates(doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_an_earlier_process_swatch_gets_no_plate() {
|
||||
// Art links to a swatch by name, which finds the earlier process `Teal`: the later spot
|
||||
// `Teal` in a colour group prints nothing, so it gets no plate.
|
||||
let mut d = gold_doc();
|
||||
let spot_teal = Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.9, 0.0, 0.4, 0.0)), global: true, spot: true };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![spot_teal.clone()] });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.8, 0.0, 0.3, 0.0);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 1.0)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: c.to_cmyk(&look, Intent::RelativeColorimetric), spot: None, registration: false });
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Teal", 1.0)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!(stop, teal, "a gradient stop linked to it separates as process too");
|
||||
assert_eq!(spot_color(&d, "Teal"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"], "no plate for the spot swatch that no art reaches");
|
||||
// The first swatch of a name decides either way: a spot swatch first gets its plate, and a
|
||||
// later process swatch of the same name does not take it away.
|
||||
let mut d = gold_doc();
|
||||
d.swatches.retain(|s| s.name != "Teal");
|
||||
d.swatches.insert(0, spot_teal);
|
||||
let process_teal = Swatch { name: "Teal".into(), paint: Paint::solid(look), global: true, spot: false };
|
||||
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![process_teal] });
|
||||
assert_eq!(spot_plates(&d), ["Teal", "Gold"]);
|
||||
let teal = inks(&d, &c, &look, Some(("Teal", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(teal, Inks { cmyk: [0.0; 4], spot: Some(("Teal".into(), 0.5)), registration: false });
|
||||
assert_eq!(spot_color(&d, "Teal"), Some(Color::cmyk(0.9, 0.0, 0.4, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_swatch_named_like_a_process_plate_prints_on_that_plate() {
|
||||
// A spot `Cyan` has the process Cyan plate's name, so art linked to it prints its tint on
|
||||
// that plate, as a Separation ink named `Cyan` in PDF and EPS export does, instead of a
|
||||
// spot amount that no plate prints.
|
||||
let mut d = gold_doc();
|
||||
let blue = Color::cmyk(1.0, 0.3, 0.0, 0.1);
|
||||
d.swatches.insert(0, Swatch { name: "Cyan".into(), paint: Paint::solid(blue), global: true, spot: true });
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let ink = inks(&d, &c, &blue, Some(("Cyan", 0.5)), Intent::RelativeColorimetric);
|
||||
assert_eq!(ink, Inks { cmyk: [0.5, 0.0, 0.0, 0.0], spot: Some(("Cyan".into(), 0.5)), registration: false });
|
||||
assert_eq!((ink.on_plate("Cyan"), ink.on_plate("Magenta"), ink.on_plate("Gold")), (0.5, 0.0, 0.0));
|
||||
let nan = inks(&d, &c, &blue, Some(("Cyan", f32::NAN)), Intent::RelativeColorimetric);
|
||||
assert_eq!(nan.cmyk, [0.0; 4], "a tint that is not a number prints no ink");
|
||||
// A gradient stop's own process plates still print, with the tint layered over its Cyan.
|
||||
let stop = stop_inks(&d, &c, &blue, Some(("Cyan", 0.5)), Some([0.2, 0.4, 0.0, 0.0]), Intent::RelativeColorimetric);
|
||||
assert!((stop.on_plate("Cyan") - 0.6).abs() < 1e-6, "{stop:?}");
|
||||
assert_eq!((stop.on_plate("Magenta"), stop.on_plate("Yellow"), stop.on_plate("Black")), (0.4, 0.0, 0.0));
|
||||
assert_eq!(spot_color(&d, "Cyan"), None);
|
||||
assert_eq!(spot_plates(&d), ["Gold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
let d = gold_doc();
|
||||
|
||||
+27
-1
@@ -65,7 +65,9 @@ pub use expand::{
|
||||
#[cfg(test)]
|
||||
use mesh::grid_eval;
|
||||
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
|
||||
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
|
||||
pub use warp::{
|
||||
WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -88,6 +90,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The smooth map takes each handle along the map's derivative, also far from the origin,
|
||||
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
|
||||
/// handles there.
|
||||
#[test]
|
||||
fn map_smooth_within_keeps_handles_far_from_the_origin() {
|
||||
for at in [0.0, 1e13] {
|
||||
let o = Point::new(at, at);
|
||||
let curve = PathData::single(vectorcraft_geom::SubPath::new(
|
||||
vec![
|
||||
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
|
||||
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
|
||||
),
|
||||
],
|
||||
false,
|
||||
));
|
||||
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
|
||||
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
|
||||
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
|
||||
}
|
||||
}
|
||||
|
||||
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
|
||||
/// down to one a segment, and matches the plain map where the budget leaves room.
|
||||
#[test]
|
||||
|
||||
@@ -497,6 +497,37 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
|
||||
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
|
||||
/// mapped as points point different ways on the two sides of a join and the curve kinks there
|
||||
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
|
||||
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
|
||||
}
|
||||
|
||||
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
|
||||
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
|
||||
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
|
||||
let v = h - p;
|
||||
let len = v.hypot();
|
||||
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
|
||||
if len.is_nan() || len <= 0.0 || len.is_infinite() {
|
||||
return f(p);
|
||||
}
|
||||
// A thousandth of the handle, or more where the coordinates are so large that so short a
|
||||
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
|
||||
// at most at the handle's own end.
|
||||
let size = p.x.abs().max(p.y.abs()).max(1.0);
|
||||
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
|
||||
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
|
||||
f(p) + d
|
||||
}
|
||||
|
||||
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
|
||||
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
@@ -516,20 +547,20 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
last.h_out = handle(sub.p0, sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
pending_in = Some(handle(sub.p3, sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+119
-7
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
@@ -46,14 +46,21 @@ impl Default for OverprintBlack {
|
||||
}
|
||||
|
||||
impl OverprintBlack {
|
||||
/// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), or a gradient whose every stop is.
|
||||
/// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with
|
||||
/// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points
|
||||
/// whose every point is (it draws from its points, not its stops).
|
||||
fn black(&self, p: &Paint, spots: &[String]) -> bool {
|
||||
let ink = |color: &Color, swatch: &Option<String>| {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
};
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => {
|
||||
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
|
||||
}
|
||||
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
|
||||
Paint::Solid { color, swatch, .. } => ink(color, swatch),
|
||||
// Only a freeform gradient draws its points; another kind draws its stops whatever it holds.
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)),
|
||||
// Without points of its own a freeform gradient places them from its stops.
|
||||
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)),
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -85,6 +92,52 @@ impl OverprintBlack {
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
|
||||
/// that change. Returns whether anything changed.
|
||||
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
|
||||
match self.marked(a, spots) {
|
||||
Some(n) => {
|
||||
*a = n;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None`
|
||||
/// otherwise). Each node is visited once, and only the nodes on the way to a change are copied.
|
||||
fn marked(&self, n: &Arc<Node>, spots: &[String]) -> Option<Arc<Node>> {
|
||||
let members: Vec<(usize, Arc<Node>)> =
|
||||
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect();
|
||||
if members.is_empty() && !self.changes(n, spots) {
|
||||
return None;
|
||||
}
|
||||
let mut copy = Arc::clone(n);
|
||||
let m = Arc::make_mut(&mut copy);
|
||||
self.apply(m, spots);
|
||||
if let Some(children) = m.children_mut() {
|
||||
for (i, c) in members {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(copy)
|
||||
}
|
||||
|
||||
/// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself.
|
||||
fn changes(&self, n: &Node, spots: &[String]) -> bool {
|
||||
let on = !self.remove;
|
||||
let item = |it: &crate::AppearanceItem| {
|
||||
it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots)
|
||||
};
|
||||
let run = |r: &crate::TextRun| {
|
||||
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|
||||
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
|
||||
};
|
||||
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
@@ -236,6 +289,65 @@ mod tests {
|
||||
assert!(tx.runs[0].style.overprint_fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_freeform_gradient_is_black_when_every_point_is() {
|
||||
use vectorcraft_color::freeform::{Freeform, FreeformPoint};
|
||||
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() });
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = k;
|
||||
}
|
||||
let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))];
|
||||
g.freeform = Some(Freeform { points, ..Default::default() });
|
||||
let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0);
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops");
|
||||
// Another kind of gradient draws its black stops, not the points it still holds.
|
||||
let mut linear = g.clone();
|
||||
linear.gradient.kind = GradientKind::Linear;
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&linear));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops");
|
||||
if let Some(f) = &mut g.freeform {
|
||||
f.points[1].color = Color::gray(1.0);
|
||||
}
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black");
|
||||
g.freeform = Some(Freeform::default());
|
||||
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
|
||||
assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() {
|
||||
let mut g = vectorcraft_color::GradientPaint::new(Default::default());
|
||||
for s in &mut g.gradient.stops {
|
||||
s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
}
|
||||
g.gradient.stops[0].swatch = Some("Ink".into());
|
||||
let k = Paint::Gradient(Box::new(g));
|
||||
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0));
|
||||
let spots = ["Ink".to_string()];
|
||||
assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black");
|
||||
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_deep_copies_only_the_nodes_that_change() {
|
||||
let k = cmyk(0.0, 0.0, 0.0, 1.0);
|
||||
let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0)));
|
||||
let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0)));
|
||||
let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()]));
|
||||
let before = group.clone();
|
||||
assert!(OverprintBlack::default().apply_deep(&mut group, &[]));
|
||||
let members = group.children().unwrap();
|
||||
assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original");
|
||||
assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied");
|
||||
assert!(!before.has_overprint());
|
||||
let marked = group.clone();
|
||||
assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change");
|
||||
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_overprint_black_list_migrates() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
@@ -27,7 +27,11 @@ impl TextObject {
|
||||
/// Character attributes as presented by controls (stored runs stay local for layout
|
||||
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
|
||||
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
|
||||
let scale = self.style_scale()?;
|
||||
Self::scaled_char_style(style, self.style_scale()?)
|
||||
}
|
||||
|
||||
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
|
||||
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
|
||||
let mut style = style.clone();
|
||||
style.size *= scale.points;
|
||||
style.leading = style.leading.map(|v| v * scale.points);
|
||||
@@ -57,19 +61,27 @@ impl TextObject {
|
||||
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
|
||||
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
|
||||
/// transform).
|
||||
///
|
||||
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
|
||||
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
|
||||
/// non-uniform scale of the path would move, and a uniform one keeps.
|
||||
pub fn scale_text_attributes(&mut self) -> bool {
|
||||
let Some(scale) = self.style_scale() else { return false };
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
let Some(mut scale) = self.style_scale() else { return false };
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
if matches!(self.kind, TextKind::OnPath { .. }) {
|
||||
scale.horizontal = 1.0;
|
||||
sx = sy;
|
||||
}
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let mut baked = Vec::with_capacity(self.runs.len());
|
||||
for run in &self.runs {
|
||||
let Some(eff) = self.effective_char_style(&run.style) else { return false };
|
||||
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
|
||||
baked.push(eff);
|
||||
}
|
||||
for (run, style) in self.runs.iter_mut().zip(baked) {
|
||||
@@ -78,6 +90,14 @@ impl TextObject {
|
||||
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
|
||||
self.scale_char_strokes(1.0 / sy);
|
||||
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
|
||||
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
|
||||
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
|
||||
let grow = Affine::scale_non_uniform(sx, sy);
|
||||
match &mut self.kind {
|
||||
TextKind::Area { frame } => frame.transform(grow),
|
||||
TextKind::OnPath { path, .. } => path.transform(grow),
|
||||
TextKind::Point => {}
|
||||
}
|
||||
self.cached_bounds = None;
|
||||
self.cached_baselines.clear();
|
||||
self.cached_ink = None;
|
||||
|
||||
@@ -5,7 +5,9 @@ use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
|
||||
use vectorcraft_pathops::addons::pathtools::insert_at;
|
||||
|
||||
use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points};
|
||||
use crate::util::{
|
||||
catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
|
||||
};
|
||||
|
||||
fn diag(b: Rect) -> f64 {
|
||||
b.width().hypot(b.height()).max(1e-6)
|
||||
@@ -325,8 +327,8 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
|
||||
}
|
||||
|
||||
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors
|
||||
/// ([`map_nonlinear_within`]).
|
||||
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
|
||||
/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069).
|
||||
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
|
||||
if ang == 0.0 {
|
||||
@@ -343,7 +345,7 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
|
||||
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
|
||||
};
|
||||
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
|
||||
map_nonlinear_within(path, piece, max, f)
|
||||
map_smooth_within(path, piece, max, f)
|
||||
}
|
||||
|
||||
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
|
||||
|
||||
@@ -82,7 +82,7 @@ pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_objec
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects.
|
||||
//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects.
|
||||
//!
|
||||
//! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path
|
||||
//! or compound path is given as its effected geometry, and a fill or stroke with geometry effects
|
||||
@@ -11,12 +11,15 @@
|
||||
//! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or
|
||||
//! layer whose clipping path has strokes with geometry effects is given as that path's geometry
|
||||
//! before its effects, which the renderer clips by, and those strokes as drawn. Fills and
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`],
|
||||
//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve,
|
||||
//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with
|
||||
//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and
|
||||
//! marquees use, leaves 3D effects unprojected. [`bounds_of`],
|
||||
//! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes
|
||||
//! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and
|
||||
//! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows,
|
||||
//! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured
|
||||
//! with its geometry effects, and the other instances in it are measured without them.
|
||||
//! with its geometry and 3D effects, and the other instances in it are measured without them.
|
||||
//! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and,
|
||||
//! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds).
|
||||
|
||||
@@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt};
|
||||
use crate::group::has_own_paint;
|
||||
use crate::reshape::{geometry_effects, leaf_geometry};
|
||||
use crate::{
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art,
|
||||
needs_outline, outline_art, paints, reshape,
|
||||
GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve,
|
||||
has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in,
|
||||
};
|
||||
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects:
|
||||
/// past it, the other instances in the object are measured without geometry effects.
|
||||
/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects:
|
||||
/// past it, the other instances in the object are measured without those effects.
|
||||
const MAX_INSTANCES: usize = 4096;
|
||||
|
||||
/// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else
|
||||
@@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc::
|
||||
.fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box())))
|
||||
}
|
||||
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else
|
||||
/// [`Node::visual_bounds_with`].
|
||||
/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected,
|
||||
/// else [`Node::visual_bounds_with`].
|
||||
pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
Drawn::new(symbols).visual_bounds(n)
|
||||
}
|
||||
@@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances
|
||||
/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a
|
||||
/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a
|
||||
/// group of its clipping path without strokes and the drawn art of the path's strokes, when they
|
||||
/// have one. `None` when no geometry effect in `n` changes what it draws.
|
||||
/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or
|
||||
/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group
|
||||
/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's
|
||||
/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps
|
||||
/// its own id. `None` when no geometry effect in `n` changes what it draws.
|
||||
pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
|
||||
Drawn::new(symbols).drawn_art(n)
|
||||
Drawn::without_3d(symbols).drawn_art(n)
|
||||
}
|
||||
|
||||
/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol
|
||||
/// instance in `n` counts when its symbol's art has a geometry effect.
|
||||
/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a
|
||||
/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its
|
||||
/// symbol's art has geometry or 3D effects.
|
||||
pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool {
|
||||
Drawn::new(symbols).draws_geometry(n)
|
||||
}
|
||||
|
||||
/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name,
|
||||
/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name,
|
||||
/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]).
|
||||
/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]).
|
||||
struct Drawn<'s, 'd> {
|
||||
symbols: &'s SymbolBoxes<'d>,
|
||||
draws: RefCell<HashMap<String, bool>>,
|
||||
left: Cell<usize>,
|
||||
three_d: bool,
|
||||
}
|
||||
|
||||
impl<'s, 'd> Drawn<'s, 'd> {
|
||||
fn new(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) }
|
||||
Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true }
|
||||
}
|
||||
|
||||
/// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]).
|
||||
fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self {
|
||||
Drawn { three_d: false, ..Self::new(symbols) }
|
||||
}
|
||||
|
||||
/// Whether `n` has a 3D effect of its own that this measurement projects.
|
||||
fn projects(&self, n: &Node) -> bool {
|
||||
self.three_d && (has_revolve(n) || has_solid(n))
|
||||
}
|
||||
|
||||
/// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object.
|
||||
@@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
let mut found = false;
|
||||
n.walk(&mut |c| {
|
||||
found = found
|
||||
|| self.projects(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol),
|
||||
_ => reshapes(c),
|
||||
@@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
d
|
||||
}
|
||||
|
||||
/// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the
|
||||
/// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that
|
||||
/// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from
|
||||
/// those effects in its symbol's art, with the instance's appearance overrides applied.
|
||||
/// A group or layer with fills or strokes of its own that
|
||||
/// paint, around members with geometry effects, is evaluated too: its fills and strokes paint
|
||||
/// the members' geometry before their effects. A blend, envelope or repeat whose objects have
|
||||
/// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and
|
||||
/// the objects in its evaluated art keep their geometry effects. `None` when it has none, and
|
||||
/// for a symbol instance past [`MAX_INSTANCES`].
|
||||
fn own_art(&self, n: &Node) -> Option<Node> {
|
||||
let doc = Some(self.symbols.document());
|
||||
// A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built.
|
||||
let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n);
|
||||
if counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
if self.three_d
|
||||
&& let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n))
|
||||
{
|
||||
// The builders retain later geometry on the projected group. Measure it after that
|
||||
// geometry too; item-level effects are handled by the ordinary member traversal.
|
||||
return Some(self.own_art(&art).unwrap_or(art));
|
||||
}
|
||||
let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c)));
|
||||
let painted = || has_own_paint(n) && inner();
|
||||
match &n.kind {
|
||||
@@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> {
|
||||
if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) {
|
||||
return None;
|
||||
}
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
if !counted {
|
||||
let left = self.left.get().checked_sub(1)?;
|
||||
self.left.set(left);
|
||||
}
|
||||
let art = self.symbols.measure_art(symbol, Arc::clone)?;
|
||||
// Paint overrides can remove a projected surface or change its stroke outline.
|
||||
let art =
|
||||
if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) };
|
||||
// An instance in perspective is projected by `reshape`.
|
||||
let doc = Some(self.symbols.document());
|
||||
reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art)))
|
||||
|
||||
@@ -608,21 +608,36 @@ fn transform_step(e: &Effect) -> Option<Affine> {
|
||||
|
||||
/// The Transform effects of `effects` that move the image of its last visible Rasterize effect
|
||||
/// instead of the art it is made from: the indices of the visible Transform effects listed after
|
||||
/// it that move the art, when from the first visible Transform effect after it on every visible
|
||||
/// effect is a Transform effect that moves the art once (no copies, not at random). Effects apply
|
||||
/// in the order they are listed, so the image is made of the art before those Transform effects
|
||||
/// and moves with them, its pixel grid and room around the art included. `None` when there is no
|
||||
/// such Transform effect, or the effects after the Rasterize effect hold anything else from there
|
||||
/// on.
|
||||
/// it that move or copy the art, when from the first visible Transform effect after it on every
|
||||
/// visible effect is a Transform effect that does not move at random, and at most one of them makes
|
||||
/// copies. Effects apply in the order they are listed, so the image is made of the art before those
|
||||
/// Transform effects and moves with them, its pixel grid and room around the art included; each copy
|
||||
/// carries the same image ([`stage_maps`]). `None` when there is no such Transform effect, or the
|
||||
/// effects after the Rasterize effect hold anything else from there on.
|
||||
pub fn rasterize_stage(effects: &[Effect]) -> Option<Vec<usize>> {
|
||||
let r = effects.iter().rposition(|e| e.visible && e.id == RASTERIZE)?;
|
||||
let first = r + 1 + effects.get(r + 1..)?.iter().position(|e| e.visible && e.id == "distort.transform")?;
|
||||
let mut at = vec![];
|
||||
let mut copying = false;
|
||||
for (i, e) in effects.iter().enumerate().skip(first).filter(|(_, e)| e.visible) {
|
||||
if e.id != "distort.transform" || transform_step(e).is_none() {
|
||||
if e.id != "distort.transform" {
|
||||
return None;
|
||||
}
|
||||
if crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).0 != Affine::IDENTITY {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
if !flag(&p, "objects", true) {
|
||||
continue;
|
||||
}
|
||||
if flag(&p, "random", false) {
|
||||
return None;
|
||||
}
|
||||
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
|
||||
if copies > 0 {
|
||||
if copying {
|
||||
return None;
|
||||
}
|
||||
copying = true;
|
||||
}
|
||||
if copies > 0 || map != Affine::IDENTITY {
|
||||
at.push(i);
|
||||
}
|
||||
}
|
||||
@@ -641,22 +656,41 @@ pub fn staged_effects(effects: &[Effect], at: &[usize]) -> Vec<Effect> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The map the Transform effects at `at` of `effects` ([`rasterize_stage`]) move the Rasterize
|
||||
/// The maps the Transform effects at `at` of `effects` ([`rasterize_stage`]) place the Rasterize
|
||||
/// image by, for `staged`, the geometry the effects before them make: each one's map about its
|
||||
/// reference point on the bounds of the geometry it takes, as the geometry pass applies it, the
|
||||
/// last one outermost. `None` when `staged` is empty or the map is not a number.
|
||||
pub fn stage_map(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Affine> {
|
||||
/// last one outermost. A Transform effect with copies places the image once more for each copy
|
||||
/// the geometry pass makes, copy `k` through its map `k` times. The maps come in the order the
|
||||
/// images paint, the lowest first: the last copy lowest and the original on top, as copied objects
|
||||
/// stack. `None` when `staged` is empty or a map is not a number.
|
||||
pub fn stage_maps(effects: &[Effect], at: &[usize], staged: &vectorcraft_geom::PathData) -> Option<Vec<Affine>> {
|
||||
let mut cur = staged.clone();
|
||||
let mut b = staged.bounds()?;
|
||||
let mut map = Affine::IDENTITY;
|
||||
// The original's map first, then each copy's.
|
||||
let mut maps = vec![Affine::IDENTITY];
|
||||
for &i in at {
|
||||
let e = effects.get(i)?;
|
||||
let (m, _) = crate::distort::transform_map(b, &merged_params(&e.id, &e.params), 0);
|
||||
map = m * map;
|
||||
cur = cur.transformed(m);
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
let (m, copies) = crate::distort::transform_map(b, &p, 0);
|
||||
if copies == 0 {
|
||||
maps.iter_mut().for_each(|x| *x = m * *x);
|
||||
cur = cur.transformed(m);
|
||||
} else {
|
||||
// As many copies as the geometry pass makes: it stops early past its limits.
|
||||
let next = crate::distort::transform(&cur, b, &p, 0);
|
||||
let made = (next.anchor_count() / cur.anchor_count().max(1)).saturating_sub(1);
|
||||
let placed = maps.clone();
|
||||
let mut xf = Affine::IDENTITY;
|
||||
for _ in 0..made {
|
||||
xf = m * xf;
|
||||
maps.extend(placed.iter().map(|x| xf * *x));
|
||||
}
|
||||
cur = next;
|
||||
}
|
||||
b = cur.bounds().unwrap_or(b);
|
||||
}
|
||||
map.is_finite().then_some(map)
|
||||
maps.reverse();
|
||||
maps.iter().all(|m| m.is_finite()).then_some(maps)
|
||||
}
|
||||
|
||||
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
|
||||
|
||||
@@ -1687,6 +1687,27 @@ fn twist_turns_clockwise_for_positive_angles() {
|
||||
assert!(turned(-45.0).y < 49.5, "{:?}", turned(-45.0));
|
||||
}
|
||||
|
||||
/// Twist turns a line into a smooth spiral: the points it adds join their pieces without a kink,
|
||||
/// however far it turns (#7069).
|
||||
#[test]
|
||||
fn twist_joins_its_pieces_smoothly() {
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false));
|
||||
let bounds = Rect::new(40.0, 30.0, 60.0, 30.0);
|
||||
for angle in [90.0, 400.0, -720.0] {
|
||||
let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds);
|
||||
let anchors = &out.subpaths[0].anchors;
|
||||
assert!(anchors.len() > 8, "{angle}°: {} anchors", anchors.len());
|
||||
for a in anchors.iter().skip(1).take(anchors.len() - 2) {
|
||||
let (into, out) = (a.p - a.h_in, a.h_out - a.p);
|
||||
if into.hypot() < 1e-9 || out.hypot() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let kink = (into.x * out.y - into.y * out.x).atan2(into.dot(out)).to_degrees().abs();
|
||||
assert!(kink < 1.0, "{angle}°: a kink of {kink:.1}° at {:?}", a.p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn twist_fixes_the_outer_circle_and_rotates_inside() {
|
||||
let out = run("distort.twist", json!({"angle": 0}), &square());
|
||||
|
||||
@@ -129,9 +129,10 @@ fn rasterize_before_a_transform_keeps_its_options() {
|
||||
assert_eq!(crate::rasterize_stage(&effects), Some(vec![1]));
|
||||
}
|
||||
|
||||
/// The Transform effects after the last Rasterize effect move its image when, from the first of
|
||||
/// them on, every visible effect is a Transform effect that moves the art once. Hidden ones, and
|
||||
/// ones with Transform Objects off, leave the image where it is.
|
||||
/// The Transform effects after the last Rasterize effect move or copy its image when, from the
|
||||
/// first of them on, every visible effect is a Transform effect that does not move at random and at
|
||||
/// most one of them makes copies. Hidden ones, and ones with Transform Objects off, leave the image
|
||||
/// where it is.
|
||||
#[test]
|
||||
fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
let rasterize = || fx(crate::RASTERIZE, json!({}));
|
||||
@@ -150,9 +151,16 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
// the image back.
|
||||
(vec![rasterize(), roughen.clone(), shadow.clone(), scale()], Some(vec![3])),
|
||||
(vec![rasterize(), scale(), roughen], None),
|
||||
(vec![rasterize(), scale(), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], None),
|
||||
(vec![rasterize(), scale(), shadow.clone()], None),
|
||||
// Each copy carries the image, even of a Transform effect that only copies in place.
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"copies": 2}))], Some(vec![1])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), scale()], Some(vec![1, 2])),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2, "objects": false}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), transform(json!({"moveV": 10, "copies": 3}))], None),
|
||||
(vec![rasterize(), transform(json!({"moveH": 10, "copies": 2})), shadow], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "random": true}))], None),
|
||||
(vec![rasterize(), transform(json!({"scaleH": 200, "copies": 2, "random": true}))], None),
|
||||
// The Transform effect before the Rasterize effect moves the art.
|
||||
(vec![scale(), rasterize()], None),
|
||||
(vec![scale(), rasterize(), rasterize(), scale()], Some(vec![3])),
|
||||
@@ -173,16 +181,62 @@ fn rasterize_following_ignores_hidden_and_objects_off() {
|
||||
fn the_image_moves_by_each_transform_about_the_art_it_takes() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"moveH": 5}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 1);
|
||||
// Twice the size about the center (20, 20), then 5 pt to the right.
|
||||
let want = Affine::translate((5.0, 0.0)) * Affine::translate((20.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-20.0, -20.0));
|
||||
assert!(map.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{map:?}");
|
||||
assert!(same_map(maps[0], want), "{maps:?}");
|
||||
// The second Transform effect turns about the center of what the first one made.
|
||||
let effects = [fx(crate::RASTERIZE, json!({})), transform(json!({"moveH": 100})), transform(json!({"rotate": 90}))];
|
||||
let map = crate::stage_map(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = map * Point::new(20.0, 20.0);
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let c = maps[0] * Point::new(20.0, 20.0);
|
||||
assert!((c.x - 120.0).abs() < 1e-9 && (c.y - 20.0).abs() < 1e-9, "{c:?}");
|
||||
assert_eq!(crate::stage_map(&effects, &[1, 2], &PathData::default()), None);
|
||||
assert_eq!(crate::stage_maps(&effects, &[1, 2], &PathData::default()), None);
|
||||
}
|
||||
|
||||
/// Is `a` `b`, each coefficient within 1e-9?
|
||||
fn same_map(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// Are `maps` `want`, in order?
|
||||
fn same_maps(maps: &[Affine], want: &[Affine]) -> bool {
|
||||
maps.len() == want.len() && maps.iter().zip(want).all(|(m, w)| same_map(*m, *w))
|
||||
}
|
||||
|
||||
/// A Transform effect with copies places the image once for the original and once for each copy,
|
||||
/// copy `k` through its map `k` times about the art before it, the last copy lowest and the
|
||||
/// original on top. A Transform effect after it moves every placement, about the bounds of all the
|
||||
/// copies.
|
||||
#[test]
|
||||
fn each_copy_carries_the_image() {
|
||||
let staged = shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0));
|
||||
let rasterize = fx(crate::RASTERIZE, json!({}));
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let want = [Affine::translate((200.0, 0.0)), Affine::translate((100.0, 0.0)), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Turned 90° about the center (20, 20) each time: copy 2 turns 180°.
|
||||
let effects = [rasterize.clone(), transform(json!({"rotate": 90, "copies": 2}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
let turn = |deg: f64| Affine::translate((20.0, 20.0)) * Affine::rotate(-deg.to_radians()) * Affine::translate((-20.0, -20.0));
|
||||
let want = [turn(180.0), turn(90.0), Affine::IDENTITY];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A scale after the copies doubles every placement about the center of all three, (120, 20).
|
||||
let effects = [rasterize.clone(), transform(json!({"moveH": 100, "copies": 2})), transform(json!({"scaleH": 200, "scaleV": 200}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let scale = Affine::translate((120.0, 20.0)) * Affine::scale(2.0) * Affine::translate((-120.0, -20.0));
|
||||
let want = [scale * Affine::translate((200.0, 0.0)), scale * Affine::translate((100.0, 0.0)), scale];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// A move before the copies moves the art they copy.
|
||||
let effects = [rasterize.clone(), transform(json!({"moveV": 5})), transform(json!({"moveH": 100, "copies": 1}))];
|
||||
let maps = crate::stage_maps(&effects, &[1, 2], &staged).unwrap();
|
||||
let want = [Affine::translate((100.0, 5.0)), Affine::translate((0.0, 5.0))];
|
||||
assert!(same_maps(&maps, &want), "{maps:?}");
|
||||
// Copies stop where the geometry pass stops them: none past its reach of 1e9 pt.
|
||||
let effects = [rasterize, transform(json!({"moveH": 1.0e7, "copies": 1000}))];
|
||||
let maps = crate::stage_maps(&effects, &[1], &staged).unwrap();
|
||||
assert_eq!(maps.len(), 100, "{}", maps.len());
|
||||
}
|
||||
|
||||
/// An SVG filter keeps its options: it paints in its own user space.
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
|
||||
/// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of
|
||||
/// segments into pieces within an anchor budget.
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, pieces};
|
||||
pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces};
|
||||
|
||||
/// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight
|
||||
/// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px,
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time
|
||||
//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500,
|
||||
//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each
|
||||
//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same
|
||||
//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks
|
||||
//! through the paths already added), and one `Selection::set` call followed by the anchors. It
|
||||
//! checks that both give the same selection, every field, before it times them, and then times the
|
||||
//! whole command once per run on the 2,000-path document.
|
||||
//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run
|
||||
//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in
|
||||
//! ms; elsewhere they are wall times.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
/// The anchors of each path, or of each subpath of the one compound path.
|
||||
const ANCHORS: usize = 10;
|
||||
|
||||
/// The builds of the selection in each timed run; a row gives the time of one build.
|
||||
const REPS: usize = 20;
|
||||
|
||||
/// What the command selects for one cut end: the path and its anchor (subpath, anchor).
|
||||
type Pick = (NodeId, (usize, usize));
|
||||
|
||||
/// A way of building the selection from the cut ends.
|
||||
type Rebuild = fn(&mut Selection, &[Pick]);
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1)
|
||||
}
|
||||
|
||||
fn median(mut ms: Vec<f64>) -> f64 {
|
||||
ms.sort_by(f64::total_cmp);
|
||||
ms[ms.len() / 2]
|
||||
}
|
||||
|
||||
/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only).
|
||||
fn thread_cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise.
|
||||
fn measure(f: impl FnOnce()) -> f64 {
|
||||
match thread_cpu_ns() {
|
||||
Some(start) => {
|
||||
f();
|
||||
thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6)
|
||||
}
|
||||
None => {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built by clearing it and adding each path in turn.
|
||||
fn one_by_one(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// The selection built with one `Selection::set` call, as the command builds it.
|
||||
fn one_call(sel: &mut Selection, picked: &[Pick]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
fn exec(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`.
|
||||
fn row(row: usize) -> SubPath {
|
||||
let y = row as f64 * 20.0;
|
||||
SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false)
|
||||
}
|
||||
|
||||
/// A session with the paths in `paths` and every anchor of theirs but the two ends of each
|
||||
/// subpath direct-selected (a path with all its anchors selected counts as selected whole).
|
||||
fn fixture(paths: Vec<PathData>) -> Session {
|
||||
let mut doc = Document::new(1600.0, 1200.0);
|
||||
let l = doc.layers.first().map(|l| l.id);
|
||||
let mut items = vec![];
|
||||
for pd in paths {
|
||||
let id = doc.alloc_id();
|
||||
let refs: Vec<[usize; 2]> =
|
||||
pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect();
|
||||
doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
items.push(json!({"id": id.0, "anchors": refs}));
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(doc, None);
|
||||
exec(&mut s, "select.anchorsMany", json!({"items": items}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The cut ends the command selects, in the order it selects them: read back from the selection it
|
||||
/// leaves, which holds each cut path once in that order.
|
||||
fn picked_after_cut(s: &Session) -> Vec<Pick> {
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect()
|
||||
}
|
||||
|
||||
fn bench(name: &str, paths: impl Fn() -> Vec<PathData>) {
|
||||
let mut s = fixture(paths());
|
||||
exec(&mut s, "path.cutAtAnchors", json!({}));
|
||||
let picked = picked_after_cut(&s);
|
||||
let mut start = Selection::default();
|
||||
one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]);
|
||||
let (mut a, mut b) = (start.clone(), start.clone());
|
||||
one_by_one(&mut a, &picked);
|
||||
one_call(&mut b, &picked);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
for i in 0..iters() {
|
||||
let run = |f: Rebuild, out: &mut Vec<f64>| {
|
||||
let ms = measure(|| {
|
||||
for _ in 0..REPS {
|
||||
let mut sel = start.clone();
|
||||
f(&mut sel, black_box(&picked));
|
||||
black_box(&sel);
|
||||
}
|
||||
});
|
||||
out.push(ms / REPS as f64);
|
||||
};
|
||||
if i % 2 == 0 {
|
||||
run(one_by_one, &mut old);
|
||||
run(one_call, &mut new);
|
||||
} else {
|
||||
run(one_call, &mut new);
|
||||
run(one_by_one, &mut old);
|
||||
}
|
||||
}
|
||||
let (old, new) = (median(old), median(new));
|
||||
println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" };
|
||||
println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup");
|
||||
for n in [500, 2_000, 5_000] {
|
||||
bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect());
|
||||
}
|
||||
bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]);
|
||||
let whole: Vec<f64> = (0..iters())
|
||||
.map(|_| {
|
||||
let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect());
|
||||
measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({})))))
|
||||
})
|
||||
.collect();
|
||||
println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `cargo run --release -p vectorcraft-engine --example direction_handles_bench` prints the time
|
||||
//! Select › Object › Direction Handles takes to select every path of documents of 2,000, 10,000 and
|
||||
//! 20,000 rectangles, spread over two layers with one group. For each size it times, on the same
|
||||
//! paths and anchors, the selection built one path at a time (a clear, then an add per path) and
|
||||
//! the selection built with one `Selection::set` call, checks that the two are equal, and then
|
||||
//! times the whole `select.object.directionHandles` command.
|
||||
//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere
|
||||
//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each
|
||||
//! row is the median in ms. A run of the two selection rows repeats the selection 1,000,000 / paths
|
||||
//! times and gives the time of one.
|
||||
// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, NodeId, Selection};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
fn iters() -> usize {
|
||||
std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7)
|
||||
}
|
||||
|
||||
/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read.
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise.
|
||||
fn ms(f: impl FnOnce()) -> f64 {
|
||||
let (cpu, wall) = (cpu_ns(), Instant::now());
|
||||
f();
|
||||
match (cpu, cpu_ns()) {
|
||||
(Some(a), Some(b)) => (b - a) as f64 / 1e6,
|
||||
_ => wall.elapsed().as_secs_f64() * 1000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f64>) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
|
||||
/// `n` 10 pt squares: a tenth of them in one group and the rest loose, half on each of two layers.
|
||||
fn document(n: usize) -> Document {
|
||||
let mut b = DocBuilder::new(4000.0, 4000.0);
|
||||
let square = |b: &mut DocBuilder, i: usize| {
|
||||
let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0);
|
||||
b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6))
|
||||
};
|
||||
let grouped = n / 10;
|
||||
let kids = (0..grouped).map(|i| square(&mut b, i)).collect();
|
||||
b.group(kids, false);
|
||||
for i in grouped..n {
|
||||
if i == n / 2 {
|
||||
b.layer("Layer 2");
|
||||
}
|
||||
let node = square(&mut b, i);
|
||||
b.add(node);
|
||||
}
|
||||
b.build()
|
||||
}
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects `items` with one `Selection::set` call and one extend of the anchors.
|
||||
fn with_set(sel: &mut Selection, items: Items) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn row(name: &str, ms: f64) {
|
||||
println!(" {name:<44} {ms:>10.3} ms");
|
||||
}
|
||||
|
||||
fn bench(n: usize) {
|
||||
println!("{n} paths");
|
||||
let mut s = Session::new();
|
||||
s.add_document(document(n), None);
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let start = s.doc().unwrap().selection.clone();
|
||||
s.execute("select.object.directionHandles", &json!({})).unwrap();
|
||||
let command = s.doc().unwrap().selection.clone();
|
||||
// The paths and anchors the command selects, in its order.
|
||||
let items: Items = command.objects.iter().map(|id| (*id, command.anchors[id].clone())).collect();
|
||||
assert_eq!(items.len(), n);
|
||||
|
||||
// Each run selects `reps` times, on copies made before the clock starts, and gives the time of one.
|
||||
let reps = (1_000_000 / n).max(1);
|
||||
let time = |f: fn(&mut Selection, Items)| -> (f64, Selection) {
|
||||
let mut last = Selection::default();
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
let mut work: Vec<(Selection, Items)> = (0..reps).map(|_| (start.clone(), items.clone())).collect();
|
||||
let t = ms(|| {
|
||||
for (sel, it) in &mut work {
|
||||
f(sel, black_box(std::mem::take(it)));
|
||||
}
|
||||
});
|
||||
last = work.pop().unwrap().0;
|
||||
t / reps as f64
|
||||
})
|
||||
.collect();
|
||||
(median(runs), last)
|
||||
};
|
||||
let (old, a) = time(one_by_one);
|
||||
let (new, b) = time(with_set);
|
||||
assert_eq!(a, b, "both ways give the same selection");
|
||||
let mut want = start.clone();
|
||||
with_set(&mut want, items.clone());
|
||||
assert_eq!(want.objects, command.objects);
|
||||
assert_eq!(want.anchors, command.anchors);
|
||||
row("selection, one add per path", old);
|
||||
row("selection, one set call", new);
|
||||
println!(" {:<44} {:>10.1}x", "ratio", old / new);
|
||||
|
||||
let runs = (0..iters())
|
||||
.map(|_| {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
ms(|| drop(black_box(s.execute("select.object.directionHandles", &json!({})).unwrap())))
|
||||
})
|
||||
.collect();
|
||||
row("select.object.directionHandles, whole command", median(runs));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" });
|
||||
for n in [2_000, 10_000, 20_000] {
|
||||
bench(n);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -100,20 +102,21 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
compounds.dedup();
|
||||
let mut beside = Beside::replacing(d, &trimmed);
|
||||
let mut all = vec![];
|
||||
// The selection is read through a set and changed once at the end, so a trim of many
|
||||
// paths does not go through the selected objects once per path and per piece.
|
||||
let mut selected_ids: HashSet<NodeId> = sel.objects.iter().copied().collect();
|
||||
let mut joining: Vec<NodeId> = vec![];
|
||||
let mut gone: Vec<NodeId> = vec![];
|
||||
for (id, pieces) in plan {
|
||||
let selected = sel.contains(id);
|
||||
let selected = selected_ids.contains(&id);
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
let made = replace_with_pieces(d, &mut beside, id, pieces)?;
|
||||
// The pieces of a selected path are selected; what was not selected stays so.
|
||||
if made.is_empty() {
|
||||
sel.remove(id);
|
||||
gone.push(id);
|
||||
} else if selected {
|
||||
for n in &made {
|
||||
if !sel.contains(*n) {
|
||||
sel.add(*n);
|
||||
}
|
||||
}
|
||||
joining.extend(made.iter().copied().filter(|n| selected_ids.insert(*n)));
|
||||
}
|
||||
all.extend(made);
|
||||
}
|
||||
@@ -121,9 +124,15 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for c in compounds {
|
||||
if d.node(c).is_some_and(|n| n.children().is_some_and(|ch| ch.is_empty())) {
|
||||
d.remove(c)?;
|
||||
sel.remove(c);
|
||||
gone.push(c);
|
||||
}
|
||||
}
|
||||
sel.remove_all(gone);
|
||||
if let Some((first, rest)) = joining.split_first() {
|
||||
// `add` clears what any change to the object selection clears; the rest are new ids.
|
||||
sel.add(*first);
|
||||
sel.objects.extend_from_slice(rest);
|
||||
}
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "removed": removed }))
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! one undo step, and what takes no part.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Stretches};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -420,6 +421,139 @@ fn the_selection_stays_as_it_was_and_the_pieces_of_a_selected_path_are_selected(
|
||||
assert!(s.doc().unwrap().selection.is_empty(), "a removed path leaves the selection");
|
||||
}
|
||||
|
||||
/// Run the command with `p`, and check that it leaves the selection exactly as changing it one
|
||||
/// id at a time does: for each trimmed path in the plan's order, its anchors and segments let go,
|
||||
/// a path with no pieces left removed, and each piece of a selected path added; then each emptied
|
||||
/// compound path removed. Returns the selection.
|
||||
fn same_selection_as_one_id_at_a_time(s: &mut Session, p: Value) -> Selection {
|
||||
let st = s.doc().unwrap();
|
||||
let pick = super::pick(&p).unwrap();
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let plan: Vec<(NodeId, usize)> =
|
||||
plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).unwrap().into_iter().map(|t| (t.id, t.pieces.len())).collect();
|
||||
let mut compounds: Vec<NodeId> = plan
|
||||
.iter()
|
||||
.filter_map(|(id, _)| st.doc.parent_of(*id))
|
||||
.filter(|c| matches!(st.doc.node(*c).map(|n| &n.kind), Some(NodeKind::Compound { .. })))
|
||||
.collect();
|
||||
compounds.dedup();
|
||||
let mut want = st.selection.clone();
|
||||
let made = ids(&s.execute(TRIM, &p).unwrap());
|
||||
assert_eq!(made.len(), plan.iter().map(|(_, n)| n).sum::<usize>());
|
||||
let mut made = made.into_iter();
|
||||
for (id, n) in plan {
|
||||
let selected = want.contains(id);
|
||||
want.anchors.remove(&id);
|
||||
want.segments.remove(&id);
|
||||
let pieces: Vec<NodeId> = made.by_ref().take(n).collect();
|
||||
if pieces.is_empty() {
|
||||
want.remove(id);
|
||||
} else if selected {
|
||||
for piece in pieces {
|
||||
if !want.contains(piece) {
|
||||
want.add(piece);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
for c in compounds {
|
||||
if st.doc.node(c).is_none() {
|
||||
want.remove(c);
|
||||
}
|
||||
}
|
||||
want.prune(&st.doc);
|
||||
assert_eq!(st.selection, want);
|
||||
st.selection.clone()
|
||||
}
|
||||
|
||||
/// Two lines across split by a rectangle, one of them selected; a selected line nothing crosses
|
||||
/// and a selected compound path of two such lines, which the rectangle removes whole; and a
|
||||
/// selected line elsewhere with an anchor and a segment direct-selected. Returns (the selected
|
||||
/// line across, the line removed whole, the compound path, the line elsewhere).
|
||||
fn trim_scene(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let (h, ..) = across_and_uprights(s);
|
||||
line(s, &[(0.0, 120.0), (300.0, 120.0)], false);
|
||||
let alone = line(s, &[(145.0, 200.0), (155.0, 200.0)], false);
|
||||
let c1 = line(s, &[(145.0, 170.0), (155.0, 170.0)], false);
|
||||
let c2 = line(s, &[(145.0, 180.0), (155.0, 180.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let elsewhere = line(s, &[(0.0, 250.0), (10.0, 250.0), (20.0, 250.0)], false);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0, alone.0, compound.0]})).unwrap();
|
||||
s.edit("direct", |_, sel| {
|
||||
sel.anchors.insert(elsewhere, [(0, 1)].into());
|
||||
sel.anchors.insert(h, [(0, 0)].into());
|
||||
sel.segments.insert(elsewhere, [(0, 0)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(h, alone, compound, elsewhere)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives() {
|
||||
// A removed key object stops being the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, elsewhere) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(alone);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, None);
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
assert_eq!(&sel.objects[..2], [elsewhere, h]);
|
||||
assert_eq!(sel.objects.len(), 3, "{:?}", sel.objects);
|
||||
assert!(sel.anchors.contains_key(&elsewhere) && sel.segments.contains_key(&elsewhere) && !sel.anchors.contains_key(&h));
|
||||
// A key object that keeps its first piece stays the key.
|
||||
let mut s = session();
|
||||
let (h, alone, compound, _) = trim_scene(&mut s);
|
||||
s.edit("key", |_, sel| {
|
||||
sel.key = Some(h);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 120]}));
|
||||
assert_eq!(sel.key, Some(h));
|
||||
assert!(!sel.contains(alone) && !sel.contains(compound));
|
||||
// Trimming only paths that are not selected leaves a targeted object targeted.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), Some(elsewhere)));
|
||||
assert!(exists(&s, h));
|
||||
// A selected path that gains a piece changes the object selection, which lets go of the target.
|
||||
let mut s = session();
|
||||
let (h, _, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, h.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 90, 20, 40]}));
|
||||
assert_eq!((sel.objects.len(), sel.target), (3, None));
|
||||
// So does a selected path that is removed whole.
|
||||
let mut s = session();
|
||||
let (_, alone, _, elsewhere) = trim_scene(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [elsewhere.0, alone.0]})).unwrap();
|
||||
s.edit("target", |_, sel| {
|
||||
sel.target = Some(elsewhere);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let sel = same_selection_as_one_id_at_a_time(&mut s, json!({"rect": [140, 190, 20, 20]}));
|
||||
assert_eq!((sel.objects.as_slice(), sel.target), ([elsewhere].as_slice(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_paths_far_from_the_trimmed_one_cost_no_crossing_search() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -5,15 +5,16 @@ use super::{
|
||||
|
||||
// ---------- brushes ----------
|
||||
|
||||
/// Brushable nodes (paths and compound paths) under `ids`.
|
||||
/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached.
|
||||
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
|
||||
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if own && !in_compound && !out.contains(&c.id) {
|
||||
if own && !in_compound && seen.insert(c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
@@ -748,3 +749,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Appearance;
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
/// The collector with a linear search of its output, kept to compare results with.
|
||||
fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |c| {
|
||||
let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. });
|
||||
let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if own && !in_compound && !out.contains(&c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn path(d: &mut Document) -> Node {
|
||||
Node::path(d.alloc_id(), PathData::default(), Appearance::default())
|
||||
}
|
||||
|
||||
fn compound(d: &mut Document, children: Vec<Node>) -> Node {
|
||||
Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() })
|
||||
}
|
||||
|
||||
fn add(d: &mut Document, node: Node) -> NodeId {
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
d.insert(layer, usize::MAX, node).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_targets_list_each_target_once_in_first_reached_order() {
|
||||
let mut d = Document::new(400.0, 300.0);
|
||||
let a = path(&mut d);
|
||||
let a = add(&mut d, a);
|
||||
let mut guide = path(&mut d);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut guide.kind {
|
||||
*g = true;
|
||||
}
|
||||
let guide = add(&mut d, guide);
|
||||
let mut clip = path(&mut d);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let clip = add(&mut d, clip);
|
||||
// A group holding a path and a compound path of two members.
|
||||
let p1 = path(&mut d);
|
||||
let p1_id = p1.id;
|
||||
let (m1, m2) = (path(&mut d), path(&mut d));
|
||||
let m1_id = m1.id;
|
||||
let cp1 = compound(&mut d, vec![m1, m2]);
|
||||
let cp1_id = cp1.id;
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]);
|
||||
let group = add(&mut d, group);
|
||||
// A compound path holding a compound path.
|
||||
let m3 = path(&mut d);
|
||||
let cp3 = compound(&mut d, vec![m3]);
|
||||
let cp3_id = cp3.id;
|
||||
let cp2 = compound(&mut d, vec![cp3]);
|
||||
let cp2 = add(&mut d, cp2);
|
||||
|
||||
let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)];
|
||||
let got = brush_targets(&d, &ids);
|
||||
assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out");
|
||||
assert_eq!(got, listed_targets(&d, &ids));
|
||||
assert!(brush_targets(&d, &[]).is_empty());
|
||||
|
||||
// Many paths in groups, each group listed with some of its members.
|
||||
let mut ids = vec![];
|
||||
for _ in 0..50 {
|
||||
let members: Vec<Node> = (0..20).map(|_| path(&mut d)).collect();
|
||||
let member_ids: Vec<NodeId> = members.iter().map(|m| m.id).collect();
|
||||
let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect());
|
||||
let g = add(&mut d, g);
|
||||
ids.push(member_ids[7]);
|
||||
ids.push(g);
|
||||
ids.push(member_ids[3]);
|
||||
}
|
||||
let got = brush_targets(&d, &ids);
|
||||
assert_eq!(got.len(), 50 * 20);
|
||||
assert_eq!(got, listed_targets(&d, &ids));
|
||||
}
|
||||
}
|
||||
+103
-10
@@ -53,10 +53,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
cmd!(
|
||||
"shape.circleThroughPoints",
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line),
|
||||
cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral),
|
||||
cmd!(
|
||||
@@ -131,14 +140,21 @@ pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewAr
|
||||
/// [`add_look`] that selects the new object only when `select` is set; otherwise the selection
|
||||
/// stays as it was.
|
||||
pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option<String>, select: bool) -> Result<Value> {
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0)
|
||||
insert_look_turned(s, label, kind, look, name, select, 0.0, true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page):
|
||||
/// its bounding box turns with it, as after the Rotate tool.
|
||||
fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation))
|
||||
insert_look_turned(s, label, kind, look, None, true, bbox_turn(rotation), true)
|
||||
}
|
||||
|
||||
/// [`add_art`] for an object whose geometry must stay where it was computed: it is not
|
||||
/// pixel-aligned, even while the document's Align New Objects to Pixel Grid is on.
|
||||
fn add_art_unaligned(s: &mut Session, label: &str, kind: NodeKind) -> Result<Value> {
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
insert_look_turned(s, label, kind, look, None, true, 0.0, false)
|
||||
}
|
||||
|
||||
/// The bounding-box angle (counter-clockwise, as `Node::bbox_angle` and the Rotate tool keep it)
|
||||
@@ -162,8 +178,10 @@ fn constrained_turn(s: &Session, rotation: f64) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. A new path or
|
||||
/// compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is on.
|
||||
/// [`insert_look`] with the new object's bounding box turned to `bbox_angle`. With `align`, a new
|
||||
/// path or compound path is pixel-aligned while the document's Align New Objects to Pixel Grid is
|
||||
/// on.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn insert_look_turned(
|
||||
s: &mut Session,
|
||||
label: &str,
|
||||
@@ -172,6 +190,7 @@ fn insert_look_turned(
|
||||
name: Option<String>,
|
||||
select: bool,
|
||||
bbox_angle: f64,
|
||||
align: bool,
|
||||
) -> Result<Value> {
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let mode = s.draw_mode;
|
||||
@@ -181,7 +200,9 @@ fn insert_look_turned(
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::new(id, kind);
|
||||
look.apply(d, &mut n);
|
||||
super::object::align_new_object(d, &mut n);
|
||||
if align {
|
||||
super::object::align_new_object(d, &mut n);
|
||||
}
|
||||
n.name = name;
|
||||
n.bbox_angle = bbox_angle;
|
||||
let mut into = None;
|
||||
@@ -390,6 +411,71 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
|
||||
}
|
||||
|
||||
/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor
|
||||
/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?,
|
||||
};
|
||||
let [a, b, c] = points;
|
||||
let (center, radius) = shapes::circle_through(a, b, c)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers.
|
||||
fn three_points(v: &Value) -> Option<[Point; 3]> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions of the selected anchor points, when there are exactly three. They are counted as
|
||||
/// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with
|
||||
/// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own.
|
||||
/// A selected segment's ends are not selected anchor points, so a selection with segments gives
|
||||
/// none; so does a selection holding an object that is not a path, or an anchor that is gone.
|
||||
fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> {
|
||||
let st = s.doc()?;
|
||||
if st.selection.segments.values().any(|set| !set.is_empty()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut points = Vec::with_capacity(4);
|
||||
for id in &st.selection.objects {
|
||||
let Some(pd) = st.doc.node(*id).and_then(|n| n.path_data()) else { return Ok(None) };
|
||||
match st.selection.anchors.get(id) {
|
||||
Some(set) => {
|
||||
for &(si, ai) in set.iter().take(4) {
|
||||
let Some(a) = pd.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)) else { return Ok(None) };
|
||||
points.push(a.p);
|
||||
}
|
||||
}
|
||||
None => points.extend(pd.anchors().take(4).map(|(_, _, a)| a.p)),
|
||||
}
|
||||
if points.len() > 3 {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Ok(match points.as_slice() {
|
||||
&[a, b, c] => Some([a, b, c]),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
|
||||
/// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default.
|
||||
fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<u64> {
|
||||
@@ -479,7 +565,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// The generator's state is odd (never 0).
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
@@ -494,7 +580,13 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
@@ -651,7 +743,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
@@ -831,7 +923,8 @@ 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);
|
||||
}
|
||||
let made = insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation))?;
|
||||
let made =
|
||||
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), 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);
|
||||
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection, Selection, TextKind};
|
||||
use vectorcraft_geom::Vec2;
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -495,16 +495,17 @@ fn direction_handles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let total: usize = items.iter().map(|x| x.1.len()).sum();
|
||||
s.select(|_, sel| {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
})?;
|
||||
s.select(|_, sel| select_anchors(sel, items))?;
|
||||
Ok(json!({ "anchors": total }))
|
||||
}
|
||||
|
||||
/// Replaces `sel` with the paths of `items` in order, each once, and direct-selects the anchors
|
||||
/// listed with each path. A path listed twice keeps its first place and its last anchor set.
|
||||
fn select_anchors(sel: &mut Selection, items: Vec<(NodeId, BTreeSet<(usize, usize)>)>) {
|
||||
sel.set(items.iter().map(|(id, _)| *id));
|
||||
sel.anchors.extend(items);
|
||||
}
|
||||
|
||||
fn save_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "select.save";
|
||||
let st = s.doc()?;
|
||||
@@ -1026,3 +1027,6 @@ fn close_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({ "closed": n }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The selection that Select ▸ Object ▸ Direction Handles builds.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{NodeId, Selection, SymbolPart};
|
||||
|
||||
use super::select_anchors;
|
||||
|
||||
type Items = Vec<(NodeId, BTreeSet<(usize, usize)>)>;
|
||||
|
||||
/// Selects `items` one path at a time: a clear, then an add and an anchor insert per path.
|
||||
fn one_by_one(sel: &mut Selection, items: Items) {
|
||||
sel.clear();
|
||||
for (id, refs) in items {
|
||||
sel.add(id);
|
||||
sel.anchors.insert(id, refs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, as one left by earlier selecting.
|
||||
fn busy() -> Selection {
|
||||
let mut sel = Selection::default();
|
||||
sel.set([NodeId(90), NodeId(91)]);
|
||||
sel.anchors.insert(NodeId(90), BTreeSet::from([(0, 0)]));
|
||||
sel.segments.insert(NodeId(91), BTreeSet::from([(0, 1)]));
|
||||
sel.key = Some(NodeId(91));
|
||||
sel.target = Some(NodeId(92));
|
||||
sel.slices = vec![NodeId(93)];
|
||||
sel.guides = vec![NodeId(94)];
|
||||
sel.key_guide = Some(NodeId(94));
|
||||
sel.key_anchor = Some((NodeId(90), (0, 0)));
|
||||
sel.symbol_part = Some(SymbolPart { instance: NodeId(95), path: vec![0, 1] });
|
||||
sel.on_path_member = Some(NodeId(96));
|
||||
sel.new_art = Arc::new(HashSet::from([NodeId(97)]));
|
||||
sel
|
||||
}
|
||||
|
||||
fn refs(n: usize) -> BTreeSet<(usize, usize)> {
|
||||
(0..n).map(|i| (0, i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_anchors_gives_the_selection_one_by_one_selecting_gives() {
|
||||
let cases: Vec<Items> = vec![
|
||||
vec![],
|
||||
vec![(NodeId(1), refs(4))],
|
||||
(1..=500).map(|i| (NodeId(i), refs(4))).collect(),
|
||||
// A path listed again keeps its first place and its last anchors.
|
||||
vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2)), (NodeId(2), BTreeSet::new()), (NodeId(1), refs(3))],
|
||||
];
|
||||
for items in cases {
|
||||
for start in [Selection::default(), busy()] {
|
||||
let (mut want, mut got) = (start.clone(), start);
|
||||
one_by_one(&mut want, items.clone());
|
||||
select_anchors(&mut got, items.clone());
|
||||
assert_eq!(got, want, "{items:?}");
|
||||
}
|
||||
}
|
||||
let mut got = busy();
|
||||
select_anchors(&mut got, vec![(NodeId(3), refs(1)), (NodeId(1), refs(4)), (NodeId(3), refs(2))]);
|
||||
assert_eq!(got.objects, vec![NodeId(3), NodeId(1)]);
|
||||
assert_eq!(got.anchors[&NodeId(3)], refs(2));
|
||||
assert!(got.segments.is_empty() && got.slices.is_empty() && got.guides.is_empty());
|
||||
assert_eq!((got.key, got.target, got.key_guide, got.key_anchor, got.on_path_member), (None, None, None, None, None));
|
||||
assert!(got.symbol_part.is_none());
|
||||
assert_eq!(*got.new_art, HashSet::from([NodeId(97)]), "selecting leaves the new-art list alone");
|
||||
}
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -200,14 +200,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("pencil")) => false,
|
||||
Some(Some("brush")) => true,
|
||||
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
|
||||
};
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("end")) => false,
|
||||
Some(Some("start")) => true,
|
||||
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
|
||||
};
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
@@ -488,12 +496,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
return Err(bad(C, "angle and roundness must be finite"));
|
||||
if !(0.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 0 to 100%"));
|
||||
}
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
|
||||
};
|
||||
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
|
||||
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
|
||||
}
|
||||
let angle = angle.clamp(-180.0, 180.0);
|
||||
let roundness = roundness.clamp(0.0, 100.0);
|
||||
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
@@ -515,13 +534,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
|
||||
};
|
||||
let spine = |tol: Option<f64>| {
|
||||
let path = match tol {
|
||||
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
|
||||
|
||||
@@ -399,9 +399,7 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
let compound = |n: &Node| matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. });
|
||||
let members = st.isolation.and_then(|i| st.doc.ancestry(i)).is_some_and(|a| a.iter().any(|i| st.doc.node(*i).is_some_and(compound)));
|
||||
let found: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
super::select::select_where(s, "document.find", p, |d, n| {
|
||||
found.contains(&n.id) && (members || !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
})
|
||||
super::select::select_where(s, "document.find", p, |_, n, parent| found.contains(&n.id) && (members || !parent.is_some_and(compound)))
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
|
||||
@@ -1040,7 +1040,8 @@ impl RasterBudget {
|
||||
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
/// the member's new id. `Err` when such a member still holds a random Transform effect after the
|
||||
/// raster budget left part of it as it is: its new ids would give that effect another seed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
@@ -1051,7 +1052,7 @@ fn expand_pieces(
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
) -> std::result::Result<std::collections::HashMap<NodeId, Vec<Listed>>, OverBudget> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = std::collections::HashMap::new();
|
||||
@@ -1065,7 +1066,12 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
let left = raster.left;
|
||||
let expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
return Err(OverBudget);
|
||||
}
|
||||
listed = Some(expanded);
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1086,7 +1092,7 @@ fn expand_pieces(
|
||||
expanded.insert(c.id, listed);
|
||||
}
|
||||
}
|
||||
expanded
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
|
||||
@@ -1301,6 +1307,19 @@ fn carries_copies(n: &Node) -> bool {
|
||||
is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len()
|
||||
}
|
||||
|
||||
/// Does `n`, something in it, or the art of the symbol it places when a color adjustment makes it
|
||||
/// that art, hold a random Transform effect ([`has_seeded`])? The raster budget can then leave `n`
|
||||
/// as it is after part of it expanded ([`expand_pieces`], Crop Marks).
|
||||
fn holds_seeded(d: &Document, n: &Node) -> bool {
|
||||
has_seeded(n)
|
||||
|| match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if effects::has_adjustment(n) => {
|
||||
d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| has_seeded(&s.art))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
@@ -1331,12 +1350,22 @@ fn expanded_node(
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment and the expansions of the copies
|
||||
// ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the
|
||||
// recolored copies and the images those add then go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n))
|
||||
// ([`copies_carrying_raster`]) and of the members that hold a random Transform effect, when the
|
||||
// raster budget may yet leave `n` as it is: the recolored copies and the images those add then
|
||||
// go again.
|
||||
let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n) || holds_seeded(d, &n))
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
// What the raster budget had left before those expansions: it gets back what they took.
|
||||
let budget_before = (raster.images, raster.pixels);
|
||||
// `n` stays as it is: `out` lists nothing of it, and the document and the raster budget lose
|
||||
// what expanding it added and took.
|
||||
let leave = |d: &mut Document, out: &mut Vec<Listed>, raster: &mut RasterBudget| {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = &images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
};
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1352,14 +1381,21 @@ fn expanded_node(
|
||||
let container = is_container(&n);
|
||||
// Crop Marks: the object and its marks become a group. The object expands on its own first,
|
||||
// with `id`: the canvas draws it with that id, which Random in a Transform effect takes its
|
||||
// seed from. Then the object and the marks get ids of their own.
|
||||
// seed from. Then the object and the marks get ids of their own. When the raster budget leaves
|
||||
// a random Transform effect in the object, `n` stays as it is: new ids would give that effect
|
||||
// another seed.
|
||||
if let Some(mut m) = effects::crop_marks_art(&n) {
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
let mut expanded = vec![];
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
let left = raster.left;
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
if raster.left > left && has_seeded(c) {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
}
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1390,16 +1426,13 @@ fn expanded_node(
|
||||
let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol), and
|
||||
// so does a group or layer whose copies keep a random Transform effect the budget left.
|
||||
// so does a group or layer whose copies or members keep a random Transform effect the budget
|
||||
// left.
|
||||
let Ok(image) = copies.and_then(|copied| {
|
||||
changed |= copied;
|
||||
raster_image(d, &n, raster)
|
||||
}) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
(raster.images, raster.pixels) = budget_before;
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
@@ -1413,18 +1446,20 @@ fn expanded_node(
|
||||
image => {
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok::<_, OverBudget>(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster));
|
||||
m
|
||||
})
|
||||
effects::evaluate_container(Some(&*d), &v)
|
||||
.map(|mut m| {
|
||||
members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)?);
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !effects::has_transform_art(&v)
|
||||
&& !effects::has_transform_copies(&v)
|
||||
{
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
Ok(effects::expand_leaf(d, &v, &mut stroke_art))
|
||||
} else {
|
||||
// Type, images, symbol instances, live objects (and paths whose Transform effect copies
|
||||
// them, each copy an object of its own, or changes their fills and strokes): through
|
||||
@@ -1440,12 +1475,18 @@ fn expanded_node(
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
outlined
|
||||
.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster)?;
|
||||
Ok(m)
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let Ok(m) = m else {
|
||||
leave(d, out, raster);
|
||||
return None;
|
||||
};
|
||||
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
|
||||
// expands in turn, to an image.
|
||||
|
||||
@@ -1189,3 +1189,90 @@ fn copies_the_raster_budget_leaves_keep_their_random_moves() {
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group whose Transform effect copies its symbol instance, which has a drop shadow and a random
|
||||
/// Transform effect that takes its seed from the instance's id: each copy's instance has that id.
|
||||
/// When the raster budget has no image left for a copy's shadow, with none left or with one for the
|
||||
/// first copy's, the group stays as it is: the copies keep the ids their random moves are drawn
|
||||
/// with, the group draws as before, and the document holds no image the first copy's expansion
|
||||
/// made, nor the budget its charge. With the whole budget, the group expands and each object gets
|
||||
/// an id of its own.
|
||||
#[test]
|
||||
fn a_member_the_raster_budget_leaves_keeps_its_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap());
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
for images in [0, 1, 1_024] {
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(g).cloned().unwrap();
|
||||
assert!(effects::outer_effects(&before).len() == before.appearance.effects.len(), "the copies carry no shadow of the group's");
|
||||
let art = effects::evaluate_container(Some(&d), &before).unwrap();
|
||||
let mut instances = 0;
|
||||
art.walk(&mut |n| instances += usize::from(n.id == id && super::has_seeded(n)));
|
||||
assert!(instances >= 2, "{images}: each copy's instance has the id and its random effect: {instances}");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, g, &[], &mut out, &mut budget);
|
||||
if images < 2 {
|
||||
assert!(budget.left > 0, "{images}: a shadow is left");
|
||||
assert!(out.is_empty(), "{images}: nothing expands: {out:?}");
|
||||
assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is");
|
||||
assert!(draw(&d) == drawn, "{images}: the group draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "{images}: no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took");
|
||||
} else {
|
||||
assert_eq!(budget.left, 0, "no shadow is left");
|
||||
assert!(!out.is_empty(), "the group expands");
|
||||
let (mut ids, mut count, mut seeded) = (std::collections::HashSet::new(), 0, false);
|
||||
d.node(g).unwrap().walk(&mut |n| {
|
||||
ids.insert(n.id);
|
||||
count += 1;
|
||||
seeded |= super::has_seeded(n);
|
||||
});
|
||||
assert_eq!(ids.len(), count, "each object has an id of its own");
|
||||
assert!(!seeded, "no random Transform effect is left");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object with Crop Marks, a drop shadow and a random Transform effect that takes its seed from
|
||||
/// the object's id stays as it is when the raster budget has no image left for its shadow: the
|
||||
/// object keeps its id and its random move, and draws as before.
|
||||
#[test]
|
||||
fn crop_marks_the_raster_budget_leaves_keep_their_random_move() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap();
|
||||
let random = json!({"moveH": 40, "moveV": 40, "random": true});
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "cropMarks", "params": {}})).unwrap();
|
||||
let draw = |d: &vectorcraft_doc::Document| {
|
||||
vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let before = d.node(id).cloned().unwrap();
|
||||
assert!(effects::crop_marks_art(&before).is_some(), "the object has crop marks");
|
||||
let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::<Vec<_>>());
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels: u64::MAX, left: 0 };
|
||||
let mut out = vec![];
|
||||
super::expand_node(&mut d, id, &[], &mut out, &mut budget);
|
||||
assert!(budget.left > 0, "the shadow is left");
|
||||
assert!(out.is_empty(), "nothing expands: {out:?}");
|
||||
assert_eq!(d.node(id), Some(&before), "the object stays as it is");
|
||||
assert!(draw(&d) == drawn, "the object draws as before");
|
||||
assert_eq!(d.images.keys().cloned().collect::<Vec<_>>(), keys, "no image is added");
|
||||
assert_eq!((budget.images, budget.pixels), (0, u64::MAX), "the budget is as it was");
|
||||
}
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, or while the row's file would name a linked image's file outside them, as document.export refuses it",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while t
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -241,7 +241,8 @@ struct RasterOptions {
|
||||
width: Option<f64>,
|
||||
/// The height of each file in pixels (wins over `ppi` and `scale`).
|
||||
height: Option<f64>,
|
||||
quality: Option<u8>,
|
||||
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
|
||||
quality: Option<Value>,
|
||||
background: Option<Value>,
|
||||
anti_alias: Option<String>,
|
||||
interlaced: Option<bool>,
|
||||
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
|
||||
/// 100; WebP refuses more than 100), or an error naming it.
|
||||
fn quality(&self) -> Result<Option<u8>> {
|
||||
match &self.quality {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|q| u8::try_from(q).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -311,7 +325,8 @@ impl RasterOptions {
|
||||
},
|
||||
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality.unwrap_or(90).min(100),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"psd" => RasterFormat::Psd,
|
||||
_ => RasterFormat::WebP,
|
||||
};
|
||||
if format == RasterFormat::WebP
|
||||
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
|
||||
|
||||
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
const WEBP_QUALITY: FormatOption = FormatOption {
|
||||
name: "quality",
|
||||
ty: "integer",
|
||||
default: "90",
|
||||
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
|
||||
};
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
|
||||
@@ -417,9 +417,13 @@ fn encode_carrying_at(
|
||||
}
|
||||
let (flat, flattened) = flatten_for(cmd, doc, set, p)?;
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if flattened {
|
||||
if let Some(o) = flattened {
|
||||
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
|
||||
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
|
||||
let line_ppi = o.line_art_ppi.round() as u32;
|
||||
let grad_ppi = o.gradient_ppi.round() as u32;
|
||||
notes.push(Note::loss(format!(
|
||||
"transparency is flattened into opaque art and images ({kind} files have none) at {line_ppi} ppi line art and text, {grad_ppi} ppi gradients and meshes: see the flattener preset"
|
||||
)));
|
||||
}
|
||||
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
notes.extend(r.warnings.into_iter().map(Note::loss));
|
||||
@@ -438,9 +442,9 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution";
|
||||
/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked
|
||||
/// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is)
|
||||
/// and whether its transparency was flattened.
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, bool)> {
|
||||
fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option<Document>, Option<FlattenOptions>)> {
|
||||
if !set.pdf13() {
|
||||
return Ok((None, false));
|
||||
return Ok((None, None));
|
||||
}
|
||||
let printed = if set.include_non_printing || set.create_layers { None } else { without_non_printing(&doc.layers) };
|
||||
let shown = printed.map(|layers| {
|
||||
@@ -456,8 +460,8 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul
|
||||
// its art: it is clipped to its regions (opaque inside them).
|
||||
o.clip_complex_regions = true;
|
||||
Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? {
|
||||
Some(flat) => (Some(flat), true),
|
||||
None => (shown, false),
|
||||
Some(flat) => (Some(flat), Some(o)),
|
||||
None => (shown, None),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -209,6 +209,8 @@ struct Row {
|
||||
options: Value,
|
||||
/// What makes two rows the same file: format, size, suffix and options.
|
||||
key: String,
|
||||
/// The row or the format's settings set `bleed` (a PDF row's own bleed, zero included).
|
||||
bleed_given: bool,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
@@ -248,12 +250,19 @@ impl Row {
|
||||
}
|
||||
// A file per artboard is for viewing: it doesn't carry the whole document to edit.
|
||||
options.entry("preserveEditing").or_insert(json!(false));
|
||||
let bleed_given = options.get("bleed").is_some_and(|b| !b.is_null());
|
||||
let options = Value::Object(options);
|
||||
// A PDF preset (built-in or saved) becomes its settings.
|
||||
let options = if format.id == "pdf" { super::pdf::expand_preset(s, C, &options)?.into_owned() } else { options };
|
||||
// Two rows that would write the same bytes under the same name are one file.
|
||||
let key = format!("{}|{}|{suffix}|{options}", format.id, size.label());
|
||||
Ok(Self { format, size, suffix, folder, options, key })
|
||||
let mut row = Self { format, size, suffix, folder, options, key: String::new(), bleed_given };
|
||||
row.key = row.file_key();
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
/// What makes two rows the same file: two rows that would write the same bytes under the same
|
||||
/// name are one file.
|
||||
fn file_key(&self) -> String {
|
||||
format!("{}|{}|{}|{}", self.format.id, self.size.label(), self.suffix, self.options)
|
||||
}
|
||||
|
||||
/// Formats that hold a whole document to edit (native, Illustrator, EPS): written from a
|
||||
@@ -525,6 +534,8 @@ fn rows_of(s: &Session, p: &Value, preset: Option<&str>) -> Result<Vec<Row>> {
|
||||
if let Some(m) = r.options.as_object_mut() {
|
||||
m.entry("antiAlias").or_insert_with(|| aa.clone());
|
||||
}
|
||||
// Two rows whose options are now the same are one file.
|
||||
r.key = r.file_key();
|
||||
}
|
||||
}
|
||||
Ok(rows)
|
||||
@@ -1137,17 +1148,22 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
|
||||
let selection = o.selection_mode()?;
|
||||
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let original = s.doc()?.doc.clone();
|
||||
// Include Bleed: each artboard grown by the document's bleed.
|
||||
let doc = if o.include_bleed && doc.setup.has_bleed() {
|
||||
let mut d = (*doc).clone();
|
||||
let grown = o.include_bleed && original.setup.has_bleed();
|
||||
let doc = if grown {
|
||||
let mut d = (*original).clone();
|
||||
for a in &mut d.artboards {
|
||||
a.rect = doc.setup.bleed_rect(a.rect);
|
||||
a.rect = original.setup.bleed_rect(a.rect);
|
||||
}
|
||||
Arc::new(d)
|
||||
} else {
|
||||
doc
|
||||
original.clone()
|
||||
};
|
||||
// A PDF page of an artboard keeps the artboard as its TrimBox and puts its row's bleed around
|
||||
// it once: it is written from the document with the artboards as they are. Assets, layers and
|
||||
// a selection are written on a page of their own bounds, which Include Bleed doesn't grow.
|
||||
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// Before the folder is made or any row is written, with the artboards each file holds.
|
||||
@@ -1164,8 +1180,26 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None };
|
||||
let rows = rows
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
// Include Bleed: a PDF row that sets no bleed of its own, and whose preset gives none,
|
||||
// puts the document's bleed around the artboard, and is the same file as a row that
|
||||
// asks for the document's bleed. A saved preset's bleed values stay, as they do in
|
||||
// that row.
|
||||
if ungrown.is_some() && r.format.id == "pdf" && !r.bleed_given && !pdf_bleeds(&r.options) {
|
||||
match r.options.get_mut("bleed").and_then(Value::as_object_mut) {
|
||||
Some(b) => {
|
||||
b.insert("useDocument".into(), json!(true));
|
||||
}
|
||||
None => r.options["bleed"] = json!({ "useDocument": true }),
|
||||
}
|
||||
r.key = r.file_key();
|
||||
}
|
||||
Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }
|
||||
})
|
||||
.collect();
|
||||
let export = ScreenExport { cmd: C, o, rows, naming, items, unused, hidden: None, ungrown };
|
||||
match &mut s.screens_hand_off {
|
||||
Some(slot) => {
|
||||
*slot = Some(export);
|
||||
@@ -1175,6 +1209,14 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
}
|
||||
}
|
||||
|
||||
/// Do the PDF `options` (a built-in preset's settings under them) give the pages a bleed: the
|
||||
/// document's, or a value above 0 on some side? Options the PDF encoder refuses count as giving
|
||||
/// one, so they are left as they are for the encoder to refuse.
|
||||
fn pdf_bleeds(options: &Value) -> bool {
|
||||
super::pdf::settings(C, options)
|
||||
.map_or(true, |s| s.bleed.use_document || [s.bleed.top, s.bleed.bottom, s.bleed.left, s.bleed.right].iter().any(|b| *b > 0.0))
|
||||
}
|
||||
|
||||
/// An export as `document.exportForScreens` and `assets.export` take it from the session: the
|
||||
/// params, the format rows, the naming, and each item with the document it writes
|
||||
/// ([`Session::prepare_screen_export`]). [`ScreenExport::write`] encodes and writes its files
|
||||
@@ -1192,6 +1234,9 @@ pub struct ScreenExport {
|
||||
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
|
||||
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
|
||||
hidden: Option<(String, String)>,
|
||||
/// Include Bleed with artboards: the document with the artboards as they are, which PDF rows
|
||||
/// write (the items hold the artboards grown by the bleed).
|
||||
ungrown: Option<Arc<Document>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -1252,7 +1297,7 @@ impl ScreenExport {
|
||||
|
||||
/// [`ScreenExport::write`].
|
||||
fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let ScreenExport { o, rows, naming, items, unused, .. } = export;
|
||||
let ScreenExport { o, rows, naming, items, unused, ungrown, .. } = export;
|
||||
let folder = o.folder.as_deref().filter(|f| !f.is_empty());
|
||||
if let Some(dir) = folder {
|
||||
create_dir(dir)?;
|
||||
@@ -1263,13 +1308,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
for text in unused {
|
||||
add_note(&mut notes, Note::setting(text));
|
||||
}
|
||||
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
|
||||
// written on a page of their own bounds, which it doesn't grow.
|
||||
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
// The document a PDF row writes: with Include Bleed, the artboards as they are.
|
||||
let pdf_doc = ungrown.as_deref();
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
|
||||
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
|
||||
for n in given {
|
||||
add_note(&mut notes, n);
|
||||
}
|
||||
Ok(bytes)
|
||||
@@ -1306,12 +1350,12 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
let bytes = if let Some(boards) = single {
|
||||
let mut options = r.options.clone();
|
||||
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
|
||||
write(&item.doc, "pdf", &options)?
|
||||
write(pdf_doc.unwrap_or(&item.doc), "pdf", &options)?
|
||||
} else if let (Some(all), "pdf") = (&item.every_artboard, r.format.id) {
|
||||
// One page per artboard.
|
||||
let mut options = r.options.clone();
|
||||
options["range"] = json!("all");
|
||||
write(all, "pdf", &options)?
|
||||
write(pdf_doc.unwrap_or(all), "pdf", &options)?
|
||||
} else if r.whole_document() && item.artboard.is_some() {
|
||||
let b = item.artboard.unwrap_or(0);
|
||||
// That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868).
|
||||
@@ -1334,7 +1378,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
}
|
||||
write(&d, r.format.id, &options)?
|
||||
} else {
|
||||
write(&item.doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
|
||||
let doc = if r.format.id == "pdf" { pdf_doc.unwrap_or(&item.doc) } else { &item.doc };
|
||||
write(doc, r.format.id, &r.options_for(item.region, item.artboard)?)?
|
||||
};
|
||||
out.put(folder, o.zip, name, bytes, writer)?;
|
||||
files += 1;
|
||||
|
||||
@@ -135,26 +135,25 @@ fn formats_list_use_artboards() {
|
||||
assert!(opts("vectorcraft").get("useArtboards").is_none());
|
||||
}
|
||||
|
||||
/// An export's reply gives what the file loses before its notes on the options, whatever order
|
||||
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
|
||||
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
|
||||
/// order.
|
||||
/// An export's reply gives what the file loses before its notes on the options: the type the
|
||||
/// export drew in the fallback font comes before the note on an option WebP doesn't read. With
|
||||
/// only notes on the options, they keep their order.
|
||||
#[test]
|
||||
fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
|
||||
let unused = "`interlaced` was not used: WebP files don't read it";
|
||||
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
|
||||
};
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "interlaced": true})), [unused]);
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
|
||||
let w = warnings(&mut s, json!({"format": "webp", "interlaced": true}));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
|
||||
assert_eq!(w[1], lossy);
|
||||
assert_eq!(w[1], unused);
|
||||
// document.serialize gives them in the same order.
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "interlaced": true})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
|
||||
@@ -830,3 +830,78 @@ fn flattening_keeps_the_group_in_the_clipping_layer_when_the_layer_below_differs
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// #6861: Layer opacity, blend modes, sublayers with transparency, and empty transparent layers:
|
||||
/// PDF/X-1a, PDF/X-3, and PDF 1.3 automatically flatten and reduce transparency without failing,
|
||||
/// and the output contains no transparency dictionary or soft mask.
|
||||
#[test]
|
||||
fn pdfx_flattens_layer_and_sublayer_transparency() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200, "colorMode": "cmyk"}));
|
||||
|
||||
// Bottom layer: base artwork
|
||||
let _layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}}));
|
||||
|
||||
// Middle layer with 50% opacity and Multiply blend mode
|
||||
let layer2 = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 1.0, "y": 0.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer2], "opacity": 50, "blendMode": "multiply"}));
|
||||
|
||||
// Sublayer inside layer2 with 70% opacity
|
||||
let sublayer = run(&mut s, "layer.newSublayer", json!({"parent": layer2}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 60, "y": 60, "width": 80, "height": 80}));
|
||||
run(&mut s, "paint.setFill", json!({"color": {"c": 0.0, "m": 0.0, "y": 1.0, "k": 0.0}}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [sublayer], "opacity": 70}));
|
||||
|
||||
// Empty layer with opacity (must not leave /CA or /ca in output)
|
||||
let empty_layer = run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "transparency.set", json!({"ids": [empty_layer], "opacity": 40}));
|
||||
|
||||
for standard in ["pdfX1a", "pdfX3"] {
|
||||
let (text, warnings) = pdf(&mut s, json!({"standard": standard}));
|
||||
assert!(text.starts_with("%PDF-1.3"), "{standard}");
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")), "{standard}: expected flattening warning");
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "{standard}: forbidden token '{no}' found in text:\n{text}");
|
||||
}
|
||||
// Verify it can be imported back and renders artwork
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let imported = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
assert!(!imported.layers.is_empty());
|
||||
let rendered = drawn(&imported);
|
||||
let non_white = rendered.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().any(|c| *c < 240)).count();
|
||||
assert!(non_white > 1000, "{standard}: flattened artwork failed to render, only {non_white} pixels");
|
||||
}
|
||||
|
||||
// PDF 1.3 export with compatibility: 1.3
|
||||
let (text, warnings) = pdf(&mut s, json!({"compatibility": "1.3", "preserveEditing": false}));
|
||||
assert!(text.starts_with("%PDF-1.3"));
|
||||
assert!(warnings.iter().any(|w| w.contains("flattened")));
|
||||
for no in ["/SMask", "/S/Transparency", "/ca ", "/CA "] {
|
||||
assert!(!text.contains(no), "PDF 1.3: forbidden token '{no}' found in text");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_outlining_does_not_wrap_layer_transparency_into_groups() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let layer1 = s.doc().unwrap().doc.layers[0].id.0;
|
||||
run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 80, "height": 80}));
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer1], "opacity": 60}));
|
||||
|
||||
let o = crate::cmd::FlattenOptions { text_to_outlines: true, ..Default::default() };
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let flattened = crate::cmd::flatten::flatten_expanded(&doc, &o).unwrap();
|
||||
let resulting_doc = flattened.as_ref().unwrap_or(&doc);
|
||||
assert_eq!(resulting_doc.layers.len(), 1);
|
||||
let l = &resulting_doc.layers[0];
|
||||
assert_eq!(l.opacity, 0.6);
|
||||
assert!(!matches!(l.children().unwrap()[0].kind, vectorcraft_doc::NodeKind::Group { .. }));
|
||||
}
|
||||
@@ -546,20 +546,19 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
|
||||
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
|
||||
}
|
||||
|
||||
/// What a later file loses comes before a note on the options that an earlier file gave: the
|
||||
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
|
||||
/// fit.
|
||||
/// What a later file loses comes before a note on the options: the second artboard's WebP says
|
||||
/// its type doesn't fit, before the note on the row's option that WebP doesn't read.
|
||||
#[test]
|
||||
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
let area = json!({"width": 30, "height": 8});
|
||||
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "interlaced": true}]}));
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("`formats[0].interlaced` was not used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -594,7 +593,8 @@ fn include_bleed_grows_each_artboard() {
|
||||
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
|
||||
}
|
||||
|
||||
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
|
||||
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the
|
||||
/// bleed out, unless the row sets a bleed of 0 itself.
|
||||
#[test]
|
||||
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
|
||||
let mut s = session(1);
|
||||
@@ -603,11 +603,103 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
|
||||
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
|
||||
assert!(warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
let zero = json!([{"format": "pdf", "standard": "pdfX4", "bleed": {"top": 0, "bottom": 0, "left": 0, "right": 0}}]);
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": zero}))), "the row's own bleed of 0 leaves the bleed out");
|
||||
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
|
||||
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
}
|
||||
|
||||
/// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read
|
||||
/// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries).
|
||||
fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
text.match_indices(key)
|
||||
.map(|(at, _)| {
|
||||
let mut words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']')).filter(|w| !w.is_empty());
|
||||
std::array::from_fn(|_| words.next().and_then(|w| w.parse().ok()).unwrap_or(f64::NAN))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A page's MediaBox, BleedBox and TrimBox sizes `(width, height)` in points, and the trim's
|
||||
/// distance from the bleed box's left and bottom edges.
|
||||
type PageSizes = ((f64, f64), (f64, f64), (f64, f64), (f64, f64));
|
||||
|
||||
/// [`PageSizes`] of each page of `pdf`.
|
||||
fn page_sizes(pdf: &[u8]) -> Vec<PageSizes> {
|
||||
let size = |b: &[f64; 4]| (b[2] - b[0], b[3] - b[1]);
|
||||
let (media, bleed, trim) = (raw_boxes(pdf, "/MediaBox"), raw_boxes(pdf, "/BleedBox"), raw_boxes(pdf, "/TrimBox"));
|
||||
assert!(!trim.is_empty() && media.len() == trim.len() && bleed.len() == trim.len(), "a MediaBox, BleedBox and TrimBox per page");
|
||||
(0..trim.len()).map(|i| (size(&media[i]), size(&bleed[i]), size(&trim[i]), (trim[i][0] - bleed[i][0], trim[i][1] - bleed[i][1]))).collect()
|
||||
}
|
||||
|
||||
/// With Include Bleed, a PDF page keeps the artboard as its TrimBox and puts the bleed around it
|
||||
/// once (PDF 32000-1:2008, 14.11.2: the trim box is the finished page, the bleed box holds it): the
|
||||
/// document's bleed when the row asks for it or sets none, else the row's own values.
|
||||
#[test]
|
||||
fn include_bleed_pdf_pages_trim_at_the_artboard() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("document.setup", &json!({"bleed": 9})).unwrap();
|
||||
let pages = |s: &mut Session, p: Value| -> Vec<PageSizes> {
|
||||
let r = export(s, p);
|
||||
files(&r).iter().filter(|(n, _)| n.ends_with(".pdf")).flat_map(|(_, b)| page_sizes(b)).collect()
|
||||
};
|
||||
let one = |media: f64, bleed: f64, trim: f64| ((media, media), (bleed, bleed), (trim, trim), ((bleed - trim) / 2.0, (bleed - trim) / 2.0));
|
||||
let document = json!({"format": "pdf", "bleed": {"useDocument": true}});
|
||||
let sides = |b: f64| json!({"top": b, "bottom": b, "left": b, "right": b});
|
||||
for (p, want) in [
|
||||
(json!({"includeBleed": true, "artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
|
||||
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}]}), one(118.0, 118.0, 100.0)),
|
||||
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "preset": "High Quality Print"}]}), one(118.0, 118.0, 100.0)),
|
||||
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(3.0)}]}), one(106.0, 106.0, 100.0)),
|
||||
(json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": sides(0.0)}]}), one(100.0, 100.0, 100.0)),
|
||||
(json!({"artboard": 0, "formats": [document]}), one(118.0, 118.0, 100.0)),
|
||||
(json!({"artboard": 0, "formats": [{"format": "pdf"}]}), one(100.0, 100.0, 100.0)),
|
||||
] {
|
||||
assert_eq!(pages(&mut s, p.clone()), [want], "{p}");
|
||||
}
|
||||
// Every page of a single file and of the Full Document, each artboard its own trim.
|
||||
for p in [
|
||||
json!({"includeBleed": true, "pdfs": "single", "formats": [document]}),
|
||||
json!({"includeBleed": true, "fullDocument": true, "formats": [document]}),
|
||||
] {
|
||||
assert_eq!(pages(&mut s, p.clone()), [one(118.0, 118.0, 100.0); 2], "{p}");
|
||||
}
|
||||
// A row with printer's marks: the sheet grows past the bleed box for them, around the same trim.
|
||||
let marked = pages(
|
||||
&mut s,
|
||||
json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf", "bleed": {"useDocument": true}, "marks": {"trim": true}}]}),
|
||||
);
|
||||
let [(media, bleed, trim, at)] = marked[..] else { panic!("one page: {marked:?}") };
|
||||
assert_eq!((bleed, trim, at), ((118.0, 118.0), (100.0, 100.0), (9.0, 9.0)));
|
||||
assert!(media.0 > 118.0 && media.1 > 118.0, "{media:?}");
|
||||
// A row that sets no bleed writes the same file as one that asks for the document's: one file.
|
||||
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [{"format": "pdf"}, document]}));
|
||||
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
|
||||
// So does it with a top-level anti-aliasing mode, which both rows take.
|
||||
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "antiAlias": "art", "formats": [{"format": "pdf"}, document]}));
|
||||
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
|
||||
// And with a saved PDF preset, which writes out every bleed value for both rows.
|
||||
s.execute("pdf.preset.save", &json!({"name": "Saved Default"})).unwrap();
|
||||
let saved = |bleed: Option<Value>| {
|
||||
let mut row = json!({"format": "pdf", "preset": "Saved Default"});
|
||||
if let Some(b) = bleed {
|
||||
row["bleed"] = b;
|
||||
}
|
||||
row
|
||||
};
|
||||
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None), saved(Some(json!({"useDocument": true})))]}));
|
||||
assert_eq!(names(&r).len(), 1, "{:?}", names(&r));
|
||||
assert_eq!(pages(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [saved(None)]})), [one(118.0, 118.0, 100.0)]);
|
||||
// A raster row of the same export still holds the bleed in its pixels.
|
||||
let r = export(&mut s, json!({"includeBleed": true, "artboard": 0, "formats": [document, {"format": "png"}]}));
|
||||
let png = files(&r).into_iter().find(|(n, _)| n.ends_with(".png")).unwrap().1;
|
||||
assert_eq!(size(&png), (118, 118));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_8_rows_write_indexed_colour() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -53,41 +53,115 @@ fn text_export_writes_the_stories_in_stacking_order() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The chunk types of RIFF WebP file `file`, in order.
|
||||
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
|
||||
let mut chunks = Vec::new();
|
||||
let mut at = 12;
|
||||
while at + 8 <= file.len() {
|
||||
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
|
||||
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// The size and straight RGBA pixels of image file `file`.
|
||||
fn rgba(file: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
let (w, h) = img.dimensions();
|
||||
(w, h, img.to_rgba8())
|
||||
}
|
||||
|
||||
/// A 120 × 80 pt document filled with a grid of rectangles in 96 colors.
|
||||
fn varied_art() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 120, "height": 80})).unwrap();
|
||||
for row in 0..8 {
|
||||
for col in 0..12 {
|
||||
s.execute("shape.rectangle", &json!({"x": col * 10, "y": row * 10, "width": 10, "height": 10})).unwrap();
|
||||
let color = format!("#{:02x}{:02x}{:02x}", col * 21, row * 32, (col * 7 + row * 23) % 256);
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
|
||||
fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
let mut s = varied_art();
|
||||
let export = |s: &mut Session, p: Value| -> (Vec<u8>, Value) {
|
||||
let r = s.execute("document.export", &merge(json!({"format": "webp", "background": "white"}), p)).unwrap();
|
||||
(b64(&r), r["warnings"].clone())
|
||||
};
|
||||
let (lossless, warnings) = export(&mut s, json!({}));
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
assert_eq!(warnings, json!([]));
|
||||
// Quality doesn't change a lossless file.
|
||||
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
|
||||
|
||||
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
|
||||
assert_eq!(warnings, json!([]), "no note: the file is lossy");
|
||||
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
|
||||
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
assert_eq!((w, h), (120, 80));
|
||||
let diff: u64 = exact.iter().zip(&near).map(|(a, b)| u64::from(a.abs_diff(*b))).sum();
|
||||
let mean = diff as f64 / exact.len() as f64;
|
||||
assert!(mean <= 4.0, "mean difference {mean}");
|
||||
// Lower quality, smaller file.
|
||||
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
|
||||
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
|
||||
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
|
||||
for q in [0, 100] {
|
||||
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_webp_keeps_translucent_pixels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "webp"})).unwrap();
|
||||
let file = b64(&r);
|
||||
assert_eq!((&file[..4], &file[8..12], &file[12..16]), (&b"RIFF"[..], &b"WEBP"[..], &b"VP8L"[..]), "lossless bitstream");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
|
||||
assert_eq!(&b64(&r)[12..16], b"VP8L");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
|
||||
assert_eq!(
|
||||
craft_image_codecs::decode(&b64(&r))
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8()
|
||||
.get_pixel(29, 19)
|
||||
.0,
|
||||
[0, 0, 0, 255]
|
||||
);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
|
||||
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
|
||||
let i = 4 * (y * w + x) as usize;
|
||||
[px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||||
};
|
||||
// The alpha is written exactly: half covered under the rectangle, clear past it.
|
||||
let alphas = |px: &[u8]| px.chunks(4).map(|p| p[3]).collect::<Vec<u8>>();
|
||||
assert_eq!(alphas(&near), alphas(&exact));
|
||||
assert!((120..=135).contains(&at(&near, 5, 5)[3]), "{:?}", at(&near, 5, 5));
|
||||
assert_eq!(at(&near, 28, 10)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_quality_out_of_its_range_is_refused() {
|
||||
let mut s = varied_art();
|
||||
for q in [json!(101), json!(255), json!(256), json!(-1), json!(60.5), json!("high"), json!(true)] {
|
||||
let p = json!({"format": "webp", "lossless": false, "quality": q});
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("quality"), "{q}: {e}");
|
||||
// In Export for Screens too, in a row or in the format's settings.
|
||||
let row = json!({"formats": [{"format": "webp", "lossless": false, "quality": q}]});
|
||||
assert!(s.execute("document.exportForScreens", &row).is_err(), "{q}");
|
||||
let settings = json!({"formats": [{"format": "webp"}], "settings": {"webp": {"lossless": false, "quality": q}}});
|
||||
assert!(s.execute("document.exportForScreens", &settings).is_err(), "{q}");
|
||||
}
|
||||
// A lossless file refuses it as well: the value is not a WebP quality.
|
||||
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
|
||||
let file = b64(&r["files"][0]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,8 +5,8 @@ use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
Knockout, MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes,
|
||||
planes_cmyk, po, separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
// ---------- plan ----------
|
||||
@@ -756,27 +756,140 @@ pub(crate) fn flatten_document(doc: &Document, o: &FlattenOptions) -> Result<Opt
|
||||
Ok(flatten_expanded(expanded.as_ref().unwrap_or(doc), o)?.or(expanded))
|
||||
}
|
||||
|
||||
fn has_layer_container_transparency(n: &Node) -> bool {
|
||||
!n.has_default_transparency() || n.children().into_iter().flatten().any(|c| c.is_layer() && has_layer_container_transparency(c))
|
||||
}
|
||||
|
||||
/// [`flatten_document`] for `doc` whose pattern tile images were expanded already
|
||||
/// ([`expand_transparent_tile_images`]).
|
||||
pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Option<Document>> {
|
||||
let outlining = o.text_to_outlines || o.strokes_to_outlines || !o.preserve_overprints;
|
||||
if !outlining && !doc.layers.iter().any(|l| o.shows_transparency(doc, l) || o.draws_see_through_image(l)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut roots = vec![];
|
||||
for l in doc.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(doc, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
let needs_flatten = outlining
|
||||
|| doc.layers.iter().any(|l| {
|
||||
(o.no_transparency.is_some() && has_layer_container_transparency(l)) || o.shows_transparency(doc, l) || o.draws_see_through_image(l)
|
||||
});
|
||||
if !needs_flatten {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let changed = o.no_transparency.is_some() && normalize_layer_transparency(&mut d, o);
|
||||
let mut roots = vec![];
|
||||
for l in d.layers.iter().filter(|l| l.visible && !matches!(l.kind, NodeKind::Layer { template: true, .. })) {
|
||||
let children = l.children().map_or(&[][..], Vec::as_slice);
|
||||
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
|
||||
}
|
||||
let plan = plan(&d, &roots, o, true)?;
|
||||
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
|
||||
if changed {
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
return Ok(Some(d));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
apply(&mut d, &mut vectorcraft_doc::Selection::default(), plan, o)?;
|
||||
if o.no_transparency.is_some() {
|
||||
for l in &mut d.layers {
|
||||
sanitize_container_transparency(Arc::make_mut(l));
|
||||
}
|
||||
}
|
||||
Ok(Some(d))
|
||||
}
|
||||
|
||||
/// Flatten and normalize container-level transparency (on layers and sublayers) into groups
|
||||
/// so that the flattener's plan includes them and leaves no container transparency behind.
|
||||
fn normalize_layer_transparency(d: &mut Document, o: &FlattenOptions) -> bool {
|
||||
if o.no_transparency.is_none() {
|
||||
return false;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut layers = std::mem::take(&mut d.layers);
|
||||
for l in &mut layers {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(l));
|
||||
}
|
||||
d.layers = layers;
|
||||
changed
|
||||
}
|
||||
|
||||
fn clear_transparency(n: &mut Node) {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
n.isolate = false;
|
||||
n.knockout = Knockout::Neutral;
|
||||
n.knockout_shape = false;
|
||||
n.extras_mut().mask = None;
|
||||
n.appearance = Appearance::default().into();
|
||||
}
|
||||
|
||||
fn normalize_node_transparency(d: &mut Document, n: &mut Node) -> bool {
|
||||
let mut changed = false;
|
||||
let is_layer = n.is_layer();
|
||||
let clips = n.clips();
|
||||
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_layer() {
|
||||
changed |= normalize_node_transparency(d, Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let has_transparency = !n.has_default_transparency() || n.shows_own_transparency();
|
||||
|
||||
if is_layer && has_transparency {
|
||||
let children = n.children().map_or(&[][..], Vec::as_slice);
|
||||
let (guides, art): (Vec<_>, Vec<_>) = children.iter().cloned().partition(|c| c.is_ruler_guide());
|
||||
|
||||
if art.is_empty() {
|
||||
clear_transparency(n);
|
||||
n.set_clips(false);
|
||||
changed = true;
|
||||
} else {
|
||||
let mut g = Node::group(d.alloc_id(), art);
|
||||
if clips {
|
||||
g.set_clips(true);
|
||||
}
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.isolate = n.isolate;
|
||||
g.knockout = n.knockout;
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.appearance = n.appearance.clone();
|
||||
g.extras_mut().mask = n.extras_mut().mask.take();
|
||||
|
||||
n.set_clips(false);
|
||||
clear_transparency(n);
|
||||
|
||||
let mut new_children = vec![Arc::new(g)];
|
||||
new_children.extend(guides);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = new_children;
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
} else if is_layer && !n.visible {
|
||||
clear_transparency(n);
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn sanitize_container_transparency(n: &mut Node) {
|
||||
if n.is_container() {
|
||||
clear_transparency(n);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.is_container() {
|
||||
sanitize_container_transparency(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- apply ----------
|
||||
|
||||
pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan: Plan, o: &FlattenOptions) -> Result<(Vec<NodeId>, usize, usize)> {
|
||||
|
||||
@@ -26,7 +26,9 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::intertwine::{Face, drawn_order, face_at, faces_in, faces_of, is_intertwine, nonempty, painted_areas};
|
||||
use vectorcraft_tools::intertwine::{
|
||||
Face, drawn_order, face_at, faces_in, faces_of, in_intertwine, is_intertwine, nonempty, painted_areas, refused_member,
|
||||
};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::Beside;
|
||||
@@ -106,17 +108,7 @@ fn refused(d: &Document, n: &Node) -> Option<&'static str> {
|
||||
if around.iter().filter(|a| **a != n.id).filter_map(|a| d.node(*a)).any(is_intertwine) {
|
||||
return Some("an object already in an Intertwine group");
|
||||
}
|
||||
let mut why = None;
|
||||
n.walk(&mut |c| {
|
||||
why = why.or(match &c.kind {
|
||||
NodeKind::Intertwine { .. } => Some("an Intertwine group"),
|
||||
NodeKind::Repeat(_) => Some("a Repeat"),
|
||||
NodeKind::Group { .. } if c.extras().graph.is_some() => Some("a graph"),
|
||||
NodeKind::Group { .. } if vectorcraft_tools::builder::is_live_paint(c) => Some("a Live Paint group"),
|
||||
_ => None,
|
||||
});
|
||||
});
|
||||
why
|
||||
refused_member(n)
|
||||
}
|
||||
|
||||
fn make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -179,10 +171,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
.flatten()
|
||||
.map(|c| {
|
||||
let mut c = (**c).clone();
|
||||
let mut e = c.extras_mut();
|
||||
e.intertwine = None;
|
||||
e.intertwine_tiers = Vec::new();
|
||||
drop(e);
|
||||
without_areas(&mut c);
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
@@ -196,6 +185,92 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
// ---------- members that come and go ----------
|
||||
|
||||
/// Why `n` can't go into `parent`, an Intertwine group or a container inside one, if it can't
|
||||
/// ([`refused_member`]). Other containers take it as they did.
|
||||
pub(crate) fn refused_in(d: &Document, parent: Option<NodeId>, n: &Node) -> Option<&'static str> {
|
||||
parent.filter(|p| in_intertwine(d, *p)).and_then(|_| refused_member(n))
|
||||
}
|
||||
|
||||
/// The Intertwine groups that `ids` are members of, each once.
|
||||
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
ids.iter().filter_map(|i| d.parent_of(*i)).filter(|g| d.node(*g).is_some_and(is_intertwine) && seen.insert(*g)).collect()
|
||||
}
|
||||
|
||||
/// `n` without the areas it is drawn over other members in.
|
||||
fn without_areas(n: &mut Node) {
|
||||
if n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty() {
|
||||
let mut e = n.extras_mut();
|
||||
e.intertwine = None;
|
||||
e.intertwine_tiers = Vec::new();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Intertwine group `g` has nothing of its own that changes how its members are drawn:
|
||||
/// it is visible and unlocked, with full opacity, normal blending, no appearance and no extras
|
||||
/// (an opacity mask among them).
|
||||
fn bare(g: &Node) -> bool {
|
||||
let plain = Node::new(g.id, NodeKind::Intertwine { children: vec![] });
|
||||
(g.visible, g.locked, g.opacity, g.blend, g.isolate, g.knockout, g.knockout_shape)
|
||||
== (plain.visible, plain.locked, plain.opacity, plain.blend, plain.isolate, plain.knockout, plain.knockout_shape)
|
||||
&& g.appearance == plain.appearance
|
||||
&& *g.extras() == *plain.extras()
|
||||
}
|
||||
|
||||
/// After objects moved in the Layers panel: each of `placed` (the objects now in place, each with
|
||||
/// the container it came from, None for a copy) that is not in the container it came from loses
|
||||
/// the areas it was drawn over other members in, so it joins an Intertwine group at no tier and
|
||||
/// leaves one as ordinary art. Then each of `left` (the Intertwine groups objects came from) that
|
||||
/// has fewer than two members is taken apart: its one member goes in its place without areas, and
|
||||
/// an empty one is removed. A group with one member and something of its own ([`bare`]) becomes a
|
||||
/// plain group of that member instead, keeping its id and all it has. The other members keep their
|
||||
/// areas.
|
||||
pub(crate) fn settle_members(d: &mut Document, placed: &[(NodeId, Option<NodeId>)], left: &[NodeId]) -> Result<()> {
|
||||
for (id, from) in placed {
|
||||
if d.node(*id).is_some_and(|n| n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty())
|
||||
&& from.is_none_or(|f| d.parent_of(*id) != Some(f))
|
||||
{
|
||||
without_areas(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?);
|
||||
}
|
||||
}
|
||||
let lone: Vec<NodeId> =
|
||||
left.iter().copied().filter(|g| d.node(*g).is_some_and(|n| is_intertwine(n) && n.children().is_none_or(|c| c.len() < 2))).collect();
|
||||
let (kept, lone): (Vec<NodeId>, Vec<NodeId>) =
|
||||
lone.into_iter().partition(|g| d.node(*g).is_some_and(|n| n.children().is_some_and(|c| c.len() == 1) && !bare(n)));
|
||||
for g in &kept {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if let NodeKind::Intertwine { children } = &mut n.kind {
|
||||
let children = std::mem::take(children)
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let mut c = (*c).clone();
|
||||
without_areas(&mut c);
|
||||
Arc::new(c)
|
||||
})
|
||||
.collect();
|
||||
n.kind = NodeKind::Group { children, clip: false };
|
||||
}
|
||||
}
|
||||
let mut apart = Beside::replacing(d, &lone);
|
||||
for g in &lone {
|
||||
let Some(n) = d.node(*g) else { continue };
|
||||
let members: Vec<Node> = n
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| {
|
||||
let mut c = (**c).clone();
|
||||
without_areas(&mut c);
|
||||
c
|
||||
})
|
||||
.collect();
|
||||
apart.put(d, *g, members)?;
|
||||
}
|
||||
apart.finish(d)
|
||||
}
|
||||
|
||||
// ---------- Expand ----------
|
||||
|
||||
/// Replace Intertwine group `id` by a plain group of the art it draws
|
||||
|
||||
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Rows",
|
||||
[],
|
||||
None,
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
"{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}",
|
||||
has_doc,
|
||||
move_rows
|
||||
),
|
||||
@@ -119,7 +119,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder",
|
||||
[],
|
||||
None,
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers), deselecting every selected object left hidden or locked (the key object too)",
|
||||
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)",
|
||||
has_doc,
|
||||
move_node
|
||||
),
|
||||
@@ -242,14 +242,15 @@ pub(crate) fn row_roots(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// Whether `parent` (None: the top level) can hold `n`: layers go at the top level or in layers,
|
||||
/// anything else in layers and groups.
|
||||
/// anything else in layers, groups and Intertwine groups (which also check what the object holds:
|
||||
/// [`super::intertwine::refused_in`]).
|
||||
pub(crate) fn accepts(d: &Document, parent: Option<NodeId>, n: &Node) -> bool {
|
||||
match parent {
|
||||
None => n.is_layer(),
|
||||
Some(p) => match d.node(p).map(|x| &x.kind) {
|
||||
Some(NodeKind::Layer { .. }) => true,
|
||||
// A ruler guide stays directly in a layer or sublayer.
|
||||
Some(NodeKind::Group { .. }) => !n.is_layer() && !n.is_ruler_guide(),
|
||||
Some(NodeKind::Group { .. } | NodeKind::Intertwine { .. }) => !n.is_layer() && !n.is_ruler_guide(),
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
@@ -791,10 +792,17 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() });
|
||||
return Err(bad(C, format!("{} can't go into {into}", n.display_name())));
|
||||
}
|
||||
if let Some(what) = nodes.iter().find_map(|n| super::intertwine::refused_in(d, parent, n)) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
if parent.is_some_and(|p| locked_within(d, p)) {
|
||||
return Err(EngineError::Other("the layer or group is locked".into()));
|
||||
}
|
||||
let label = if copy { "Duplicate Rows" } else { "Move Rows" };
|
||||
// Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the
|
||||
// Intertwine groups it leaves.
|
||||
let from: std::collections::HashMap<NodeId, Option<NodeId>> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect();
|
||||
let left = if copy { vec![] } else { super::intertwine::groups_of(d, &ids) };
|
||||
let moved = s.edit(label, |d, sel| {
|
||||
let nodes = if copy {
|
||||
let mut nodes = vec![];
|
||||
@@ -829,6 +837,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if copy {
|
||||
super::typecmd::refresh_bounds_of(d, &out);
|
||||
}
|
||||
let placed: Vec<(NodeId, Option<NodeId>)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect();
|
||||
super::intertwine::settle_members(d, &placed, &left)?;
|
||||
sel.prune(d);
|
||||
sel.deselect_uneditable(d);
|
||||
Ok(out)
|
||||
@@ -848,8 +858,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !accepts(d, parent, n) {
|
||||
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
|
||||
}
|
||||
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
|
||||
return Err(bad(C, format!("{what} can't be intertwined")));
|
||||
}
|
||||
let from = d.parent_of(id);
|
||||
let left = super::intertwine::groups_of(d, &[id]);
|
||||
s.edit("Reorder", |d, sel| {
|
||||
d.move_node(id, parent, index)?;
|
||||
super::intertwine::settle_members(d, &[(id, from)], &left)?;
|
||||
sel.prune(d);
|
||||
sel.deselect_uneditable(d);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -92,7 +92,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => defaults,
|
||||
};
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
|
||||
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
|
||||
@@ -364,29 +364,91 @@ fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
|
||||
pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.options";
|
||||
let Some((_, cur, _)) = selected_spec(s) else {
|
||||
let id = crate::cmd::object_param(p, "id", C)?;
|
||||
let target = match id {
|
||||
Some(id) => {
|
||||
let doc = &s.doc()?.doc;
|
||||
match doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { .. }) if !doc.is_editable(id) => return Err(bad(C, "the object is hidden or locked")),
|
||||
Some(NodeKind::Blend { spec, children }) => Some((id, (**spec).clone(), children.iter().map(|c| c.id).collect())),
|
||||
_ => return Err(bad(C, "not a blend")),
|
||||
}
|
||||
}
|
||||
None => selected_spec(s),
|
||||
};
|
||||
let Some((_, cur, _)) = target else {
|
||||
if ["easingType", "ramp", "colorShift"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad(C, "select a blend to set easing or color shift"));
|
||||
}
|
||||
// Nothing to set them on: the options new blends start with (easing is per blend).
|
||||
let d = s.prefs.blend_options.unwrap_or_default();
|
||||
let spacing = spacing_param(p, C, d.spacing)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
|
||||
let orientation = orientation_param(p, C, d.orientation)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation, ..d });
|
||||
return Ok(json!({ "defaults": true }));
|
||||
};
|
||||
if gives_easing(p) && any_without_spine(s) {
|
||||
let no_spine = if id.is_some() { cur.no_spine } else { any_without_spine(s) };
|
||||
if gives_easing(p) && no_spine {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
// Every value is checked before anything changes. Each blend then takes only the values that
|
||||
// were given and keeps its own for the rest, so editing several blends does not copy the first
|
||||
// one's options onto the others.
|
||||
let given = |key: &str| p.get(key).is_some_and(|v| !v.is_null());
|
||||
let has_count = given("value") || given("steps") || given("distance");
|
||||
let has_spacing = given("spacing") || has_count || p.get("smooth").and_then(Value::as_bool) == Some(true);
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let orientation = orientation_param(p, C, cur.orientation)?;
|
||||
let ease = ease_param(p, C, cur.ease)?;
|
||||
let color_shift = percent_param(p, C, "colorShift", cur.color_shift, -100.0)?;
|
||||
edit_blends(s, "Blend Options", |_, spec| {
|
||||
spec.spacing = spacing;
|
||||
spec.orientation = orientation;
|
||||
spec.ease = ease;
|
||||
spec.color_shift = color_shift;
|
||||
})
|
||||
let (has_orientation, has_kind, has_ramp, has_shift) = (given("orientation"), given("easingType"), given("ramp"), given("colorShift"));
|
||||
let set = |spec: &mut BlendSpec| {
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode.
|
||||
let same_mode = std::mem::discriminant(&spacing) == std::mem::discriminant(&spec.spacing);
|
||||
if has_spacing && (has_count || !same_mode) {
|
||||
spec.spacing = spacing;
|
||||
}
|
||||
if has_orientation {
|
||||
spec.orientation = orientation;
|
||||
}
|
||||
if has_kind {
|
||||
spec.ease.kind = ease.kind;
|
||||
}
|
||||
if has_ramp {
|
||||
spec.ease.ramp = ease.ramp;
|
||||
}
|
||||
if has_shift {
|
||||
spec.color_shift = color_shift;
|
||||
}
|
||||
};
|
||||
let targets = match id {
|
||||
Some(id) => vec![id],
|
||||
None => selected_of(s, is_blend),
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let changes = |b: &NodeId| match doc.node(*b).map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => {
|
||||
let mut next = (**spec).clone();
|
||||
set(&mut next);
|
||||
next != **spec
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !targets.iter().any(changes) {
|
||||
return ok();
|
||||
}
|
||||
match id {
|
||||
Some(id) => {
|
||||
s.edit("Blend Options", |d, _| {
|
||||
if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
set(spec);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
None => edit_blends(s, "Blend Options", |_, spec| set(spec)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blend Options…",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends; easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (omitted ones keep their value; out of range is an error); with no blend selected, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
"{id?: id, spacing?: smooth|steps|distance, value?: n, steps?: n, distance?: pt, orientation?: page|path, smooth?: bool, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct} set the options of the selected blends (or of the blend `id` alone; a hidden or locked one is an error); easingType chooses the distribution, ramp sets its strength (0..100; 0 = even), colorShift (-100..100; 0 = even) shifts colours independently of shape/position easing (each blend keeps its own value for every option omitted; out of range is an error and changes nothing; no undo step when nothing changes); with no blend selected and no `id`, the options new blends start with (spacing and orientation only; a tool setting, not an undo step) → {defaults?: true}",
|
||||
always,
|
||||
blend_options
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::mesh::whole;
|
||||
use super::{
|
||||
Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, str_param, switch_or,
|
||||
bad, check_numbers, has_selection, json, named_ids, selected_roots, switch_or, text_param,
|
||||
};
|
||||
|
||||
pub(super) fn ids_json(ids: &[NodeId]) -> Value {
|
||||
@@ -128,8 +128,11 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
let smooth = switch_or(p, "smooth", false, cmd)?;
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64);
|
||||
let steps = |k: &str, n: f64| whole(n, k, cmd).map(|n| BlendSpacing::Steps(n as u32));
|
||||
let mode = str_param(p, "spacing");
|
||||
let mode = text_param(p, "spacing", cmd)?;
|
||||
let value = num("value");
|
||||
if mode.is_none() && value.is_some() {
|
||||
return Err(bad(cmd, "`value` needs `spacing` (steps|distance)"));
|
||||
}
|
||||
let sp = match mode {
|
||||
Some("smooth") | Some("smoothColor") => BlendSpacing::SmoothColor,
|
||||
Some("steps") => match value {
|
||||
@@ -157,11 +160,15 @@ pub(super) fn spacing_param(p: &Value, cmd: &str, current: BlendSpacing) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn orientation_param(p: &Value, current: BlendOrientation) -> BlendOrientation {
|
||||
match str_param(p, "orientation") {
|
||||
Some("path") | Some("alignToPath") => BlendOrientation::AlignToPath,
|
||||
Some("page") | Some("alignToPage") => BlendOrientation::AlignToPage,
|
||||
_ => current,
|
||||
/// `orientation`: `page` or `path`; missing or null keeps `current`, and any other value is an error.
|
||||
pub(super) fn orientation_param(p: &Value, cmd: &str, current: BlendOrientation) -> Result<BlendOrientation> {
|
||||
match p.get("orientation").filter(|v| !v.is_null()) {
|
||||
None => Ok(current),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("path") | Some("alignToPath") => Ok(BlendOrientation::AlignToPath),
|
||||
Some("page") | Some("alignToPage") => Ok(BlendOrientation::AlignToPage),
|
||||
_ => Err(bad(cmd, "orientation must be page or path")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -80,11 +80,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value>
|
||||
if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Send to Current Layer", |d, _| {
|
||||
let placed: Vec<(NodeId, Option<NodeId>)> = ids.iter().map(|i| (*i, st.doc.parent_of(*i))).collect();
|
||||
let left = crate::cmd::intertwine::groups_of(&st.doc, &ids);
|
||||
s.edit("Send to Current Layer", |d, sel| {
|
||||
let moved = d.remove_many(&ids)?;
|
||||
let ch = d.children_mut(Some(layer))?;
|
||||
let at = Node::guide_run_start(ch);
|
||||
ch.splice(at..at, moved);
|
||||
// Members sent out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
sel.prune(d);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
can_distribute,
|
||||
distribute
|
||||
),
|
||||
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute Spacing",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
can_distribute,
|
||||
distribute_spacing
|
||||
),
|
||||
|
||||
@@ -153,6 +153,20 @@ fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTre
|
||||
fonts
|
||||
}
|
||||
|
||||
/// The document whose links are copied beside the placed file `name` (`bytes`), which is copied
|
||||
/// as it is: a `.ai` file's editing data ([`super::place::document::editing_data`]), or the native
|
||||
/// document an EPS or PostScript file carries, which placing it reads. `None` for other files and
|
||||
/// for data that can't be read.
|
||||
fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if let Some(doc) = super::place::document::editing_data(name, bytes) {
|
||||
return Some(doc);
|
||||
}
|
||||
if !super::place::document::is_postscript(bytes) {
|
||||
return None;
|
||||
}
|
||||
vectorcraft_format::load(&vectorcraft_eps::native(bytes)?).ok()
|
||||
}
|
||||
|
||||
/// Collect dependencies depth-first so nested VectorCraft files are rewritten before
|
||||
/// their parents: each parent can record the final hash of the rewritten child.
|
||||
/// Cycles, excessive nesting, and unreadable children are reported, not fatal.
|
||||
@@ -200,7 +214,7 @@ impl<'a> Collector<'a> {
|
||||
self.warnings.push(message);
|
||||
}
|
||||
|
||||
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
|
||||
/// Warns when a file that placed `.ai` or EPS file `source` links (`name`) was copied as `copy`: the
|
||||
/// copy of `source` finds it only by its name, beside it.
|
||||
/// `path` is the link's path as the warning names it.
|
||||
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
|
||||
@@ -213,8 +227,8 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` file's editing data,
|
||||
/// whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// Collects the files `doc` links. `by_name`: `doc` is a placed `.ai` or EPS file's editing
|
||||
/// data, whose links are not rewritten, so its copy finds them by name beside it. `lookup`: the
|
||||
/// document whose links (with the same paths as `doc`'s) are looked for, and where from, when
|
||||
/// not `doc` from `source`.
|
||||
fn collect(
|
||||
@@ -311,12 +325,13 @@ impl<'a> Collector<'a> {
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
|
||||
}
|
||||
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
|
||||
// read from its editing data links are copied beside it.
|
||||
// A placed PDF, .ai or EPS file is copied as it is, as an image is; the files a .ai
|
||||
// file read from its editing data, or an EPS file read from the native document it
|
||||
// carries, links are copied beside it.
|
||||
let pages = placed.get(&file.path);
|
||||
let placed_file = pages.is_some();
|
||||
check_carried_scripts(&file.name, &bytes, found_path)?;
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if placed_file && let Some(mut art) = editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
|
||||
@@ -649,6 +649,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"transparency.setOpacityMask",
|
||||
"transparency.unlinkOpacityMask",
|
||||
"type.pathOptions",
|
||||
"webExport.optimizeToFileSize",
|
||||
"webExport.presets.save",
|
||||
"webExport.settings",
|
||||
];
|
||||
@@ -663,18 +664,28 @@ fn pdf_option_tree() -> Value {
|
||||
tree
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
|
||||
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
|
||||
/// is one value of the message, so a catalog can match the message and translate it.
|
||||
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
|
||||
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
|
||||
}
|
||||
|
||||
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
|
||||
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
match (schema.get(key), value) {
|
||||
(None, _) => {
|
||||
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
|
||||
let why = match nearest(key, &keys) {
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
let near = nearest(key, &keys);
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => {
|
||||
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
_ => {}
|
||||
@@ -691,14 +702,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
));
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
|
||||
});
|
||||
}
|
||||
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
|
||||
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
|
||||
@@ -797,12 +805,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
let formats = screen_formats();
|
||||
for (format, options) in settings {
|
||||
if !formats.contains(&format.as_str()) {
|
||||
let why = match nearest(format, &formats) {
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
let near = nearest(format, &formats);
|
||||
let key = format!("{within}settings.{}", shown_key(format));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")),
|
||||
None => {
|
||||
let (object, keys) = (format!("{within}settings"), formats.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
|
||||
|
||||
@@ -1874,20 +1874,85 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
cut.finish(d)?;
|
||||
// Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart.
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(id);
|
||||
sel.anchors.entry(id).or_default().insert(a);
|
||||
}
|
||||
select_cut_ends(sel, &picked);
|
||||
Ok(all)
|
||||
})?;
|
||||
Ok(super::draw2::ids_json(&ids))
|
||||
}
|
||||
|
||||
/// Replaces the selection with the anchors in `picked`: each id once, in the order it first
|
||||
/// appears, with every anchor listed for it. An empty `picked` clears the selection.
|
||||
fn select_cut_ends(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.set(picked.iter().map(|(id, _)| *id));
|
||||
for (id, a) in picked {
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `select_cut_ends` by clearing the selection and adding each id in turn, kept as the
|
||||
/// reference the one-call version must match.
|
||||
fn select_cut_ends_one_by_one(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) {
|
||||
sel.clear();
|
||||
for (id, a) in picked {
|
||||
sel.add(*id);
|
||||
sel.anchors.entry(*id).or_default().insert(*a);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set, the art made since the last deselect included.
|
||||
fn busy_selection() -> Selection {
|
||||
Selection {
|
||||
objects: vec![NodeId(90), NodeId(91)],
|
||||
anchors: [(NodeId(90), [(0, 3)].into())].into(),
|
||||
segments: [(NodeId(91), [(0, 1)].into())].into(),
|
||||
key: Some(NodeId(90)),
|
||||
target: Some(NodeId(91)),
|
||||
slices: vec![NodeId(92)],
|
||||
guides: vec![NodeId(93)],
|
||||
key_guide: Some(NodeId(93)),
|
||||
key_anchor: Some((NodeId(90), (0, 3))),
|
||||
symbol_part: Some(vectorcraft_doc::SymbolPart { instance: NodeId(94), path: vec![0, 2] }),
|
||||
on_path_member: Some(NodeId(95)),
|
||||
new_art: Arc::new([NodeId(90), NodeId(97)].into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cut ends of open paths, of an opened closed path, of a path of several subpaths (one id
|
||||
/// with several anchors, first seen before other ids), long lists and an empty one give the
|
||||
/// same selection, every field, as clearing it and adding each id in turn.
|
||||
#[test]
|
||||
fn selecting_cut_ends_matches_adding_them_one_by_one() {
|
||||
let n = NodeId;
|
||||
let mut cases: Vec<Vec<(NodeId, (usize, usize))>> = vec![
|
||||
vec![],
|
||||
vec![(n(1), (0, 0)), (n(2), (0, 0))],
|
||||
vec![(n(5), (0, 0))],
|
||||
vec![(n(7), (0, 0)), (n(3), (1, 0)), (n(8), (0, 0)), (n(3), (2, 0)), (n(7), (0, 0)), (n(3), (0, 0))],
|
||||
];
|
||||
let mut rng = Lcg(11);
|
||||
for len in [50, 2_000] {
|
||||
cases.push((0..len).map(|_| (n(rng.below(300) + 1), (rng.below(4) as usize, 0))).collect());
|
||||
}
|
||||
for picked in &cases {
|
||||
for start in [Selection::default(), busy_selection()] {
|
||||
let (mut ours, mut theirs) = (start.clone(), start.clone());
|
||||
select_cut_ends(&mut ours, picked);
|
||||
select_cut_ends_one_by_one(&mut theirs, picked);
|
||||
assert_eq!(ours, theirs, "{picked:?}");
|
||||
assert_eq!(ours.new_art, start.new_art);
|
||||
}
|
||||
}
|
||||
let mut sel = busy_selection();
|
||||
select_cut_ends(&mut sel, &cases[3]);
|
||||
assert_eq!(sel.objects, [n(7), n(3), n(8)]);
|
||||
assert_eq!(sel.anchors[&n(3)].iter().collect::<Vec<_>>(), [&(0, 0), &(1, 0), &(2, 0)]);
|
||||
assert_eq!((sel.anchors.len(), sel.key, sel.target, sel.symbol_part.is_some()), (3, None, None, false));
|
||||
}
|
||||
|
||||
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
|
||||
/// reference the one-pass version must match.
|
||||
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
|
||||
|
||||
@@ -548,6 +548,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.toggle",
|
||||
"select.update",
|
||||
"shape.arc",
|
||||
"shape.circleThroughPoints",
|
||||
"shape.ellipse",
|
||||
"shape.flare",
|
||||
"shape.line",
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
@@ -82,11 +82,38 @@ pub(crate) fn settings_over(cmd: &str, mut v: Value, p: &Value) -> Result<PrintS
|
||||
Some(over @ Value::Object(_)) => merge(&mut v, over),
|
||||
Some(_) => return Err(bad(cmd, "settings must be an object")),
|
||||
}
|
||||
link_scale(cmd, &mut v, p.get("settings").and_then(|s| s.get("scale")).filter(|s| s.is_object()))?;
|
||||
let set = PrintSettings::deserialize(&v).map_err(|e| bad(cmd, format!("print settings: {e}")))?;
|
||||
set.check().map_err(|e| pdf_error(cmd, e))?;
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// Keep the custom scale's width and height equal in the merged settings `v` while `scale.linked`
|
||||
/// is on, after `over` (the request's `scale`) was merged in: the one side the request gives sets
|
||||
/// the other, and otherwise the height takes the width (as turning the link on does). A request
|
||||
/// that gives a different width and height without a `linked` key turns the link off; with
|
||||
/// `linked: true`, or with `linked: null` over a linked scale, it is refused.
|
||||
fn link_scale(cmd: &str, v: &mut Value, over: Option<&Value>) -> Result<()> {
|
||||
let given = |k: &str| over.and_then(|o| o.get(k)).filter(|x| !x.is_null());
|
||||
let (width, height) = (given("width").cloned(), given("height").cloned());
|
||||
let apart = matches!((&width, &height), (Some(w), Some(h)) if w.as_f64() != h.as_f64());
|
||||
let Some(scale) = v.get_mut("scale").and_then(Value::as_object_mut) else { return Ok(()) };
|
||||
if apart && over.and_then(|o| o.get("linked")).is_none() {
|
||||
scale.insert("linked".into(), Value::Bool(false));
|
||||
}
|
||||
if scale.get("linked") != Some(&Value::Bool(true)) {
|
||||
return Ok(());
|
||||
}
|
||||
if apart {
|
||||
return Err(bad(cmd, "scale: give one percentage, or the same width and height, while scale.linked is on (linked: false scales them apart)"));
|
||||
}
|
||||
let (from, to) = if width.is_none() && height.is_some() { ("height", "width") } else { ("width", "height") };
|
||||
if let Some(value) = scale.get(from).cloned() {
|
||||
scale.insert(to.into(), value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn to_json(set: &PrintSettings) -> Result<Value> {
|
||||
serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
@@ -378,11 +378,12 @@ pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool)
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
/// that is its only visible raster effect and is its own (not a fill's or a stroke's): made of `n`
|
||||
/// without that effect and without its transparency, which stays on the object. When Transform
|
||||
/// effects after the Rasterize effect move its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
/// effects after the Rasterize effect move or copy its image ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// the image is made of the art before them once and placed by each of their maps, as the canvas
|
||||
/// draws it: with copies, a group of the placements with the lowest first. `None` otherwise, when
|
||||
/// those Transform effects flatten every placement, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let (whole, r, maps) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -395,33 +396,58 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
match maps.as_deref() {
|
||||
None => Some(image),
|
||||
Some([map]) => {
|
||||
image.transform(*map, false);
|
||||
Some(image)
|
||||
}
|
||||
Some(maps) => {
|
||||
// Each placement is an object of its own on the one image's pixels.
|
||||
let placed: Vec<Arc<Node>> = maps
|
||||
.iter()
|
||||
.map(|map| {
|
||||
let mut copy = d.reid(&image);
|
||||
copy.transform(*map, false);
|
||||
Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
Some(Node::group(d.alloc_id(), placed))
|
||||
}
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
/// that move or copy the image, without the Rasterize effect and without its transparency; that
|
||||
/// effect's options; and the maps those Transform effects place the image by, the lowest first,
|
||||
/// without those that flatten it. `None` when `n` has another raster effect, when the Rasterize
|
||||
/// effect is not its own, or when those Transform effects flatten every placement.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Vec<Affine>>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let (stage, maps) = match vectorcraft_render::rasterize_stage(d, n) {
|
||||
Some((stage, maps)) => {
|
||||
let maps: Vec<Affine> = maps.into_iter().filter(|m| places(*m)).collect();
|
||||
if maps.is_empty() {
|
||||
return None;
|
||||
}
|
||||
(Some(stage), Some(maps))
|
||||
}
|
||||
None => (None, None),
|
||||
};
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
Some((whole, r, maps))
|
||||
}
|
||||
|
||||
/// Does `map`, one of those a Rasterize image is placed by ([`vectorcraft_render::rasterize_stage`]),
|
||||
/// place it? Not when it flattens it to a line or a point: the canvas draws nothing there.
|
||||
fn places(map: Affine) -> bool {
|
||||
let det = map.determinant();
|
||||
det.is_finite() && det.abs() > 1e-12
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
@@ -658,27 +684,32 @@ fn walk_all(out: &mut Document, nodes: &[Arc<Node>], report: &mut FlattenReport)
|
||||
.then(|| nodes.iter().map(|n| walk(out, n, report).map(Arc::new).unwrap_or_else(|| n.clone())).collect())
|
||||
}
|
||||
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it
|
||||
/// ([`vectorcraft_render::rasterize_stage`]): the image is made of the art before those Transform
|
||||
/// effects and moved by them, as the canvas draws it, which baking the geometry effects first would
|
||||
/// lose. A map that flattens the image leaves an empty group, as the canvas draws nothing. Inside
|
||||
/// groups, layers and opacity masks, the members are looked at the same way. `None` when nothing in
|
||||
/// `n` changes; hidden objects and template layers stay as they are.
|
||||
/// `n` as an image when its Rasterize image moves with the Transform effects after it, or as a
|
||||
/// group of that image's placements when they copy it ([`vectorcraft_render::rasterize_stage`]):
|
||||
/// the image is made of the art before those Transform effects and placed by them, as the canvas
|
||||
/// draws it, which baking the geometry effects first would lose. Maps that flatten every placement
|
||||
/// leave an empty group, as the canvas draws nothing. Inside groups, layers and opacity masks, the
|
||||
/// members are looked at the same way. `None` when nothing in `n` changes; hidden objects and
|
||||
/// template layers stay as they are.
|
||||
fn staged(out: &mut Document, n: &Node, report: &mut FlattenReport) -> Option<Node> {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, map)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
if let Some((_, maps)) = vectorcraft_render::rasterize_stage(out, n) {
|
||||
let mut v = n.clone();
|
||||
strip_raster(&mut v, false);
|
||||
let det = map.determinant();
|
||||
if !(det.is_finite() && det.abs() > 1e-12) {
|
||||
if !maps.iter().any(|m| places(*m)) {
|
||||
v.appearance = Default::default();
|
||||
v.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return Some(v);
|
||||
}
|
||||
let image = raster_image(out, n, false, false)?;
|
||||
report.record(n, &image);
|
||||
// The placements share one image: its resolution is the first one's.
|
||||
let first = match &image.kind {
|
||||
NodeKind::Group { children, clip: false } => children.first().map_or(&image, |c| &**c),
|
||||
_ => &image,
|
||||
};
|
||||
report.record(n, first);
|
||||
let mut m = replace_with_image(v, image);
|
||||
staged_mask(out, &mut m, report);
|
||||
return Some(m);
|
||||
|
||||
@@ -66,11 +66,13 @@ impl FlattenReport {
|
||||
lowest
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default();
|
||||
format!(
|
||||
"raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap",
|
||||
r.id.0, self.requested_ppi, r.achieved_ppi
|
||||
)
|
||||
// The id and the name are one value of the message, so a catalog can match it.
|
||||
let object = match r.name {
|
||||
Some(name) => format!("{} ({name})", r.id.0),
|
||||
None => r.id.0.to_string(),
|
||||
};
|
||||
let (requested, achieved) = (self.requested_ppi, r.achieved_ppi);
|
||||
format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -127,4 +129,23 @@ mod tests {
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warning_names_the_object_by_its_id_and_its_name() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.raster_effects_ppi = 300.0;
|
||||
let mut named = Node::group(NodeId(7), vec![]);
|
||||
named.name = Some("Logo".into());
|
||||
let unnamed = Node::group(NodeId(8), vec![]);
|
||||
let mut report = FlattenReport::new(Which::All, &doc);
|
||||
report.record(&named, &image(72.0));
|
||||
report.record(&unnamed, &image(150.0));
|
||||
assert_eq!(
|
||||
report.warnings(),
|
||||
[
|
||||
"raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap",
|
||||
"raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -308,24 +308,30 @@ pub(crate) fn selectable(d: &Document, iso: Option<NodeId>) -> Vec<NodeId> {
|
||||
/// them, leaving out every hidden or locked object with what it holds. `f` returns whether to
|
||||
/// visit the objects inside the one it is given.
|
||||
pub(crate) fn walk_selectable(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
walk_selectable_in(d, iso, |n, _| f(n));
|
||||
}
|
||||
|
||||
/// [`walk_selectable`], handing `f` each object with the node that holds it in the tree: its
|
||||
/// layer, sublayer, group or other container, or `None` for a top-level layer.
|
||||
fn walk_selectable_in(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
fn inside(n: &Node, parent: Option<&Node>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if n.visible && !n.locked && f(n, parent) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
inside(c, Some(n), f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
fn find(n: &Node, parent: Option<&Node>, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node, Option<&Node>) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
return inside(n, parent, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
find(c, Some(n), tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
find(l, None, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1098,7 +1104,9 @@ fn select_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "give `fill`, `stroke` or both"));
|
||||
}
|
||||
let reads_as = |paint: Paint, hex: Option<&str>| hex.is_none_or(|h| paint.color().is_some_and(|c| c.to_hex() == h));
|
||||
select_where(s, C, p, |d, n| paint_reported(d, n) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref()))
|
||||
select_where(s, C, p, |_, n, parent| {
|
||||
paint_reported(n, parent) && reads_as(fill_of(n), fill.as_deref()) && reads_as(stroke_of(n).0, stroke.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// The longest note, in bytes, that Select by Note searches for.
|
||||
@@ -1219,11 +1227,11 @@ fn fold_case(c: char) -> impl Iterator<Item = char> {
|
||||
c.to_lowercase().map(|l| if l == 'ς' { 'σ' } else { l })
|
||||
}
|
||||
|
||||
/// Does `document.inspect` report a fill and stroke for `n`? A compound path's are its own, though
|
||||
/// it holds its members, and its members report none.
|
||||
fn paint_reported(d: &Document, n: &Node) -> bool {
|
||||
/// Does `document.inspect` report a fill and stroke for `n`, held by `parent`? A compound path's
|
||||
/// are its own, though it holds its members, and its members report none.
|
||||
fn paint_reported(n: &Node, parent: Option<&Node>) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
compound(n) || (!n.is_container() && !parent.is_some_and(compound))
|
||||
}
|
||||
|
||||
/// The object Select > Same compares the others with, and whether isolation mode is inside a
|
||||
@@ -1260,30 +1268,30 @@ fn same_fill(s: &mut Session, cmd: &str, eq: impl Fn(&Node, &Node) -> bool) -> R
|
||||
fn same_in(s: &mut Session, cmd: &str, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let (refn, members) = same_reference(st, cmd)?;
|
||||
let group = live_paint_group(&st.doc, refn.id);
|
||||
let group = live_paint_group(st.doc.parent_of(refn.id).and_then(|p| st.doc.node(p)));
|
||||
let refn = refn.clone();
|
||||
select_where(s, cmd, &json!({}), |d, n| {
|
||||
(!live_paint || live_paint_group(d, n.id) == group) && (if members { !n.is_container() } else { paint_reported(d, n) }) && eq(n, &refn)
|
||||
})
|
||||
select_where(s, cmd, &json!({}), |_, n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, &refn))
|
||||
}
|
||||
|
||||
/// The Live Paint group `id` is a face or edge of.
|
||||
fn live_paint_group(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
/// Whether Select > Same compares `n`, held by `parent`, with its reference: with `live_paint`, only
|
||||
/// when `n` is a face or edge of the Live Paint group `group` (or of none, for `None`); in
|
||||
/// isolation mode inside a compound path (`members`), any object that is not a container;
|
||||
/// otherwise one that [`paint_reported`] accepts.
|
||||
fn same_candidate(n: &Node, parent: Option<&Node>, live_paint: bool, group: Option<NodeId>, members: bool) -> bool {
|
||||
(!live_paint || live_paint_group(parent) == group) && (if members { !n.is_container() } else { paint_reported(n, parent) })
|
||||
}
|
||||
|
||||
/// The Live Paint group an object held by `parent` is a face or edge of.
|
||||
fn live_paint_group(parent: Option<&Node>) -> Option<NodeId> {
|
||||
parent.filter(|p| is_live_paint(p)).map(|p| p.id)
|
||||
}
|
||||
|
||||
/// Select the objects [`walk_selectable`] visits that `f` accepts (not looking inside accepted
|
||||
/// ones); Select > Reselect repeats `cmd` with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node) -> bool) -> Result<Value> {
|
||||
/// ones); `f` is given each object with the node that holds it. Select > Reselect repeats `cmd`
|
||||
/// with `p`.
|
||||
pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Document, &Node, Option<&Node>) -> bool) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut ids = vec![];
|
||||
walk_selectable(&st.doc, st.isolation, |n| {
|
||||
if f(&st.doc, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
let ids = matching(&st.doc, st.isolation, |n, parent| f(&st.doc, n, parent));
|
||||
let from = st.selection.objects.clone();
|
||||
s.select(|_, sel| sel.set(ids.iter().copied()))?;
|
||||
let st = s.doc_mut()?;
|
||||
@@ -1292,12 +1300,26 @@ pub(crate) fn select_where(s: &mut Session, cmd: &str, p: &Value, f: impl Fn(&Do
|
||||
Ok(json!({ "count": st.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// The objects [`walk_selectable`] visits that `f` accepts, in paint order, not looking inside
|
||||
/// accepted ones. `f` is given each object with the node that holds it.
|
||||
fn matching(d: &Document, iso: Option<NodeId>, f: impl Fn(&Node, Option<&Node>) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_selectable_in(d, iso, |n, parent| {
|
||||
if f(n, parent) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
fn same_graphic_style(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let cmd = "select.same.graphicStyle";
|
||||
let st = s.doc()?;
|
||||
let (refn, _) = same_reference(st, cmd)?;
|
||||
let id = super::style::linked_style(&st.doc, refn).map(|g| g.id).ok_or_else(|| bad(cmd, "the selection has no graphic style"))?;
|
||||
select_where(s, cmd, &json!({}), |d, n| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
select_where(s, cmd, &json!({}), |d, n, _| n.extras().graphic_style == Some(id) && super::style::linked_style(d, n).is_some())
|
||||
}
|
||||
|
||||
/// An appearance attribute Select > Same > Appearance Attribute matches.
|
||||
@@ -1321,7 +1343,7 @@ fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Attribute::Item(ap.items.iter().rev().find(|i| i.is_fill()).cloned().ok_or_else(|| bad(cmd, "the object has no fill, stroke or effect"))?)
|
||||
}
|
||||
};
|
||||
select_where(s, cmd, p, |_, n| match &attr {
|
||||
select_where(s, cmd, p, |_, n, _| match &attr {
|
||||
Attribute::Item(it) => n.appearance.items.contains(it),
|
||||
Attribute::Effect(e) => n.appearance.effects.iter().any(|x| x.id == e.id && x.params == e.params),
|
||||
})
|
||||
@@ -1381,5 +1403,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod same_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Select > Same and Select by Color through [`walk_selectable_in`], which hands each object the
|
||||
//! node that holds it, against copies of the walk and the tests that looked each object's parent up
|
||||
//! by its id.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::{fill_of, is_live_paint, matching, same_candidate, same_paint, same_reference, selectable, stroke_of, walk_selectable_in};
|
||||
use crate::Session;
|
||||
|
||||
/// `walk_selectable` as it was before it handed each object its parent.
|
||||
fn walk_by_id(d: &Document, iso: Option<NodeId>, mut f: impl FnMut(&Node) -> bool) {
|
||||
fn inside(n: &Node, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if n.visible && !n.locked && f(n) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
inside(c, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn find(n: &Node, tops: &BTreeSet<NodeId>, f: &mut impl FnMut(&Node) -> bool) {
|
||||
if tops.contains(&n.id) {
|
||||
return inside(n, f);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
find(c, tops, f);
|
||||
}
|
||||
}
|
||||
let tops: BTreeSet<NodeId> = selectable(d, iso).into_iter().collect();
|
||||
for l in &d.layers {
|
||||
find(l, &tops, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint_reported` as it was, looking up `n`'s parent by its id.
|
||||
fn paint_reported_by_id(d: &Document, n: &Node) -> bool {
|
||||
let compound = |n: &Node| matches!(n.kind, NodeKind::Compound { .. });
|
||||
compound(n) || (!n.is_container() && !d.parent_of(n.id).and_then(|p| d.node(p)).is_some_and(compound))
|
||||
}
|
||||
|
||||
/// `live_paint_group` as it was, looking up the parent of `id`.
|
||||
fn live_paint_group_by_id(d: &Document, id: NodeId) -> Option<NodeId> {
|
||||
d.parent_of(id).filter(|p| d.node(*p).is_some_and(is_live_paint))
|
||||
}
|
||||
|
||||
/// The objects `select_where`'s loop took before the walk handed each object its parent.
|
||||
fn matching_by_id(d: &Document, iso: Option<NodeId>, f: impl Fn(&Document, &Node) -> bool) -> Vec<NodeId> {
|
||||
let mut ids = vec![];
|
||||
walk_by_id(d, iso, |n| {
|
||||
if f(d, n) {
|
||||
ids.push(n.id);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
ids
|
||||
}
|
||||
|
||||
/// The objects `same_in` took before the walk handed each object its parent.
|
||||
fn same_by_id(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = live_paint_group_by_id(d, refn.id);
|
||||
matching_by_id(d, iso, |d, n| {
|
||||
(!live_paint || live_paint_group_by_id(d, n.id) == group)
|
||||
&& (if members { !n.is_container() } else { paint_reported_by_id(d, n) })
|
||||
&& eq(n, refn)
|
||||
})
|
||||
}
|
||||
|
||||
/// The objects `same_in` takes now.
|
||||
fn same_now(d: &Document, iso: Option<NodeId>, refn: &Node, members: bool, live_paint: bool, eq: impl Fn(&Node, &Node) -> bool) -> Vec<NodeId> {
|
||||
let group = super::live_paint_group(d.parent_of(refn.id).and_then(|p| d.node(p)));
|
||||
matching(d, iso, |n, parent| same_candidate(n, parent, live_paint, group, members) && eq(n, refn))
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("`{cmd}` {p} failed: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
fn sel(s: &mut Session, ids: &[NodeId]) {
|
||||
run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}));
|
||||
}
|
||||
|
||||
/// A 10 × 10 rectangle at (`x`, `y`) filled with `hex`.
|
||||
fn rect(s: &mut Session, x: f64, y: f64, hex: &str) -> NodeId {
|
||||
let r = id(&run(s, "shape.rectangle", json!({"x": x, "y": y, "width": 10.0, "height": 10.0})));
|
||||
run(s, "paint.setFill", json!({"ids": [r.0], "color": hex}));
|
||||
r
|
||||
}
|
||||
|
||||
/// A compound path of three rectangles at `y`, filled with `hex` → the compound path and its
|
||||
/// member paths.
|
||||
fn compound(s: &mut Session, y: f64, hex: &str) -> (NodeId, Vec<NodeId>) {
|
||||
let members: Vec<NodeId> = [0.0, 20.0, 40.0].map(|x| rect(s, 300.0 + x, y, hex)).into();
|
||||
sel(s, &members);
|
||||
let c = id(&run(s, "object.compoundPath.make", json!({})));
|
||||
run(s, "paint.setFill", json!({"ids": [c.0], "color": hex}));
|
||||
(c, members)
|
||||
}
|
||||
|
||||
/// A Live Paint group of two overlapping squares at `y`, its left face red, its middle face blue and
|
||||
/// its right face red → the group and its faces.
|
||||
fn live_paint(s: &mut Session, y: f64) -> (NodeId, Vec<NodeId>) {
|
||||
let a = id(&run(s, "shape.rectangle", json!({"x": 0.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
let b = id(&run(s, "shape.rectangle", json!({"x": 50.0, "y": y, "width": 100.0, "height": 100.0})));
|
||||
sel(s, &[a, b]);
|
||||
let g = id(&run(s, "livePaint.make", json!({})));
|
||||
let faces = [(25.0, "#ff0000"), (75.0, "#0000ff"), (125.0, "#ff0000")]
|
||||
.map(|(x, hex)| NodeId(run(s, "livePaint.fill", json!({"group": g.0, "point": [x, y + 50.0], "color": hex}))["face"].as_u64().unwrap()))
|
||||
.into();
|
||||
(g, faces)
|
||||
}
|
||||
|
||||
/// The objects of [`rich`] that tests pick from.
|
||||
struct Rich {
|
||||
plain: Vec<NodeId>,
|
||||
compound: NodeId,
|
||||
members: Vec<NodeId>,
|
||||
group: NodeId,
|
||||
live_paint: NodeId,
|
||||
faces: Vec<NodeId>,
|
||||
sublayer: NodeId,
|
||||
}
|
||||
|
||||
/// A document with red and blue rectangles, a compound path, a group with a hidden and a locked
|
||||
/// rectangle, a locked group, a Live Paint group, a sublayer holding a rectangle and a second
|
||||
/// compound path, and a hidden and a locked layer with a red rectangle each.
|
||||
fn rich() -> (Session, Rich) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let mut plain = vec![rect(&mut s, 0.0, 0.0, "#ff0000"), rect(&mut s, 20.0, 0.0, "#ff0000"), rect(&mut s, 40.0, 0.0, "#0000ff")];
|
||||
let (compound_id, members) = compound(&mut s, 0.0, "#ff0000");
|
||||
let [in_group, hidden, locked] = [0.0, 20.0, 40.0].map(|x| rect(&mut s, x, 200.0, "#ff0000"));
|
||||
let blue = rect(&mut s, 60.0, 200.0, "#0000ff");
|
||||
sel(&mut s, &[in_group, hidden, locked, blue]);
|
||||
let group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": hidden.0, "visible": false}));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked.0, "locked": true}));
|
||||
let in_locked = rect(&mut s, 100.0, 200.0, "#ff0000");
|
||||
sel(&mut s, &[in_locked]);
|
||||
let locked_group = id(&run(&mut s, "object.group", json!({})));
|
||||
run(&mut s, "layer.setProps", json!({"id": locked_group.0, "locked": true}));
|
||||
let (live_paint_id, faces) = live_paint(&mut s, 300.0);
|
||||
plain.extend([in_group, blue]);
|
||||
let sublayer = id(&run(&mut s, "layer.newSublayer", json!({"parent": layer.0})));
|
||||
plain.push(rect(&mut s, 0.0, 500.0, "#ff0000"));
|
||||
compound(&mut s, 500.0, "#0000ff");
|
||||
for prop in ["visible", "locked"] {
|
||||
let l = id(&run(&mut s, "layer.new", json!({"top": true})));
|
||||
rect(&mut s, 200.0, 500.0, "#ff0000");
|
||||
run(&mut s, "layer.setProps", json!({"id": l.0, prop: prop == "locked"}));
|
||||
}
|
||||
let rich = Rich { plain, compound: compound_id, members, group, live_paint: live_paint_id, faces, sublayer };
|
||||
(s, rich)
|
||||
}
|
||||
|
||||
/// The isolation scopes to try: none, the group, the compound path, and the Live Paint group.
|
||||
fn scopes(r: &Rich) -> [Option<NodeId>; 4] {
|
||||
[None, Some(r.group), Some(r.compound), Some(r.live_paint)]
|
||||
}
|
||||
|
||||
/// Isolate `iso`, leaving isolation mode first.
|
||||
fn isolate(s: &mut Session, iso: Option<NodeId>) {
|
||||
if s.doc().unwrap().isolation.is_some() {
|
||||
run(s, "object.exitIsolation", json!({}));
|
||||
}
|
||||
if let Some(i) = iso {
|
||||
run(s, "object.isolate", json!({"id": i.0}));
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// The walk visits the objects it visited before, in the same order and with the same objects left
|
||||
/// out, and hands each the node that `Document::parent_of` names for it.
|
||||
#[test]
|
||||
fn the_walk_hands_each_object_the_node_that_holds_it() {
|
||||
let (mut s, r) = rich();
|
||||
// Look inside everything, and inside every other object only.
|
||||
let deeper: [fn(&Node) -> bool; 2] = [|_| true, |n| n.id.0 % 2 == 0];
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
let st = s.doc().unwrap();
|
||||
let d = &st.doc;
|
||||
for f in deeper {
|
||||
let mut before = vec![];
|
||||
walk_by_id(d, st.isolation, |n| {
|
||||
before.push((n.id, d.parent_of(n.id)));
|
||||
f(n)
|
||||
});
|
||||
let mut now = vec![];
|
||||
walk_selectable_in(d, st.isolation, |n, parent| {
|
||||
now.push((n.id, parent.map(|p| p.id)));
|
||||
f(n)
|
||||
});
|
||||
assert!(!now.is_empty(), "isolating {iso:?}");
|
||||
assert_eq!(now, before, "isolating {iso:?}");
|
||||
}
|
||||
}
|
||||
// Every face, member path and the sublayer's art were visited somewhere above.
|
||||
let st = s.doc().unwrap();
|
||||
assert!(r.faces.iter().chain(&r.members).all(|f| st.doc.node(*f).is_some()));
|
||||
assert!(st.doc.node(r.sublayer).is_some_and(|n| n.is_layer()));
|
||||
}
|
||||
|
||||
/// Select > Same and Select by Color select the objects they selected before, in the same order,
|
||||
/// with the same reply and the same Select > Reselect state, from every kind of reference object
|
||||
/// and in every isolation scope.
|
||||
#[test]
|
||||
fn select_same_takes_the_objects_it_took_when_it_looked_up_parents() {
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
let commands: [(&str, bool, Eq); 6] = [
|
||||
("select.same.fillColor", true, fill),
|
||||
("select.same.fillAndStroke", true, |a, b| {
|
||||
same_paint(&fill_of(a), &fill_of(b), false) && same_paint(&stroke_of(a).0, &stroke_of(b).0, false)
|
||||
}),
|
||||
("select.same.strokeColor", false, stroke),
|
||||
("select.same.opacity", false, |a, b| (a.opacity - b.opacity).abs() < 1e-6),
|
||||
("select.same.blendingMode", false, |a, b| a.blend == b.blend),
|
||||
("select.same.shapeType", false, |a, b| a.kind_label() == b.kind_label()),
|
||||
];
|
||||
let (mut s, r) = rich();
|
||||
assert!(!s.prefs.select_same_tint_percent);
|
||||
let froms: Vec<NodeId> = r.plain.iter().chain(&r.members).chain(&r.faces).copied().chain([r.compound]).collect();
|
||||
let mut checked = 0;
|
||||
for iso in scopes(&r) {
|
||||
isolate(&mut s, iso);
|
||||
for from in &froms {
|
||||
for (cmd, live_paint, eq) in commands {
|
||||
// An object outside the isolated one may not be selectable; the selection then
|
||||
// stays, and both sides compare with what it holds.
|
||||
let _ = s.execute("select.set", &json!({"ids": [from.0]}));
|
||||
let st = s.doc().unwrap();
|
||||
let Ok((refn, members)) = same_reference(st, cmd) else {
|
||||
assert!(s.execute(cmd, &json!({})).is_err(), "{cmd} from {from:?} isolating {iso:?}");
|
||||
continue;
|
||||
};
|
||||
let refn = refn.clone();
|
||||
let expected = same_by_id(&st.doc, st.isolation, &refn, members, live_paint, eq);
|
||||
assert_eq!(same_now(&st.doc, st.isolation, &refn, members, live_paint, eq), expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
let before = st.selection.objects.clone();
|
||||
let reply = run(&mut s, cmd, json!({}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "{cmd} from {from:?} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd, Some((cmd.to_string(), json!({}), before)));
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
for hex in ["#ff0000", "#0000ff"] {
|
||||
let st = s.doc().unwrap();
|
||||
let reads_as = |n: &Node| fill_of(n).color().is_some_and(|c| c.to_hex() == hex);
|
||||
let expected = matching_by_id(&st.doc, st.isolation, |d, n| paint_reported_by_id(d, n) && reads_as(n));
|
||||
let p = json!({"fill": hex});
|
||||
let reply = run(&mut s, "select.color", p.clone());
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.selection.objects, expected, "select.color {hex} isolating {iso:?}");
|
||||
assert_eq!(reply, json!({"count": expected.len()}));
|
||||
assert_eq!(st.last_selection_cmd.as_ref().map(|(c, p, _)| (c.as_str(), p)), Some(("select.color", &p)));
|
||||
}
|
||||
}
|
||||
// Most of the references can be selected in some scope.
|
||||
assert!(checked > froms.len() * commands.len(), "{checked} checks");
|
||||
}
|
||||
|
||||
/// In a damaged document that holds an id twice, the parent that decides whether an object is a
|
||||
/// member of a compound path or a face of a Live Paint group is the one that holds the object the
|
||||
/// walk is at, not the one that holds the id's first place in the tree.
|
||||
#[test]
|
||||
fn select_same_reads_the_parent_of_the_object_it_is_at() {
|
||||
for in_live_paint in [false, true] {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let (_, inner) = if in_live_paint { live_paint(&mut s, 300.0) } else { compound(&mut s, 0.0, "#0000ff") };
|
||||
let from = rect(&mut s, 0.0, 0.0, "#ff0000");
|
||||
// A red rectangle above the others that has the id of a face or member path.
|
||||
let mut copy = s.doc().unwrap().doc.node(from).unwrap().clone();
|
||||
copy.id = inner[0];
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).insert(Some(layer), usize::MAX, copy).unwrap();
|
||||
let mut commands = vec![("select.same.fillColor", json!({})), ("select.same.fillAndStroke", json!({}))];
|
||||
// Select by Color takes the red faces of a Live Paint group too, so it is tried on the
|
||||
// compound path only.
|
||||
if !in_live_paint {
|
||||
commands.push(("select.color", json!({"fill": "#ff0000"})));
|
||||
}
|
||||
for (cmd, p) in commands {
|
||||
sel(&mut s, &[from]);
|
||||
let reply = run(&mut s, cmd, p);
|
||||
assert_eq!(reply["count"], 2, "{cmd}, Live Paint: {in_live_paint}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document of `n` objects on one layer: red and blue rectangles, one in 25 a compound path of
|
||||
/// three, and two Live Paint groups that hold one in 25 each as faces → the session, with the first
|
||||
/// rectangle selected.
|
||||
fn big(n: usize) -> Session {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 600}));
|
||||
let (c, _) = compound(&mut s, 0.0, "#ff0000");
|
||||
let (g, _) = live_paint(&mut s, 300.0);
|
||||
let [red, blue] = ["#ff0000", "#0000ff"].map(|hex| rect(&mut s, 0.0, 0.0, hex));
|
||||
let mut d = Document::clone(&s.doc().unwrap().doc);
|
||||
let layer = d.layers[0].id;
|
||||
let template = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let (c, g, red, blue) = (template(c), template(g), template(red), template(blue));
|
||||
fn renumber(n: &Node, d: &mut Document) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = d.alloc_id();
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
*c = Arc::new(renumber(c, d));
|
||||
}
|
||||
n
|
||||
}
|
||||
d.children_mut(Some(layer)).unwrap().clear();
|
||||
let faces: Vec<Arc<Node>> = g.children().into_iter().flatten().cloned().collect();
|
||||
for _ in 0..2 {
|
||||
let mut g = renumber(&g, &mut d);
|
||||
if let Some(ch) = g.children_mut() {
|
||||
ch.clear();
|
||||
for i in 0..n / 25 {
|
||||
ch.push(Arc::new(renumber(&faces[i % faces.len()], &mut d)));
|
||||
}
|
||||
}
|
||||
d.insert(Some(layer), usize::MAX, g).unwrap();
|
||||
}
|
||||
for i in 0..n - 2 * (n / 25) {
|
||||
let node = match i % 25 {
|
||||
0 => renumber(&c, &mut d),
|
||||
k if k % 2 == 0 => renumber(&red, &mut d),
|
||||
_ => renumber(&blue, &mut d),
|
||||
};
|
||||
d.insert(Some(layer), usize::MAX, node).unwrap();
|
||||
}
|
||||
let first = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Path { .. })).unwrap().id;
|
||||
s.add_document(d, None);
|
||||
sel(&mut s, &[first]);
|
||||
s
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ms(d: Duration) -> f64 {
|
||||
d.as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Timings of Select > Same's search, by id lookups and with the walk's parents, on 5,000, 50,000
|
||||
/// and 200,000 objects, run in turn on the same document, 7 runs each. Ignored by default; it
|
||||
/// prints the median, fastest and slowest run and sets no bound on them:
|
||||
/// `cargo test --release -p vectorcraft-engine --lib select_same_perf -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "a benchmark: run with --ignored --nocapture"]
|
||||
fn select_same_perf() {
|
||||
const RUNS: usize = 7;
|
||||
type Eq = fn(&Node, &Node) -> bool;
|
||||
let fill: Eq = |a, b| same_paint(&fill_of(a), &fill_of(b), false);
|
||||
let stroke: Eq = |a, b| same_paint(&stroke_of(a).0, &stroke_of(b).0, false);
|
||||
eprintln!("select_same_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
eprintln!(
|
||||
"select_same_perf: {:>7} {:<12} {:>8} {:>26} {:>26}",
|
||||
"objects", "command", "selected", "by id ms (min-max)", "walk parents ms (min-max)"
|
||||
);
|
||||
for n in [5_000, 50_000, 200_000] {
|
||||
let s = big(n);
|
||||
let st = s.doc().unwrap();
|
||||
let (d, iso) = (&st.doc, st.isolation);
|
||||
let objects = {
|
||||
let mut k = 0;
|
||||
walk_selectable_in(d, iso, |_, _| {
|
||||
k += 1;
|
||||
true
|
||||
});
|
||||
k
|
||||
};
|
||||
for (cmd, live_paint, eq) in [("fillColor", true, fill), ("strokeColor", false, stroke)] {
|
||||
let (refn, members) = same_reference(st, cmd).unwrap();
|
||||
let (mut old, mut new) = (Vec::new(), Vec::new());
|
||||
let (mut a, mut b) = (vec![], vec![]);
|
||||
for run in 0..RUNS {
|
||||
// The two take turns going first.
|
||||
if run % 2 == 0 {
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
} else {
|
||||
new.push(time(|| b = std::hint::black_box(same_now(d, iso, refn, members, live_paint, eq))));
|
||||
old.push(time(|| a = std::hint::black_box(same_by_id(d, iso, refn, members, live_paint, eq))));
|
||||
}
|
||||
assert_eq!(a, b, "{n} objects, {cmd}");
|
||||
}
|
||||
old.sort();
|
||||
new.sort();
|
||||
eprintln!(
|
||||
"select_same_perf: {objects:>7} {cmd:<12} {:>8} {:>10.3} ({:>6.3}-{:>7.3}) {:>10.3} ({:>6.3}-{:>7.3})",
|
||||
b.len(),
|
||||
ms(old[RUNS / 2]),
|
||||
ms(old[0]),
|
||||
ms(old[RUNS - 1]),
|
||||
ms(new[RUNS / 2]),
|
||||
ms(new[0]),
|
||||
ms(new[RUNS - 1]),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
has_doc,
|
||||
swatch_new_group
|
||||
),
|
||||
@@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) };
|
||||
let cs: Vec<Paint> = cs
|
||||
.iter()
|
||||
.map(|c| color_value(c).map(|c| Paint::solid(stored(c))))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| bad(C, "bad colour in `colors`"))?;
|
||||
.map(|c| match swatch_entry(s, c, C)? {
|
||||
Some(paint) => Ok(paint),
|
||||
None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")),
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if cs.is_empty() {
|
||||
return Err(bad(C, "`colors` is empty"));
|
||||
}
|
||||
@@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch,
|
||||
/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot
|
||||
/// color stays linked to it). `None` for an entry without `swatch`.
|
||||
fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> {
|
||||
let Some(name) = v.get("swatch") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?;
|
||||
let tint = super::paint::tint_param(v, cmd)?;
|
||||
super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
@@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut names = str_list(p, "swatches");
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?;
|
||||
let colors: Vec<Color> = p
|
||||
// A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other
|
||||
// entry becomes a process color swatch.
|
||||
let colors: Vec<Paint> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|v| match swatch_entry(s, v, C)? {
|
||||
Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint),
|
||||
Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let from_art = bool_or(p, "fromArtwork", false);
|
||||
@@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tints = bool_or(p, "includeTints", false);
|
||||
let requested = name_param(p, "name");
|
||||
let (name, members, linked) = s.edit("New Color Group", |d, sel| {
|
||||
// New swatches: (colour, global).
|
||||
let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect();
|
||||
// New swatches: (paint, global).
|
||||
let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect();
|
||||
if from_art {
|
||||
if sel.objects.is_empty() {
|
||||
return Err(bad(C, "select artwork to make a group of its colours"));
|
||||
}
|
||||
let mut art = vec![];
|
||||
artwork_colors(d, &sel.objects, tints, &mut names, &mut art);
|
||||
new.extend(art.into_iter().map(|c| (c, to_global)));
|
||||
new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global)));
|
||||
}
|
||||
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
|
||||
// Colour groups hold solid colours only.
|
||||
@@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
|
||||
for (c, global) in new {
|
||||
let nm = free.take(&color_name(c));
|
||||
if global {
|
||||
for (paint, global) in new {
|
||||
// A tint swatch is named "Name 40%", a colour after its values.
|
||||
let nm = free.take_new(&paint);
|
||||
if global && let Some(c) = paint.color() {
|
||||
links.push((c, nm.clone()));
|
||||
}
|
||||
group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false });
|
||||
group.swatches.push(Swatch { name: nm, paint, global, spot: false });
|
||||
}
|
||||
let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect();
|
||||
d.swatch_groups.push(group);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! Magic Wand panel's (session state, kept across tool switches); the tool runs
|
||||
//! `select.magicWand` on click.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -188,13 +190,14 @@ impl WandSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable.
|
||||
/// Paintable leaves (paths, compounds, text, images) that are visible and editable, in the order
|
||||
/// of the document walk.
|
||||
fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
let mut compounds: HashSet<NodeId> = HashSet::new();
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
compounds.insert(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
@@ -210,6 +213,18 @@ fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Shift-click: the selected objects in their order, then each hit that isn't selected yet.
|
||||
fn added(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let seen: HashSet<NodeId> = selected.iter().copied().collect();
|
||||
selected.iter().copied().chain(hits.into_iter().filter(|h| !seen.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// Alt-click: the selected objects that aren't hits, in their order.
|
||||
fn subtracted(selected: &[NodeId], hits: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let hits: HashSet<NodeId> = hits.into_iter().collect();
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?;
|
||||
let st = s.doc()?;
|
||||
@@ -224,8 +239,8 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter(|i| st.doc.node(*i).is_some_and(|n| w.matches(&reference, n, mode)))
|
||||
.collect();
|
||||
let ids: Vec<NodeId> = match str_param(p, "mode").unwrap_or("set") {
|
||||
"add" => st.selection.objects.iter().copied().chain(hits.iter().copied().filter(|h| !st.selection.objects.contains(h))).collect(),
|
||||
"subtract" => st.selection.objects.iter().copied().filter(|i| !hits.contains(i)).collect(),
|
||||
"add" => added(&st.selection.objects, hits),
|
||||
"subtract" => subtracted(&st.selection.objects, hits),
|
||||
"set" => hits,
|
||||
other => return Err(bad("select.magicWand", format!("unknown mode `{other}` (set, add, subtract)"))),
|
||||
};
|
||||
@@ -423,6 +438,252 @@ mod tests {
|
||||
assert_eq!((o["fillTolerance"].as_f64(), o["strokeTolerance"].as_f64()), (Some(32.0), Some(32.0)));
|
||||
}
|
||||
|
||||
/// [`paintable`] with the compound paths kept in a list and searched for each object's parent.
|
||||
fn paintable_by_search(doc: &Document) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
let mut compounds: Vec<NodeId> = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Compound { .. }) {
|
||||
compounds.push(n.id);
|
||||
out.push(n.id);
|
||||
} else if !n.is_container() && !n.is_ruler_guide() {
|
||||
out.push(n.id);
|
||||
}
|
||||
});
|
||||
let editable = doc.editable();
|
||||
out.retain(|id| {
|
||||
!doc.parent_of(*id).is_some_and(|p| compounds.contains(&p))
|
||||
&& editable(*id)
|
||||
&& doc.is_visible(*id)
|
||||
&& doc.node(*id).is_some_and(|n| n.visible)
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`added`] with the selection searched for each hit.
|
||||
fn added_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().chain(hits.iter().copied().filter(|h| !selected.contains(h))).collect()
|
||||
}
|
||||
|
||||
/// [`subtracted`] with the hits searched for each selected object.
|
||||
fn subtracted_by_search(selected: &[NodeId], hits: &[NodeId]) -> Vec<NodeId> {
|
||||
selected.iter().copied().filter(|i| !hits.contains(i)).collect()
|
||||
}
|
||||
|
||||
/// A red fill for an even `k` and a blue one for an odd `k`, with a 1 pt black stroke.
|
||||
fn bench_paint(k: usize) -> vectorcraft_doc::Appearance {
|
||||
use vectorcraft_color::Color;
|
||||
let fill = if k.is_multiple_of(2) { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) };
|
||||
vectorcraft_doc::Appearance::basic(Paint::solid(fill), Paint::solid(Color::BLACK), 1.0)
|
||||
}
|
||||
|
||||
/// Path `k`: a 10 × 10 rectangle painted as [`bench_paint`]. Every 97th path is locked and
|
||||
/// every 89th hidden.
|
||||
fn bench_path(d: &mut Document, k: usize) -> Node {
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), bench_paint(k));
|
||||
n.locked = k % 97 == 5;
|
||||
n.visible = k % 89 != 7;
|
||||
n
|
||||
}
|
||||
|
||||
/// A session whose document holds `blocks` × 200 paths on one layer. Each block has a group of
|
||||
/// 10 paths, 25 compound paths of 2 paths each and 140 loose paths, with the group and the
|
||||
/// compound paths among the loose paths. The compound paths alternate red and blue fills, and
|
||||
/// a few are locked or hidden.
|
||||
fn wand_session(blocks: usize) -> Session {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_geom::FillRule;
|
||||
let mut d = Document::new(4000.0, 4000.0);
|
||||
let mut k = 0;
|
||||
let mut next = |d: &mut Document| {
|
||||
k += 1;
|
||||
bench_path(d, k - 1)
|
||||
};
|
||||
let mut art = vec![];
|
||||
for slot in 0..blocks * 166 {
|
||||
let node = match slot % 166 {
|
||||
0 => {
|
||||
let members = (0..10).map(|_| Arc::new(next(&mut d))).collect();
|
||||
Node::group(d.alloc_id(), members)
|
||||
}
|
||||
c @ 1..=25 => {
|
||||
let members = (0..2).map(|_| Arc::new(next(&mut d))).collect();
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
n.appearance = bench_paint(c).into();
|
||||
n.locked = slot % 1001 == 3;
|
||||
n.visible = slot % 1003 != 5;
|
||||
n
|
||||
}
|
||||
_ => next(&mut d),
|
||||
};
|
||||
art.push(Arc::new(node));
|
||||
}
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
*ch = art;
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
s
|
||||
}
|
||||
|
||||
/// The objects the wand picks when `reference` is clicked, found as before membership sets.
|
||||
fn hits_by_search(s: &Session, reference: NodeId) -> Vec<NodeId> {
|
||||
let st = s.doc().unwrap();
|
||||
let r = st.doc.node(reference).unwrap();
|
||||
let w = s.menu.wand.clone();
|
||||
paintable_by_search(&st.doc).into_iter().filter(|i| w.matches(r, st.doc.node(*i).unwrap(), st.doc.color_mode)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membership_sets_give_the_same_objects_in_the_same_order_as_searches() {
|
||||
// 20,000 paths: 5,000 in 2,500 compound paths and 1,000 in 100 groups.
|
||||
let mut s = wand_session(100);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let all = paintable(doc);
|
||||
assert!(all == paintable_by_search(doc), "paintable objects differ");
|
||||
// Compound paths stay pickable unless locked or hidden, and their members never are.
|
||||
let pickable: HashSet<NodeId> = all.iter().copied().collect();
|
||||
let (mut compounds, mut skipped) = (0, 0);
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
compounds += 1;
|
||||
skipped += usize::from(n.locked || !n.visible);
|
||||
assert_eq!(pickable.contains(&n.id), n.visible && !n.locked, "compound path {}", n.id.0);
|
||||
assert!(children.iter().all(|m| !pickable.contains(&m.id)), "a member of compound path {} is pickable", n.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(compounds, 2_500);
|
||||
assert!(skipped > 0 && skipped < 100, "{skipped} locked or hidden compound paths");
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
assert!(hits.len() > 5_000 && hits.len() < all.len() / 2 + 1_000, "{} hits", hits.len());
|
||||
// A selection in another order than the document's: every third object from the end, both
|
||||
// hits and objects that aren't hits.
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(3).copied().collect();
|
||||
assert!(selected.iter().any(|i| hits.contains(i)) && selected.iter().any(|i| !hits.contains(i)));
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits), "Shift-click differs");
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits), "Alt-click differs");
|
||||
// And through the command, in each mode.
|
||||
let ids: Vec<u64> = selected.iter().map(|i| i.0).collect();
|
||||
for (mode, want) in [("set", hits.clone()), ("add", added_by_search(&selected, &hits)), ("subtract", subtracted_by_search(&selected, &hits))]
|
||||
{
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
assert!(s.doc().unwrap().selection.objects == selected, "select.set kept the order");
|
||||
let r = s.execute("select.magicWand", &json!({"id": reference.0, "mode": mode})).unwrap();
|
||||
assert_eq!(r["count"], json!(want.len()), "{mode}");
|
||||
assert!(s.doc().unwrap().selection.objects == want, "{mode} selects other objects or another order");
|
||||
}
|
||||
}
|
||||
|
||||
/// Time the Magic Wand's paintable walk, Shift-click and Alt-click lists and a whole Shift-click
|
||||
/// on documents of 2,000, 20,000 and 50,000 paths, with membership sets and with the searches
|
||||
/// they replace, alternating 7 runs of each and giving the medians in ms. On Linux the times are
|
||||
/// the thread's CPU time.
|
||||
/// Run with `cargo test --release -p vectorcraft-engine --lib magic_wand_membership_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn magic_wand_membership_timing() {
|
||||
fn cpu_ns() -> Option<u64> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
/// The time of one call of `f`, averaged over `reps` calls.
|
||||
fn time(reps: u32, f: &mut dyn FnMut()) -> f64 {
|
||||
let start = (cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..reps {
|
||||
f();
|
||||
}
|
||||
let ms = match (start.0, cpu_ns()) {
|
||||
(Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6,
|
||||
_ => start.1.elapsed().as_secs_f64() * 1000.0,
|
||||
};
|
||||
ms / f64::from(reps)
|
||||
}
|
||||
fn median(v: &mut [f64]) -> f64 {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
}
|
||||
/// Alternate `old` and `new` 7 times each and print their medians and every run. Each run
|
||||
/// takes the mean of enough calls for about 100 ms.
|
||||
fn compare(paths: usize, what: &str, old: &mut dyn FnMut(), new: &mut dyn FnMut()) {
|
||||
let reps = (100.0 / time(1, old).max(0.1)).clamp(1.0, 200.0) as u32;
|
||||
let (mut o, mut n) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
o.push(time(reps, old));
|
||||
n.push(time(reps, new));
|
||||
}
|
||||
let runs = format!("calls per run {reps}: {o:.3?} / {n:.3?}");
|
||||
println!("| {paths} | {what} | {:.3} | {:.3} | {runs}", median(&mut o), median(&mut n));
|
||||
}
|
||||
println!("clock: {}", if cpu_ns().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| paths | step | searches (ms) | sets (ms) | runs");
|
||||
for blocks in [10, 100, 250] {
|
||||
let mut s = wand_session(blocks);
|
||||
let paths = blocks * 200;
|
||||
let st = s.doc().unwrap();
|
||||
let all = paintable(&st.doc);
|
||||
assert!(all == paintable_by_search(&st.doc));
|
||||
let reference = all[0];
|
||||
let hits = hits_by_search(&s, reference);
|
||||
let selected: Vec<NodeId> = all.iter().rev().step_by(2).copied().collect();
|
||||
assert!(added(&selected, hits.clone()) == added_by_search(&selected, &hits));
|
||||
assert!(subtracted(&selected, hits.clone()) == subtracted_by_search(&selected, &hits));
|
||||
let doc = &st.doc;
|
||||
compare(
|
||||
paths,
|
||||
"paintable",
|
||||
&mut || {
|
||||
std::hint::black_box(paintable_by_search(doc));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(paintable(doc));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Shift-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(added_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(added(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
compare(
|
||||
paths,
|
||||
"Alt-click list",
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted_by_search(&selected, &hits));
|
||||
},
|
||||
&mut || {
|
||||
std::hint::black_box(subtracted(&selected, hits.clone()));
|
||||
},
|
||||
);
|
||||
// A whole Shift-click after the selection is set: [`magic_wand`], and its steps with
|
||||
// the searches.
|
||||
let ids = json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<u64>>() });
|
||||
let click = json!({"id": reference.0, "mode": "add"});
|
||||
let s = std::cell::RefCell::new(&mut s);
|
||||
compare(
|
||||
paths,
|
||||
"select.set, then Shift-click",
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
let before = s.doc().unwrap().selection.objects.clone();
|
||||
let picked = added_by_search(&before, &hits_by_search(s, reference));
|
||||
s.select(|_, sel| sel.set(picked)).unwrap();
|
||||
},
|
||||
&mut || {
|
||||
let s = &mut **s.borrow_mut();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
magic_wand(s, &click).unwrap();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isolation_mode_limits_the_wand_to_the_isolated_group() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.optimizeToFileSize",
|
||||
"Optimize to File Size",
|
||||
[],
|
||||
None,
|
||||
"{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting",
|
||||
has_doc,
|
||||
optimize_to_file_size
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.settings",
|
||||
"Save for Web Settings",
|
||||
@@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Optimize to File Size ----------
|
||||
|
||||
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
|
||||
/// it measures once.
|
||||
pub const OPTIMIZE_TRIALS: usize = 32;
|
||||
/// The largest desired file size, in K (1 GiB).
|
||||
pub const MAX_DESIRED_K: f64 = 1_048_576.0;
|
||||
|
||||
/// Where Optimize to File Size starts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StartWith {
|
||||
/// The current format, with its JPEG quality or palette colors lowered.
|
||||
Current,
|
||||
/// GIF or JPEG, by the image's content.
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render,
|
||||
/// else a copy.
|
||||
fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> {
|
||||
if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) }
|
||||
}
|
||||
|
||||
/// The settings Optimize to File Size found.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SizeFit {
|
||||
pub settings: WebSettings,
|
||||
/// The size the settings give the measured images.
|
||||
pub bytes: usize,
|
||||
/// Whether `bytes` is within the target.
|
||||
pub achieved: bool,
|
||||
/// The trial settings encoded.
|
||||
pub trials: usize,
|
||||
}
|
||||
|
||||
/// The files a search measures and the trials it has left.
|
||||
struct Trials<'a> {
|
||||
doc: &'a Document,
|
||||
r: &'a WebRender,
|
||||
/// The pixels (`[x0, y0, x1, y1]`) of each file in `r`.
|
||||
files: &'a [[u32; 4]],
|
||||
/// Measure the largest file (else the files together).
|
||||
each: bool,
|
||||
left: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Trials<'_> {
|
||||
/// The size `s` gives the files, encoded one at a time; `None` when no trial is left.
|
||||
fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> {
|
||||
if self.left == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.left -= 1;
|
||||
self.used += 1;
|
||||
let mut out = 0usize;
|
||||
for &px in self.files {
|
||||
let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len();
|
||||
out = if self.each { out.max(n) } else { out.saturating_add(n) };
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `(settings, bytes)` of a trial.
|
||||
pub type Trial = (WebSettings, usize);
|
||||
|
||||
/// Keep `(s, n)` in `smallest` when it is the smallest trial so far.
|
||||
fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) {
|
||||
if smallest.as_ref().is_none_or(|(_, b)| n < *b) {
|
||||
*smallest = Some((s, n));
|
||||
}
|
||||
}
|
||||
|
||||
/// The values [`highest_within`] measures spread over its range before it narrows a step.
|
||||
pub const OPTIMIZE_SAMPLES: u16 = 6;
|
||||
|
||||
/// Measures the size a setting gives; `None` when no trial is left.
|
||||
pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a;
|
||||
|
||||
/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the
|
||||
/// value `hi` is over it. A lower value can give a larger file, so the search measures up to
|
||||
/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that
|
||||
/// fits, and halves the step between it and the measured value above it, keeping the highest value
|
||||
/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over
|
||||
/// the target go to `smallest`.
|
||||
pub fn highest_within(
|
||||
size: &mut MeasureSize,
|
||||
start: &WebSettings,
|
||||
(lo, hi): (u16, u16),
|
||||
set: fn(&mut WebSettings, u16),
|
||||
target: usize,
|
||||
smallest: &mut Option<Trial>,
|
||||
) -> std::result::Result<Option<Trial>, String> {
|
||||
let with = |v: u16| {
|
||||
let mut s = start.clone();
|
||||
set(&mut s, v);
|
||||
s
|
||||
};
|
||||
if lo >= hi {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = u32::from(hi - lo);
|
||||
let samples = u32::from(OPTIMIZE_SAMPLES).min(span);
|
||||
let (mut above, mut found) = (hi, None);
|
||||
for i in (0..samples).rev() {
|
||||
let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) };
|
||||
let v = lo.saturating_add(u16::try_from(step).unwrap_or(0));
|
||||
let s = with(v);
|
||||
let Some(n) = size(&s)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
found = Some((v, (s, n)));
|
||||
break;
|
||||
}
|
||||
keep_smallest(smallest, s, n);
|
||||
above = v;
|
||||
}
|
||||
let Some((mut lo, mut best)) = found else { return Ok(None) };
|
||||
let mut hi = above;
|
||||
while hi - lo > 1 {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let s = with(mid);
|
||||
let Some(n) = size(&s)? else { break };
|
||||
if n <= target {
|
||||
lo = mid;
|
||||
best = (s, n);
|
||||
} else {
|
||||
keep_smallest(smallest, s, n);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
Ok(Some(best))
|
||||
}
|
||||
|
||||
/// Sets the JPEG quality, for [`highest_within`].
|
||||
pub fn set_quality(s: &mut WebSettings, v: u16) {
|
||||
s.quality = u8::try_from(v).unwrap_or(100);
|
||||
}
|
||||
|
||||
/// Sets the palette colors, for [`highest_within`].
|
||||
pub fn set_colors(s: &mut WebSettings, v: u16) {
|
||||
s.colors = v;
|
||||
}
|
||||
|
||||
/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest
|
||||
/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none
|
||||
/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved.
|
||||
/// `None` when no trial is left.
|
||||
fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> {
|
||||
let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 };
|
||||
let Some(n) = t.size(start)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
return Ok(Some(fit((start.clone(), n), true)));
|
||||
}
|
||||
let mut smallest = Some((start.clone(), n));
|
||||
let found = match start.format {
|
||||
WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?,
|
||||
WebFormat::Gif | WebFormat::Png8 => {
|
||||
match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? {
|
||||
None if start.format == WebFormat::Gif && start.lossy < 100 => {
|
||||
let lossy = WebSettings { lossy: 100, ..start.clone() };
|
||||
match t.size(&lossy)? {
|
||||
Some(n) if n <= target => Some((lossy, n)),
|
||||
Some(n) => {
|
||||
keep_smallest(&mut smallest, lossy.clone(), n);
|
||||
highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)?
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
WebFormat::Png24 => None,
|
||||
};
|
||||
Ok(match (found, smallest) {
|
||||
(Some(f), _) => Some(fit(f, true)),
|
||||
(None, Some(s)) => Some(fit(s, false)),
|
||||
(None, None) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`)
|
||||
/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most
|
||||
/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without
|
||||
/// `transparency`, the pixels blended over `matte`.
|
||||
fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) {
|
||||
let stride = r.width as usize * 4;
|
||||
let row =
|
||||
move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default();
|
||||
let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter()));
|
||||
let opaque = !transparency || pixels().all(|p| p[3] == 255);
|
||||
if !opaque {
|
||||
return (WebFormat::Gif, false);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
// An opaque pixel blends to itself.
|
||||
let few = pixels().all(|p| {
|
||||
seen.insert(flatten(p, matte).next().unwrap_or_default());
|
||||
seen.len() <= 256
|
||||
});
|
||||
(if few { WebFormat::Gif } else { WebFormat::Jpg }, true)
|
||||
}
|
||||
|
||||
/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of
|
||||
/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most
|
||||
/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time.
|
||||
pub fn optimize_to_size(
|
||||
doc: &Document,
|
||||
r: &WebRender,
|
||||
files: &[[u32; 4]],
|
||||
s: &WebSettings,
|
||||
start: StartWith,
|
||||
each: bool,
|
||||
target: usize,
|
||||
) -> std::result::Result<SizeFit, String> {
|
||||
let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 };
|
||||
let with = |format: WebFormat| WebSettings { format, ..s.clone() };
|
||||
let found = match start {
|
||||
_ if files.is_empty() => None,
|
||||
StartWith::Current => search_format(&mut t, s, target)?,
|
||||
StartWith::Auto => {
|
||||
let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3]));
|
||||
let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif };
|
||||
match search_format(&mut t, &with(first), target)? {
|
||||
Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? {
|
||||
Some(b) if b.achieved || b.bytes < a.bytes => Some(b),
|
||||
_ => Some(a),
|
||||
},
|
||||
a => a,
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?;
|
||||
best.trials = t.used;
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const O: &str = "webExport.optimizeToFileSize";
|
||||
let k = p
|
||||
.get("desiredK")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K)
|
||||
.ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?;
|
||||
let target = ((k * 1024.0).floor() as usize).max(1);
|
||||
let start = match p.get("startWith").map(Value::as_str) {
|
||||
None | Some(Some("current")) => StartWith::Current,
|
||||
Some(Some("auto")) => StartWith::Auto,
|
||||
Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")),
|
||||
};
|
||||
let scope = match p.get("use").map(Value::as_str) {
|
||||
None if p.get("slice").is_some() => "currentSlice",
|
||||
None => "allSlices",
|
||||
Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u,
|
||||
Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")),
|
||||
};
|
||||
let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) {
|
||||
None => None,
|
||||
Some(Some(n)) => Some(n),
|
||||
Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")),
|
||||
};
|
||||
let settings = s.web_settings(p).map_err(|e| bad(O, e))?;
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, &settings).map_err(|e| bad(O, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?;
|
||||
let image_cells: Vec<&Cell> =
|
||||
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect();
|
||||
let picked: Vec<&Cell> = match (scope, slice) {
|
||||
("currentSlice", Some(n)) => {
|
||||
let c = image_cells.iter().find(|c| c.area.number as u64 == n);
|
||||
vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?]
|
||||
}
|
||||
("currentSlice", None) => {
|
||||
image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect()
|
||||
}
|
||||
_ => image_cells,
|
||||
};
|
||||
let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() };
|
||||
let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?;
|
||||
Ok(json!({
|
||||
"targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(),
|
||||
"settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const S: &str = "webExport.settings";
|
||||
let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() };
|
||||
|
||||
@@ -24,6 +24,7 @@ mod build;
|
||||
mod cancel;
|
||||
mod caret_kerning;
|
||||
mod charstroke;
|
||||
mod circle_through;
|
||||
pub(super) mod clip;
|
||||
mod clipboard;
|
||||
mod clipflavours;
|
||||
@@ -3312,6 +3313,26 @@ fn flare_ring_seed_moves_only_the_rings() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
let mut s = session();
|
||||
let mut positions = Vec::new();
|
||||
for seed in [0, 1, 2, 5, 11, (1u64 << 53) - 1] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
let ring = children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap();
|
||||
let center = ring.geometric_bounds().unwrap().center();
|
||||
assert!((20.0..=1020.0).contains(¢er.x), "seed {seed}: {center:?}");
|
||||
assert!((center.y - 30.0).abs() < 1e-9);
|
||||
positions.push(center.x);
|
||||
}
|
||||
assert!((positions[0] - positions[1]).abs() > 1.0, "neighboring small seeds visibly move the first ring: {positions:?}");
|
||||
let lo = positions[..5].iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let hi = positions[..5].iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -772,3 +772,142 @@ fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
|
||||
assert!(!v.no_spine, "{odd}");
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Two blends with different options, both selected: the first (Steps 3, along the path, Ease
|
||||
/// Out at 20%, Shift 10%) and the second (Distance 12 pt, along the page, Ease In Out at 60%,
|
||||
/// Shift -40%).
|
||||
fn two_different_blends(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let b1 = make(s, 0.0, json!({"spacing": "steps", "orientation": "path"}));
|
||||
let b2 = make(s, 100.0, json!({"spacing": "distance", "value": 12, "orientation": "path"}));
|
||||
s.execute("object.blend.setEasing", &json!({"id": b1.0, "easingType": "easeOut", "ramp": 20, "colorShift": 10})).unwrap();
|
||||
s.execute("object.blend.setEasing", &json!({"id": b2.0, "easingType": "easeInOut", "ramp": 60, "colorShift": -40})).unwrap();
|
||||
sel(s, &[b2]);
|
||||
s.execute("object.blend.options", &json!({"orientation": "page"})).unwrap();
|
||||
sel(s, &[b1, b2]);
|
||||
(b1, b2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_on_several_blends_set_only_the_values_given() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let (before1, before2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
assert_ne!(before1.spacing, before2.spacing);
|
||||
// Each value given goes to every selected blend; each keeps its own for the others.
|
||||
for (p, apply) in [
|
||||
(json!({"colorShift": 30}), (|sp: &mut BlendSpec| sp.color_shift = 30.0) as fn(&mut BlendSpec)),
|
||||
(json!({"ramp": 45}), |sp| sp.ease.ramp = 0.45),
|
||||
(json!({"easingType": "easeOutIn"}), |sp| sp.ease.kind = vectorcraft_doc::BlendEaseType::OutIn),
|
||||
(json!({"orientation": "path"}), |sp| sp.orientation = BlendOrientation::AlignToPath),
|
||||
(json!({"spacing": "steps", "value": 7}), |sp| sp.spacing = BlendSpacing::Steps(7)),
|
||||
] {
|
||||
let (mut want1, mut want2) = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
apply(&mut want1);
|
||||
apply(&mut want2);
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1), (want1, want2), "{p}");
|
||||
}
|
||||
// A spacing mode without a count keeps the count of a blend already in that mode; a blend in
|
||||
// another mode takes the mode's starting count.
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "distance", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(5)));
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "spacing": "steps", "value": 12})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"spacing": "steps"})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.spacing, spec(&s, b2).1.spacing), (BlendSpacing::Steps(7), BlendSpacing::Steps(12)));
|
||||
// The whole edit of both blends is one undo step.
|
||||
let depth = undo_len(&s);
|
||||
s.execute("object.blend.options", &json!({"colorShift": -5, "ramp": 5})).unwrap();
|
||||
assert_eq!(undo_len(&s), depth + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((spec(&s, b1).1.color_shift, spec(&s, b2).1.color_shift), (30.0, 30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_with_an_id_edit_that_blend_alone() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before2 = spec(&s, b2).1;
|
||||
let mut want1 = spec(&s, b1).1;
|
||||
s.execute("object.blend.options", &json!({"id": b1.0, "spacing": "distance", "value": 15, "ramp": 50, "colorShift": -20})).unwrap();
|
||||
want1.spacing = BlendSpacing::Distance(15.0);
|
||||
want1.ease.ramp = 0.5;
|
||||
want1.color_shift = -20.0;
|
||||
assert_eq!(spec(&s, b1).1, want1, "only the values given change");
|
||||
assert_eq!(spec(&s, b2).1, before2, "a selected blend that is not `id` stays as it was");
|
||||
// `id` works with nothing selected, and does not set the options new blends start with.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "orientation": "path"})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.orientation, BlendOrientation::AlignToPath);
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
// A hidden or locked blend and an object that is not a blend are errors that change nothing.
|
||||
for (visible, locked) in [(false, false), (true, true)] {
|
||||
s.edit("state", |d, _| {
|
||||
let n = d.node_mut(b1).unwrap();
|
||||
(n.visible, n.locked) = (visible, locked);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (before, depth) = (spec(&s, b1).1, undo_len(&s));
|
||||
let error = s.execute("object.blend.options", &json!({"id": b1.0, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("the object is hidden or locked"), "{error}");
|
||||
assert_eq!((spec(&s, b1).1, undo_len(&s)), (before, depth));
|
||||
}
|
||||
let other = rect(&mut s, 300.0, 0.0, 10.0);
|
||||
for id in [json!(other.0), json!(999_999)] {
|
||||
let error = s.execute("object.blend.options", &json!({"id": id, "colorShift": 25})).unwrap_err().to_string();
|
||||
assert!(error.contains("not a blend"), "{error}");
|
||||
}
|
||||
// The blend's own spine decides whether easing is allowed, whatever is selected.
|
||||
s.execute("object.blend.createSpine", &json!({"mode": "never"})).unwrap();
|
||||
let bare = make(&mut s, 300.0, json!({}));
|
||||
sel(&mut s, &[b2]);
|
||||
let error = s.execute("object.blend.options", &json!({"id": bare.0, "ramp": 30})).unwrap_err().to_string();
|
||||
assert!(error.contains("the blend has no spine"), "{error}");
|
||||
s.execute("object.blend.options", &json!({"id": b2.0, "ramp": 30})).unwrap();
|
||||
assert_eq!(spec(&s, b2).1.ease.ramp, 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_that_change_nothing_or_are_refused_record_no_undo_step() {
|
||||
let mut s = session();
|
||||
let (b1, b2) = two_different_blends(&mut s);
|
||||
let before = (spec(&s, b1).1, spec(&s, b2).1);
|
||||
let depth = undo_len(&s);
|
||||
// Values the blends already have, and no values at all.
|
||||
for p in [json!({}), json!({"smooth": false}), json!({"orientation": "page", "id": b2.0}), json!({"colorShift": 10, "id": b1.0})] {
|
||||
s.execute("object.blend.options", &p).unwrap();
|
||||
assert_eq!(undo_len(&s), depth, "{p}");
|
||||
}
|
||||
// An invalid value anywhere stops the whole call before anything changes.
|
||||
for p in [
|
||||
json!({"colorShift": 50, "ramp": 101}),
|
||||
json!({"colorShift": 50, "ramp": -1}),
|
||||
json!({"colorShift": 50, "ramp": "half"}),
|
||||
json!({"ramp": 50, "colorShift": -101}),
|
||||
json!({"ramp": 50, "easingType": "linear"}),
|
||||
json!({"ramp": 50, "spacing": "steps", "value": 0}),
|
||||
json!({"ramp": 50, "spacing": "distance", "value": -3}),
|
||||
json!({"ramp": 50, "id": "b1"}),
|
||||
json!({"ramp": 50, "orientation": "sideways"}),
|
||||
json!({"ramp": 50, "orientation": 1}),
|
||||
json!({"ramp": 50, "value": 3}),
|
||||
json!({"ramp": 50, "spacing": 123}),
|
||||
] {
|
||||
assert!(s.execute("object.blend.options", &p).is_err(), "{p}");
|
||||
assert_eq!((spec(&s, b1).1, spec(&s, b2).1, undo_len(&s)), (before.0.clone(), before.1.clone(), depth), "{p}");
|
||||
}
|
||||
// Make and the options new blends start with refuse an unknown orientation too.
|
||||
let error = s.execute("object.blend.make", &json!({"orientation": "sideways"})).unwrap_err().to_string();
|
||||
assert!(error.contains("orientation must be page or path"), "{error}");
|
||||
assert_eq!(undo_len(&s), depth);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let defaults = s.execute("object.blend.info", &json!({})).unwrap();
|
||||
assert!(s.execute("object.blend.options", &json!({"orientation": "sideways"})).is_err());
|
||||
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap(), defaults);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor
|
||||
//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Whether the geometric bounds of `id` are `want` to within 10⁻⁹ pt.
|
||||
fn bounds_are(s: &Session, id: NodeId, want: vectorcraft_geom::Rect) -> bool {
|
||||
let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap();
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-9)
|
||||
}
|
||||
|
||||
/// The largest distance of `points` from the path of `id`.
|
||||
fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 {
|
||||
let n = node(s, id);
|
||||
let path = n.path_data().unwrap();
|
||||
points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// (0, 0), (80, 0) and (0, 60) lie on the circle centered at (40, 30) with radius 50 (their
|
||||
/// right angle stands on the diameter). The circle is a live ellipse with the current paint, is
|
||||
/// selected, passes through the points to within the four-curve circle's error (about 0.03% of the
|
||||
/// radius), and one undo removes it.
|
||||
#[test]
|
||||
fn the_circle_through_three_given_points_is_exact_and_one_undo_step() {
|
||||
let mut s = session();
|
||||
let reference = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap());
|
||||
let undo = undo_len(&s);
|
||||
let points = [Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(0.0, 60.0)];
|
||||
let out = s.execute(C, &json!({"points": [[0, 0], [80, 0], [0, 60]]})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
let id = id_of(&out);
|
||||
let n = node(&s, id);
|
||||
match &n.kind {
|
||||
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => assert_eq!((*w, *h, *pie), (100.0, 100.0, (0.0, 360.0))),
|
||||
other => panic!("not a live ellipse: {other:?}"),
|
||||
},
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(-10.0, -20.0, 90.0, 80.0)));
|
||||
assert!(farthest_from_path(&s, id, &points) < 50.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert_eq!(n.appearance, node(&s, reference).appearance, "the current paint, as the Ellipse tool draws");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
}
|
||||
|
||||
/// Two points that are the same, or three on one line, are refused with a message; nothing is
|
||||
/// drawn and no undo step is recorded. Points nearly on one line still give their circle.
|
||||
#[test]
|
||||
fn coincident_or_collinear_points_are_refused() {
|
||||
let mut s = session();
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
for points in [json!([[10, 10], [10, 10], [50, 80]]), json!([[0, 0], [50, 50], [100, 100]]), json!([[5, 5], [5, 5], [5, 5]])] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("no circle passes through these points"), "{points}: {e}");
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "{points}");
|
||||
}
|
||||
// 0.01 pt off a chord 200 pt long: the sagitta formula r = (h² + (L/2)²) / 2h.
|
||||
let out = s.execute(C, &json!({"points": [[100, 200], [300, 200], [200, 199.99]]})).unwrap();
|
||||
let want = (0.01f64 * 0.01 + 100.0 * 100.0) / 0.02;
|
||||
let (cx, cy, r) = (out["cx"].as_f64().unwrap(), out["cy"].as_f64().unwrap(), out["radius"].as_f64().unwrap());
|
||||
assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}");
|
||||
}
|
||||
|
||||
/// Points that are not three pairs of finite numbers are an error, not a fallback.
|
||||
#[test]
|
||||
fn malformed_points_are_refused() {
|
||||
let mut s = session();
|
||||
let undo = undo_len(&s);
|
||||
for points in [
|
||||
json!([[0, 0], [10, 0]]),
|
||||
json!([[0, 0], [10, 0], [0, 10], [5, 5]]),
|
||||
json!([[0, 0], [10, 0], [0]]),
|
||||
json!([[0, 0], [10, 0], ["0", 10]]),
|
||||
json!("0,0 10,0 0,10"),
|
||||
json!([[0, 0], [10, 0], [0, 10, 3]]),
|
||||
] {
|
||||
let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string();
|
||||
assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With `points` left out, the three anchor points selected with Direct Selection give the
|
||||
/// circle, from one path or several; any other number of them is an error.
|
||||
#[test]
|
||||
fn three_direct_selected_anchor_points_give_the_circle() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<Value> = [(0, 0), (80, 0), (0, 60), (50, 120)].iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let path = id_of(&s.execute("path.create", &json!({ "anchors": anchors })).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
// Anchors of two paths.
|
||||
let other = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 60}, {"x": 0, "y": 200}]})).unwrap());
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
|
||||
let out = s.execute(C, &json!({"points": null})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}");
|
||||
// Two or four anchors, or a path of four anchors selected whole.
|
||||
for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] {
|
||||
s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap();
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}");
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
// A path of three anchors selected whole counts all three, as the other anchor commands count
|
||||
// them; with an object that is not a path also selected, there is no circle.
|
||||
let triangle = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0]})).unwrap();
|
||||
let out = s.execute(C, &json!({})).unwrap();
|
||||
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(30.0), Some(50.0)), "{out}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let text = id_of(&s.execute("text.create", &json!({"x": 300, "y": 300, "text": "A"})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [triangle.0, text.0]})).unwrap();
|
||||
assert!(s.execute(C, &json!({})).is_err());
|
||||
let undo = undo_len(&s);
|
||||
// Two selected segments hold three ends, which are not selected anchor points.
|
||||
s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3));
|
||||
let e = s.execute(C, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}");
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// With Align New Objects to Pixel Grid on, the circle is still drawn through the points: it is
|
||||
/// not pixel-aligned, so the grid does not move it.
|
||||
#[test]
|
||||
fn the_circle_is_not_moved_onto_the_pixel_grid() {
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
|
||||
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
|
||||
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
let id = id_of(&s.execute(C, &json!({ "points": pairs })).unwrap());
|
||||
assert!(farthest_from_path(&s, id, &points) < 51.0 * 3e-4, "{}", farthest_from_path(&s, id, &points));
|
||||
assert!(!node(&s, id).extras().pixel_aligned);
|
||||
}
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, ..ViewInfo::default() }
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one
|
||||
/// undo step; Escape drops the points placed so far.
|
||||
#[test]
|
||||
fn three_shift_clicks_with_the_ellipse_tool_draw_the_circle_through_them() {
|
||||
let mut s = session();
|
||||
s.select_tool("ellipse", view()).unwrap();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (undo, count) = (undo_len(&s), object_count(&s));
|
||||
click(&mut s, shift, 100.0, 100.0);
|
||||
click(&mut s, shift, 180.0, 100.0);
|
||||
assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two points draw nothing yet");
|
||||
click(&mut s, shift, 100.0, 160.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(90.0, 80.0, 190.0, 180.0)));
|
||||
// Escape after two points: the next three clicks start afresh.
|
||||
click(&mut s, shift, 0.0, 0.0);
|
||||
click(&mut s, shift, 10.0, 300.0);
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
|
||||
click(&mut s, shift, 200.0, 200.0);
|
||||
click(&mut s, shift, 280.0, 200.0);
|
||||
let undo = undo_len(&s);
|
||||
click(&mut s, shift, 200.0, 260.0);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(190.0, 180.0, 290.0, 280.0)));
|
||||
}
|
||||
@@ -95,3 +95,50 @@ fn new_swatch_saves_several_colours_in_one_step() {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": []})).is_err());
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["nope"]})).is_err());
|
||||
}
|
||||
|
||||
/// The tint swatch a swatch named `name` is: (base, tint 0..1); none for any other swatch.
|
||||
fn tint_of(s: &Session, name: &str) -> Option<(String, f32)> {
|
||||
s.doc().unwrap().doc.swatch(name)?.tint_of().map(|(b, t)| (b.to_string(), t))
|
||||
}
|
||||
|
||||
/// `{swatch, tint}` entries of `swatch.new {colors}` and `swatch.newGroup {colors}` make tint
|
||||
/// swatches linked to their spot color, beside plain colors, in one undo step; the tints follow an
|
||||
/// edit of the spot color; a bad entry saves nothing.
|
||||
#[test]
|
||||
fn colors_entries_naming_a_spot_color_save_tint_swatches() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("swatch.new", &json!({"colors": [{"swatch": "Ink", "tint": 60}, "#112233", {"swatch": "Ink", "tint": 30}]})).unwrap();
|
||||
let names = hexes(&r["names"]);
|
||||
assert_eq!(names, ["Ink 60%", "R=17 G=34 B=51", "Ink 30%"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let (base, tint) = tint_of(&s, "Ink 60%").expect("a tint swatch");
|
||||
assert_eq!(base, "Ink");
|
||||
assert!((tint - 0.6).abs() < 1e-6, "{tint}");
|
||||
assert!(tint_of(&s, "R=17 G=34 B=51").is_none());
|
||||
let r = s.execute("swatch.newGroup", &json!({"name": "Guide", "colors": [{"swatch": "Ink", "tint": 45}, "#445566", {"swatch": "Ink"}]})).unwrap();
|
||||
let members = hexes(&r["swatches"]);
|
||||
assert_eq!(members[0], "Ink 45%");
|
||||
assert_eq!(tint_of(&s, "Ink 45%").map(|(b, _)| b).as_deref(), Some("Ink"));
|
||||
assert!(members[1..].iter().all(|m| tint_of(&s, m).is_none()), "a color and the full spot color are process copies: {members:?}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let full = d.swatch(&members[2]).unwrap();
|
||||
assert!(!full.spot && !full.global, "{full:?}");
|
||||
// The tint swatches follow an edit of the spot color.
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#cc0000"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let ink = d.global_color("Ink").unwrap();
|
||||
for name in ["Ink 60%", "Ink 45%"] {
|
||||
let w = d.swatch(name).unwrap();
|
||||
let t = w.tint_of().unwrap().1;
|
||||
assert_eq!(w.paint.color().map(|c| c.to_hex()), Some(ink.tinted(t).to_hex()), "{name}");
|
||||
}
|
||||
// A missing swatch, a tint of a process color or a tint that is not a number saves nothing.
|
||||
let count = s.doc().unwrap().doc.swatches_iter().count();
|
||||
for bad in [json!({"swatch": "Nope", "tint": 50}), json!({"swatch": "R=17 G=34 B=51", "tint": 50}), json!({"swatch": "Ink", "tint": "half"})] {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
assert!(s.execute("swatch.newGroup", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), count);
|
||||
}
|
||||
@@ -86,8 +86,57 @@ fn blob_tip_zero_and_invalid_values_are_safe() {
|
||||
p[key] = value;
|
||||
assert!(s.execute("path.blob", &p).is_err(), "{key}: {p}");
|
||||
}
|
||||
s.execute("path.blob", &json!({"points": [[100, 200], [300, 200]], "angle": 1e300, "roundness": -1e300, "merge": false})).unwrap();
|
||||
assert!(paths(&s)[1].1.control_bounds().unwrap().height().is_finite());
|
||||
let stroke = json!({"points": [[100, 200], [300, 200]], "merge": false});
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"angle": 1e300})), "`angle` must be from -180 to 180 degrees");
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"roundness": -1e300})), "`roundness` must be from 0 to 100%");
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
}
|
||||
|
||||
/// `path.blob` refuses an `angle`, `roundness` or `fidelity` outside its range and changes nothing;
|
||||
/// each end of a range paints, and a key left out or null takes its default (0°, 100% and no fitting).
|
||||
#[test]
|
||||
fn blob_brush_rejects_out_of_range_tip_and_fidelity_without_edit() {
|
||||
let mut s = session();
|
||||
let stroke = json!({"points": [[100, 100], [300, 100]], "size": 20, "merge": false});
|
||||
let angle = "`angle` must be from -180 to 180 degrees";
|
||||
let roundness = "`roundness` must be from 0 to 100%";
|
||||
let fidelity = "`fidelity` must be from 0.01 to 100 pt";
|
||||
for (extra, want) in [
|
||||
(json!({"angle": -180.5}), angle),
|
||||
(json!({"angle": 181}), angle),
|
||||
(json!({"angle": 1e300}), angle),
|
||||
(json!({"roundness": -0.5}), roundness),
|
||||
(json!({"roundness": 101}), roundness),
|
||||
(json!({"fidelity": 0.005}), fidelity),
|
||||
(json!({"fidelity": 0}), fidelity),
|
||||
(json!({"fidelity": -1}), fidelity),
|
||||
(json!({"fidelity": 101}), fidelity),
|
||||
(json!({"fidelity": 1e300}), fidelity),
|
||||
(json!({"angle": 45, "roundness": 50, "fidelity": 100.5}), fidelity),
|
||||
] {
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, extra), want);
|
||||
}
|
||||
assert!(paths(&s).is_empty());
|
||||
let painted = |s: &mut Session, extra: serde_json::Value| {
|
||||
let id = NodeId(s.execute("path.blob", &with(&stroke, extra)).unwrap()["id"].as_u64().unwrap());
|
||||
path(s, id)
|
||||
};
|
||||
for extra in [
|
||||
json!({"angle": -180}),
|
||||
json!({"angle": 180}),
|
||||
json!({"roundness": 0}),
|
||||
json!({"roundness": 100}),
|
||||
json!({"fidelity": 0.01}),
|
||||
json!({"fidelity": 100}),
|
||||
] {
|
||||
let pd = painted(&mut s, extra.clone());
|
||||
assert!(pd.control_bounds().is_some_and(|b| b.height().is_finite() && b.height() > 0.0), "{extra}: {pd:?}");
|
||||
}
|
||||
let defaults = painted(&mut s, json!({}));
|
||||
let nulls = painted(&mut s, json!({"angle": null, "roundness": null, "fidelity": null}));
|
||||
let given = painted(&mut s, json!({"angle": 0, "roundness": 100}));
|
||||
assert_eq!(nulls, defaults);
|
||||
assert_eq!(given, defaults);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -330,6 +379,41 @@ fn pencil_connect_keeps_the_rest_of_a_compound_path_and_refuses_the_extended_pat
|
||||
assert!(s.execute("path.freehand", &json!({"points": points, "extend": {"id": a.0}, "connect": {"id": a.0}})).is_err());
|
||||
}
|
||||
|
||||
/// `path.freehand` refuses a `style` other than "pencil" or "brush" and an `extend` end other than
|
||||
/// "start" or "end" and changes nothing; left out or null, the style is "pencil" and the stroke
|
||||
/// continues the path from its end.
|
||||
#[test]
|
||||
fn pencil_refuses_an_unknown_style_or_extend_end() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
let stroke = json!({"points": [[100, 300], [200, 320], [300, 300]]});
|
||||
for style in [json!("calligraphic"), json!("Brush"), json!(""), json!(1), json!(true)] {
|
||||
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "style": style })), "style must be \"pencil\" or \"brush\"");
|
||||
}
|
||||
let from_end = json!({"points": [[200, 100], [250, 150], [300, 100]]});
|
||||
for end in [json!("middle"), json!("START"), json!(""), json!(0), json!(false)] {
|
||||
let p = with(&from_end, json!({"extend": {"id": a.0, "end": end}}));
|
||||
refuses_with(&mut s, "path.freehand", &p, "extend end must be \"start\" or \"end\"");
|
||||
}
|
||||
assert_eq!((paths(&s).len(), path(&s, a).anchor_count()), (1, 2), "refused: nothing changed");
|
||||
for style in [json!("pencil"), json!("brush"), json!(null)] {
|
||||
s.execute("path.freehand", &with(&stroke, json!({ "style": style }))).unwrap();
|
||||
}
|
||||
assert_eq!(paths(&s).len(), 4);
|
||||
for end in [json!(null), json!("end")] {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &with(&from_end, json!({"extend": {"id": a.0, "end": end}}))).unwrap();
|
||||
let sp = &path(&s, a).subpaths[0];
|
||||
assert_eq!((sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p), (Point::new(100.0, 100.0), Point::new(300.0, 100.0)), "{end}");
|
||||
}
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &json!({"points": [[100, 100], [50, 150], [0, 100]], "extend": {"id": a.0, "end": "start"}})).unwrap();
|
||||
let ends: Vec<Point> = path(&s, a).subpaths[0].anchors.iter().map(|x| x.p).collect();
|
||||
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
|
||||
}
|
||||
|
||||
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
|
||||
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
|
||||
#[test]
|
||||
|
||||
@@ -641,7 +641,7 @@ fn export_selection_reports_the_encoders_warnings() {
|
||||
assert_eq!(plain["format"], "svg");
|
||||
assert!(warnings(&plain).is_empty(), "{plain}");
|
||||
for (format, options, says) in [
|
||||
("webp", json!({"lossless": false}), "lossless"),
|
||||
("webp", json!({"interlaced": true}), "interlaced"),
|
||||
("svg", json!({"profile": "tiny12"}), "blend"),
|
||||
("pdf", json!({"createLayers": true, "compatibility": "1.4"}), "layers"),
|
||||
] {
|
||||
|
||||
@@ -452,6 +452,237 @@ fn what_cannot_be_intertwined_is_refused_with_a_reason() {
|
||||
assert!(e.to_string().contains("not an Intertwine group"), "{e}");
|
||||
}
|
||||
|
||||
// ---------- members dragged in and out in the Layers panel ----------
|
||||
|
||||
/// A green rectangle (84..96 × 46..54) that crosses ring B's stroke at (90, 50) and no part of A.
|
||||
fn green_bar(s: &mut Session) -> NodeId {
|
||||
let id = id_of(&s.execute("shape.rectangle", &json!({"x": 84, "y": 46, "width": 12, "height": 8})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn kids(s: &Session, g: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.node(g).and_then(vectorcraft_doc::Node::children).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn rows(s: &mut Session, ids: &[NodeId], target: NodeId, place: &str, copy: bool) -> Result<Value> {
|
||||
s.execute("layer.move", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "target": target.0, "place": place, "copy": copy}))
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn has_areas(s: &Session, id: NodeId) -> bool {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
n.extras().intertwine.is_some() || !n.extras().intertwine_tiers.is_empty()
|
||||
}
|
||||
|
||||
fn parent(s: &Session, id: NodeId) -> Option<NodeId> {
|
||||
s.doc().unwrap().doc.parent_of(id)
|
||||
}
|
||||
|
||||
/// The help page: "You can drag additional objects into the group later."
|
||||
#[test]
|
||||
fn layer_move_adds_a_member_without_losing_existing_weave() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
let c = green_bar(&mut s);
|
||||
let undo = undo_len(&s);
|
||||
rows(&mut s, &[c], g, "inside", false).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, b, c], "on top of the group's objects");
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
assert!(area(&s, a).is_some(), "the arranged overlap is kept");
|
||||
let r = render(&s);
|
||||
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "the rings are woven as before");
|
||||
assert!(green(&r, 90, 50), "the new member is drawn in its own order");
|
||||
// A live member: its overlap with B can be arranged.
|
||||
assert_eq!(arrange(&mut s, json!({"id": g.0, "at": [90, 50]}))["count"], 1);
|
||||
assert!(blue(&render(&s), 90, 50));
|
||||
for format in ["vectorcraft", "svg"] {
|
||||
let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone();
|
||||
let mut o = Session::new();
|
||||
o.execute("document.open", &json!({"name": format!("woven.{format}"), "dataBase64": data})).unwrap();
|
||||
let r = render(&o);
|
||||
assert!(red(&r, 50, 30) && blue(&r, 50, 70) && blue(&r, 90, 50), "{format}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, b]);
|
||||
assert_eq!(parent(&s, c), parent(&s, g));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, b, c]);
|
||||
}
|
||||
|
||||
/// An object that overlaps no member still joins the group, beside a member's row too; Alt-drag
|
||||
/// adds a copy, which starts drawn in its own order everywhere.
|
||||
#[test]
|
||||
fn layer_move_accepts_nonoverlapping_member() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
let c = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
|
||||
rows(&mut s, &[c], a, "above", false).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, c, b], "above member A");
|
||||
let v = rows(&mut s, &[a], g, "inside", true).unwrap();
|
||||
let copy = NodeId(v["ids"][0].as_u64().unwrap());
|
||||
assert_eq!(kids(&s, g), [a, c, b, copy]);
|
||||
assert!(has_areas(&s, a) && !has_areas(&s, copy), "the copy has no arranged areas");
|
||||
let r = render(&s);
|
||||
assert!(red(&r, 50, 30) && red(&r, 50, 70), "the copy of A is drawn over B at both crossings");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_move_rejects_unsupported_intertwine_members_atomically() {
|
||||
let mut s = session();
|
||||
let (a, b) = rings(&mut s);
|
||||
let p = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
|
||||
select(&mut s, &[p]);
|
||||
let pg = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
select(&mut s, &[a, b, pg]);
|
||||
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
|
||||
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
|
||||
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
|
||||
select(&mut s, &[d, e]);
|
||||
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
|
||||
let f = id_of(&s.execute("shape.rectangle", &json!({"x": 180, "y": 180, "width": 5, "height": 5})).unwrap());
|
||||
select(&mut s, &[g2, f]);
|
||||
let holder = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let layer = s.doc().unwrap().doc.layer_of(g).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_len(&s);
|
||||
// No nested Intertwine groups: not as a member, inside a member's group, beside a member's
|
||||
// row, nor held in a group.
|
||||
for (ids, target, place) in [(g2, g, "inside"), (g2, pg, "inside"), (g2, a, "above"), (holder, g, "inside"), (holder, b, "below")] {
|
||||
let err = rows(&mut s, &[ids], target, place, false).unwrap_err();
|
||||
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{place} {}: {err}", target.0);
|
||||
let err = rows(&mut s, &[ids], target, place, true).unwrap_err();
|
||||
assert!(err.to_string().contains("can't be intertwined"), "copy: {err}");
|
||||
}
|
||||
let err = s.execute("node.move", &json!({"id": holder.0, "parent": g.0, "index": 0})).unwrap_err();
|
||||
assert!(err.to_string().contains("an Intertwine group can't be intertwined"), "{err}");
|
||||
let err = rows(&mut s, &[layer], g, "inside", false).unwrap_err();
|
||||
assert!(err.to_string().contains("can't go into"), "{err}");
|
||||
assert_eq!(undo_len(&s), undo, "no undo step");
|
||||
assert!(s.doc().unwrap().doc == before, "the document is as it was");
|
||||
// A plain object goes into the group inside the Intertwine group.
|
||||
rows(&mut s, &[f], pg, "inside", false).unwrap();
|
||||
assert_eq!(kids(&s, pg), [p, f]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_move_clears_areas_when_member_leaves() {
|
||||
let mut s = session();
|
||||
let (a, b) = rings(&mut s);
|
||||
let c = green_bar(&mut s);
|
||||
select(&mut s, &[a, b, c]);
|
||||
let g = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
assert!(has_areas(&s, a));
|
||||
rows(&mut s, &[a], g, "above", false).unwrap();
|
||||
assert_eq!(parent(&s, a), parent(&s, g));
|
||||
assert!(!has_areas(&s, a), "ordinary art again");
|
||||
assert_eq!(kids(&s, g), [b, c], "two members stay an Intertwine group");
|
||||
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
|
||||
let r = render(&s);
|
||||
assert!(red(&r, 50, 30) && red(&r, 50, 70) && green(&r, 90, 50), "A is above the group at both crossings");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, b, c]);
|
||||
assert!(has_areas(&s, a));
|
||||
assert!(red(&render(&s), 50, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_move_between_intertwines_drops_old_areas() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
let d = id_of(&s.execute("shape.rectangle", &json!({"x": 150, "y": 150, "width": 10, "height": 10})).unwrap());
|
||||
let e = id_of(&s.execute("shape.rectangle", &json!({"x": 155, "y": 150, "width": 10, "height": 10})).unwrap());
|
||||
select(&mut s, &[d, e]);
|
||||
let g2 = id_of(&s.execute("object.intertwine.make", &json!({})).unwrap());
|
||||
rows(&mut s, &[a], g2, "inside", false).unwrap();
|
||||
assert_eq!(kids(&s, g2), [d, e, a]);
|
||||
assert!(!has_areas(&s, a), "the areas of the group it left do not come along");
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none(), "the group A left has one member and is taken apart");
|
||||
assert_eq!(parent(&s, b), parent(&s, g2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_move_dissolves_a_group_left_with_one_member() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
let layer = parent(&s, g).unwrap();
|
||||
let top = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap());
|
||||
select(&mut s, &[g]);
|
||||
let undo = undo_len(&s);
|
||||
rows(&mut s, &[b], top, "above", false).unwrap();
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
assert_eq!(kids(&s, layer), [a, top, b], "the one member left is in the group's place");
|
||||
assert!(!has_areas(&s, a), "with no other member it has no areas");
|
||||
assert!(!s.doc().unwrap().selection.contains(g));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, layer), [g, top]);
|
||||
assert_eq!(kids(&s, g), [a, b]);
|
||||
let r = render(&s);
|
||||
assert!(red(&r, 50, 30) && blue(&r, 50, 70), "woven as before");
|
||||
// Both members out: the empty group is removed.
|
||||
rows(&mut s, &[a, b], g, "above", false).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
assert_eq!(kids(&s, layer), [a, b, top]);
|
||||
assert!(!has_areas(&s, a) && !has_areas(&s, b));
|
||||
}
|
||||
|
||||
/// A group left with one member that has an opacity of its own stays, as a plain group of that
|
||||
/// member, so the member is drawn as before.
|
||||
#[test]
|
||||
fn layer_move_keeps_a_lone_members_group_with_its_own_opacity() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
s.execute("object.setProps", &json!({"ids": [g.0], "opacity": 40})).unwrap();
|
||||
let layer = parent(&s, g).unwrap();
|
||||
rows(&mut s, &[b], g, "above", false).unwrap();
|
||||
assert_eq!(kids(&s, layer), [g, b]);
|
||||
assert_eq!(kids(&s, g), [a]);
|
||||
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
|
||||
assert!(matches!(n.kind, NodeKind::Group { clip: false, .. }), "a plain group");
|
||||
assert!((n.opacity - 0.4).abs() < 1e-6, "{}", n.opacity);
|
||||
assert!(!has_areas(&s, a));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(s.doc().unwrap().doc.node(g).unwrap().kind, NodeKind::Intertwine { .. }));
|
||||
assert_eq!(kids(&s, g), [a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_move_and_send_to_current_layer_clean_up_membership() {
|
||||
let mut s = session();
|
||||
let (g, a, b) = intertwined(&mut s);
|
||||
arrange(&mut s, json!({"at": [50, 30]}));
|
||||
let layer = parent(&s, g).unwrap();
|
||||
s.execute("node.move", &json!({"id": b.0, "parent": layer.0, "index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
assert_eq!(kids(&s, layer), [b, a]);
|
||||
assert!(!has_areas(&s, a));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, b]);
|
||||
// A member sent to the current layer leaves the group the same way.
|
||||
select(&mut s, &[a]);
|
||||
s.execute("object.arrange.sendToCurrentLayer", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
assert_eq!(kids(&s, layer), [b, a]);
|
||||
assert!(!has_areas(&s, a));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// node.move puts an object into an Intertwine group.
|
||||
let c = green_bar(&mut s);
|
||||
s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 1})).unwrap();
|
||||
assert_eq!(kids(&s, g), [a, c, b]);
|
||||
}
|
||||
|
||||
// ---------- on the canvas ----------
|
||||
|
||||
fn press(s: &mut Session, pts: &[(f64, f64)], shift: bool) -> Vec<UiRequest> {
|
||||
|
||||
@@ -3160,6 +3160,27 @@ fn direction_handles_leave_out_hidden_and_locked_paths() {
|
||||
assert_eq!(selected(&s), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_handles_select_many_paths_in_groups_and_layers_in_paint_order() {
|
||||
let mut s = session();
|
||||
let mut paths: Vec<NodeId> = (0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, (i / 20) as f64 * 12.0, 10.0, 10.0)).collect();
|
||||
sel(&mut s, &paths[10..40]);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
paths.extend((0..60).map(|i| rect(&mut s, (i % 20) as f64 * 12.0, 100.0 + (i / 20) as f64 * 12.0, 10.0, 10.0)));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("select.object.directionHandles", &json!({})).unwrap()["anchors"], 4 * paths.len());
|
||||
let st = s.doc().unwrap();
|
||||
let mut want = vectorcraft_doc::Selection::default();
|
||||
for id in st.doc.paint_order(paths.iter().copied()) {
|
||||
want.add(id);
|
||||
want.anchors.insert(id, (0..4).map(|i| (0, i)).collect());
|
||||
}
|
||||
want.new_art = st.selection.new_art.clone();
|
||||
assert_eq!(st.selection.objects.len(), paths.len());
|
||||
assert_eq!(st.selection, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_point_and_area_text() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -767,6 +767,38 @@ fn package_copies_a_linked_eps_file_as_it_is() {
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_the_files_a_linked_eps_files_native_document_places_beside_it() {
|
||||
let dir = Folder::new("package-placed-eps-links");
|
||||
let pic = dir.file("pics/photo.png");
|
||||
write(&pic, &png(600, 300, RED));
|
||||
let mut art = session();
|
||||
place(&mut art, &pic);
|
||||
std::fs::create_dir_all(dir.0.join("art")).unwrap();
|
||||
let src = dir.file("art/seal.eps");
|
||||
run(&mut art, "document.export", json!({"path": src, "format": "eps"}));
|
||||
let mut s = session();
|
||||
let placed = run(&mut s, "file.place", json!({"path": src}));
|
||||
assert_eq!(placed["linked"], true, "{placed}");
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
|
||||
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone(), r["warnings"].clone()), (Some(2), json!([]), json!([])), "{r}");
|
||||
let root = dir.0.join("out/poster Folder");
|
||||
assert_eq!(std::fs::read(root.join("Links/photo.png")).unwrap(), png(600, 300, RED));
|
||||
// The copy of the EPS file finds the picture beside it, not its preview.
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
std::fs::remove_dir_all(dir.0.join("pics")).unwrap();
|
||||
let copy = root.join("Links/seal.eps").to_string_lossy().into_owned();
|
||||
let shows_the_file = || {
|
||||
let bytes = std::fs::read(©).unwrap();
|
||||
let a = cmd::place::document::document_art("seal.eps", &bytes, Some(©), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
|
||||
a.doc.images.values().any(|b| !b.is_proxy())
|
||||
};
|
||||
assert!(shows_the_file());
|
||||
std::fs::remove_file(root.join("Links/photo.png")).unwrap();
|
||||
assert!(!shows_the_file(), "the preview only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_a_linked_postscript_ai_file_the_document_holds_after_it_is_gone() {
|
||||
let dir = Folder::new("package-placed-ps-ai");
|
||||
|
||||
@@ -378,6 +378,60 @@ fn flare_spiral_and_polar_grid_draw_in_perspective() {
|
||||
assert_eq!(attached(&s, NodeId(r["id"].as_u64().unwrap())).map(|a| a.0), Some(Plane::Left));
|
||||
}
|
||||
|
||||
/// Alt-click (Option-click on macOS) with the Flare tool draws one flare with the tool's options as
|
||||
/// one undo step, without a dialog. On the active plane it is the flare the click-opened Flare Tool
|
||||
/// Options draw there; without the grid it is drawn flat. A plain click opens the dialog.
|
||||
#[test]
|
||||
fn an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let (mut s, _) = persp_session();
|
||||
s.execute("perspective.grid.show", &json!({"visible": true})).unwrap();
|
||||
s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("flare", v).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "flare", "values": {"diameter": 40, "rays": 6, "ringsOn": false}})).unwrap();
|
||||
let options = s.tool_options_of("flare");
|
||||
let at = Point::new(300.0, 380.0);
|
||||
let alt = Mods { alt: true, ..Default::default() };
|
||||
let alt_click = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(alt), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(alt), v).unwrap()
|
||||
};
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(alt_click(&mut s), vec![], "no dialog");
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.journal.last().unwrap().0, "perspective.draw");
|
||||
let id = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Left));
|
||||
let drawn = node(&s, id).geometric_bounds().unwrap();
|
||||
assert_eq!(s.tool_options_of("flare"), options, "the click leaves the options as they are");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, id).geometric_bounds(), Some(drawn));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let params = vectorcraft_tools::extra::flare_params(&options, at);
|
||||
let (cmd, p) = crate::perspective_click(&s, "shape.flare", ¶ms, at).unwrap();
|
||||
let dialog = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(node(&s, dialog).geometric_bounds(), Some(drawn), "the flare the dialog's OK draws");
|
||||
// A click above the ground plane's horizon draws nothing and reports the error.
|
||||
s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap();
|
||||
let above = grid(&s).horizon - 50.0;
|
||||
let n = undo_len(&s);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, above).with_mods(alt), v).unwrap();
|
||||
assert!(s.pointer(&PointerEvent::new(PointerKind::Up, at.x, above).with_mods(alt), v).is_err());
|
||||
assert_eq!(undo_len(&s), n);
|
||||
// Without the grid the flare is drawn flat; a plain click opens the dialog.
|
||||
s.execute("perspective.grid.show", &json!({"visible": false})).unwrap();
|
||||
assert_eq!(alt_click(&mut s), vec![]);
|
||||
assert_eq!(s.journal.last().unwrap().0, "shape.flare");
|
||||
let flat = *s.doc().unwrap().selection.objects.first().unwrap();
|
||||
assert_eq!(attached(&s, flat), None);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
|
||||
let ui = s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap();
|
||||
assert_eq!(ui, vec![UiRequest::Dialog("flare".into(), json!({"x": at.x, "y": at.y}))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() {
|
||||
let (mut s, _) = persp_session();
|
||||
|
||||
@@ -1212,6 +1212,30 @@ fn a_click_of_the_place_cursor_asks_the_frontend_to_place_the_file_when_asked_to
|
||||
assert_eq!(s.journal.last(), at_once.journal.last());
|
||||
}
|
||||
|
||||
/// A Shift-click of the place cursor asks the frontend for the file's import options
|
||||
/// (`showImportOptions: true`); headless, with no frontend to ask, it places the file as a click
|
||||
/// does.
|
||||
#[test]
|
||||
fn a_shift_click_of_the_place_cursor_places_headless_as_a_click_does() {
|
||||
let view = ViewInfo::default();
|
||||
let files: Vec<Value> = ["a.png", "b.png"].iter().map(|n| file(n, &png(40, 20, [9, 9, 9, 255], None))).collect();
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (mut headless, mut app) = (session(), session());
|
||||
app.place_cursor_requests = true;
|
||||
let mut reqs = vec![];
|
||||
for s in [&mut headless, &mut app] {
|
||||
s.execute("file.place.queue", &json!({"files": files})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0).with_mods(shift), view).unwrap();
|
||||
reqs = s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0).with_mods(shift), view).unwrap();
|
||||
}
|
||||
let [UiRequest::Place(p)] = &reqs[..] else { panic!("{reqs:?}") };
|
||||
assert_eq!(p["showImportOptions"], true);
|
||||
let [img] = &top_children(&headless)[..] else { panic!("one image placed") };
|
||||
let b = img.geometric_bounds().unwrap();
|
||||
assert_eq!([b.x0, b.y0, b.width(), b.height()], [10.0, 10.0, 40.0, 20.0]);
|
||||
assert_eq!(headless.tool_options()["names"], json!(["b.png"]));
|
||||
}
|
||||
|
||||
/// Files read for the place cursor apart from the session ([`Session::prepare_place_queue`], then
|
||||
/// [`cmd::place::QueueJob::read`] on another thread and [`Session::place_queue_read`]) load it as
|
||||
/// `file.place.queue` loads it: the same reply, with the files that can't be read skipped, and the
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Use Preview Bounds: the Transform panel values, the bounding box, Align and Distribute measure
|
||||
//! visual bounds (strokes and geometry effects included) when it is on.
|
||||
//! visual bounds (strokes, geometry and projected 3D effects included) when it is on.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -103,6 +103,284 @@ fn near(a: Rect, b: Rect, tolerance: f64) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tolerance)
|
||||
}
|
||||
|
||||
const PREVIEW_3D: [&str; 4] = ["threeD.extrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"];
|
||||
|
||||
/// A live projected rectangle, with the effect on the object or its painted fill.
|
||||
fn projected_rect(s: &mut Session, effect: &str, item: bool) -> NodeId {
|
||||
let id = rect(s, 100.0, 80.0, 0.0);
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect), "item": if item { json!(0) } else { Value::Null }}));
|
||||
id
|
||||
}
|
||||
|
||||
/// Settings for `effect` that turn the art and give it depth.
|
||||
fn params_3d(effect: &str) -> Value {
|
||||
let mut params = json!({"rotationX": -20, "rotationY": 35, "rotationZ": 15, "perspectiveAngle": 0, "shade": false});
|
||||
match effect {
|
||||
"threeD.revolve" => {
|
||||
params["segments"] = json!(8);
|
||||
params["angle"] = json!(240);
|
||||
params["offset"] = json!(12);
|
||||
}
|
||||
"threeD.extrude" => {
|
||||
params["depth"] = json!(40);
|
||||
params["bevel"] = json!("rounded");
|
||||
}
|
||||
"threeD.inflate" => params["depth"] = json!(20),
|
||||
_ => {}
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// Measure the renderer's projected vector art, including any geometry effects left after 3D.
|
||||
fn projected(s: &Session, id: NodeId) -> Rect {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(id).unwrap();
|
||||
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
|
||||
vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap()
|
||||
}
|
||||
|
||||
/// All four projected effects contribute at object and item scope; off and hidden keep source bounds.
|
||||
#[test]
|
||||
fn preview_3d_measures_the_projected_art_at_object_and_item_scope() {
|
||||
for effect in PREVIEW_3D {
|
||||
for item in [false, true] {
|
||||
let mut s = session();
|
||||
let id = projected_rect(&mut s, effect, item);
|
||||
let expected = projected(&s, id);
|
||||
let source = geometric(&s, id);
|
||||
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
|
||||
preview(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
|
||||
preview(&mut s, false);
|
||||
assert_eq!(s.transform_bounds(&[id]), Some(source));
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "effect.setParams", json!({"ids": [id.0], "index": 0, "item": if item { json!(0) } else { Value::Null }, "visible": false}));
|
||||
assert_eq!(s.transform_bounds(&[id]), Some(source), "hidden {effect}, item={item}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Align and spacing use projected edges, with one undo step and no repeat-alignment edit.
|
||||
#[test]
|
||||
fn preview_3d_align_and_spacing_measure_projected_edges() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut s = session();
|
||||
let a = projected_rect(&mut s, effect, false);
|
||||
let b = rect(&mut s, 20.0, 30.0, 0.0);
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "object.align", json!({"horizontal": "left"}));
|
||||
assert!((projected(&s, a).x0 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
|
||||
let aligned = s.doc().unwrap().doc.clone();
|
||||
run(&mut s, "object.align", json!({"horizontal": "left"}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "already aligned {effect}");
|
||||
assert_eq!(s.doc().unwrap().doc, aligned);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc, aligned);
|
||||
|
||||
let mut s = session();
|
||||
let a = projected_rect(&mut s, effect, false);
|
||||
let b = rect(&mut s, 350.0, 30.0, 0.0);
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
run(&mut s, "object.distributeSpacing", json!({"axis": "horizontal", "spacing": 0}));
|
||||
assert!((projected(&s, a).x1 - geometric(&s, b).x0).abs() < 1e-6, "{effect}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's and a symbol's projected members are measured as art rather than flat source paths.
|
||||
#[test]
|
||||
fn preview_3d_measures_projected_group_and_symbol_members() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut source = session();
|
||||
let source_id = projected_rect(&mut source, effect, false);
|
||||
let expected = projected(&source, source_id);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let mut shape = source.doc().unwrap().doc.node(source_id).unwrap().clone();
|
||||
shape.id = d.alloc_id();
|
||||
let group = Node::group(d.alloc_id(), vec![Arc::new(shape.clone())]);
|
||||
let group_id = group.id;
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
shape.id = d.alloc_id();
|
||||
d.symbols.push(Symbol { dynamic: false, name: "3D / Bounds".into(), art: Arc::new(shape) });
|
||||
let shift = Affine::translate((250.0, 0.0));
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Bounds".into(), xf: shift });
|
||||
let instance_id = instance.id;
|
||||
d.insert(Some(layer), 1, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
preview(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[group_id]).unwrap(), expected, 1e-6), "group {effect}");
|
||||
assert!(near(s.transform_bounds(&[instance_id]).unwrap(), shift.transform_rect_bbox(expected), 1e-6), "symbol {effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol instance with a 3D effect of its own is measured by the art the renderer projects from its symbol.
|
||||
#[test]
|
||||
fn preview_3d_measures_an_instance_with_its_own_effect() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let square = Node::path(
|
||||
d.alloc_id(),
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 80.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "3D / Own".into(), art: Arc::new(square) });
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Own".into(), xf: Affine::translate((50.0, 40.0)) });
|
||||
let (layer, id) = (d.layers[0].id, instance.id);
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "params": params_3d(effect)}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(id).unwrap();
|
||||
let art = vectorcraft_render::effects::revolve_art_in(Some(d), n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), n)).unwrap();
|
||||
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
|
||||
let source = geometric(&s, id);
|
||||
assert!(!near(expected, source, 1e-3), "the fixture must change its bounds: {effect}");
|
||||
preview(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Dynamic instance overrides are applied before deciding which painted 3D surfaces remain.
|
||||
#[test]
|
||||
fn preview_3d_dynamic_symbol_overrides_precede_projection() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut source = session();
|
||||
let source_id = projected_rect(&mut source, effect, false);
|
||||
let full = projected(&source, source_id);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let mut art = source.doc().unwrap().doc.node(source_id).unwrap().clone();
|
||||
art.id = d.alloc_id();
|
||||
d.symbols.push(Symbol { dynamic: true, name: "3D / Dynamic".into(), art: Arc::new(art) });
|
||||
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "3D / Dynamic".into(), xf: Affine::IDENTITY });
|
||||
instance
|
||||
.extras_mut()
|
||||
.symbol_overrides
|
||||
.push(vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(Paint::None), ..Default::default() });
|
||||
let id = instance.id;
|
||||
let changed = vectorcraft_doc::symbol_overrides::dynamic_art(&d.symbols[0].art, &instance);
|
||||
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &changed);
|
||||
if effect == "threeD.extrude" {
|
||||
assert!(expected.is_some(), "the Extrude fixture must retain its source bounds");
|
||||
}
|
||||
assert!(expected.is_none_or(|b| !near(b, full, 1e-3)), "the override must remove the projected surface: {effect}");
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, instance).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.add_document(d, None);
|
||||
preview(&mut s, true);
|
||||
let actual = s.transform_bounds(&[id]);
|
||||
assert!(
|
||||
match (actual, expected) {
|
||||
(Some(a), Some(b)) => near(a, b, 1e-6),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
},
|
||||
"overridden {effect}: {actual:?}, expected {expected:?}"
|
||||
);
|
||||
run(&mut s, "symbol.instance.reset", json!({"ids": [id.0]}));
|
||||
assert!(near(s.transform_bounds(&[id]).unwrap(), full, 1e-6), "reset {effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometry after projection remains part of the measured stack at object and item scope.
|
||||
#[test]
|
||||
fn preview_3d_applies_geometry_after_the_projected_surface() {
|
||||
for effect in PREVIEW_3D {
|
||||
for item in [false, true] {
|
||||
let mut s = session();
|
||||
let id = projected_rect(&mut s, effect, item);
|
||||
run(
|
||||
&mut s,
|
||||
"effect.apply",
|
||||
json!({"ids": [id.0], "effect": "path.offsetPath", "params": {"offset": 5}, "item": if item { json!(0) } else { Value::Null }}),
|
||||
);
|
||||
let expected = projected(&s, id);
|
||||
preview(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[id]).unwrap(), expected, 1e-6), "{effect}, item={item}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed width sizes the projected art and remains one undoable edit.
|
||||
#[test]
|
||||
fn preview_3d_set_bounds_sizes_the_projected_width() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut s = session();
|
||||
let id = projected_rect(&mut s, effect, false);
|
||||
let target = projected(&s, id).width() * 1.25;
|
||||
preview(&mut s, true);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "object.setBounds", json!({"width": target, "reference": 0, "proportional": true, "strokes": false}));
|
||||
assert!((projected(&s, id).width() - target).abs() < 1e-4, "{effect}: {:?}, target {target}", projected(&s, id));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rotated selection measures the projected surface in its own bounding-box frame.
|
||||
#[test]
|
||||
fn preview_3d_oriented_box_follows_projected_art() {
|
||||
for effect in PREVIEW_3D {
|
||||
let mut s = session();
|
||||
let id = projected_rect(&mut s, effect, false);
|
||||
run(&mut s, "object.rotate", json!({"angle": 30}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let angle = d.bbox_angle(&[id]);
|
||||
assert!(angle.abs() > 0.1);
|
||||
let n = d.node(id).unwrap();
|
||||
let art = vectorcraft_render::effects::revolve_art(n).or_else(|| vectorcraft_render::effects::solid_art(n)).unwrap();
|
||||
let frame = vectorcraft_doc::OrientedBox { angle, rect: Rect::ZERO }.to_doc().inverse();
|
||||
let expected = vectorcraft_render::effects::preview::bounds_in(&d.symbol_boxes(), &art, frame).unwrap();
|
||||
preview(&mut s, true);
|
||||
let measured = s.transform_box(&[id]).unwrap();
|
||||
assert_eq!(measured.angle, angle);
|
||||
assert!(near(measured.rect, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on a member of a layer with a 3D effect selects that member, with Use Preview Bounds on
|
||||
/// or off, and the layer is still measured by its projected art.
|
||||
#[test]
|
||||
fn a_click_selects_the_member_of_a_layer_with_a_3d_effect() {
|
||||
for effect in PREVIEW_3D {
|
||||
for on in [false, true] {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 80.0, 0.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
run(&mut s, "effect.apply", json!({"ids": [layer.0], "effect": effect, "params": params_3d(effect), "item": null}));
|
||||
preview(&mut s, on);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, 140.0, 125.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(s.active().unwrap().selection.objects, [id], "{effect}, preview={on}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art =
|
||||
vectorcraft_render::effects::revolve_art(&d.layers[0]).or_else(|| vectorcraft_render::effects::solid_art(&d.layers[0])).unwrap();
|
||||
let expected = vectorcraft_render::effects::preview::visual_bounds(&d.symbol_boxes(), &art).unwrap();
|
||||
let measured = vectorcraft_render::effects::preview::bounds_of(d, &[layer], true).unwrap();
|
||||
assert!(near(measured, expected, 1e-6), "{effect}: {measured:?} vs {expected:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_square_with_offset_path_is_measured_by_the_offset_shape() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -47,6 +47,81 @@ fn setup_is_saved_with_the_document_as_one_undo_step() {
|
||||
assert!(vectorcraft_format::load(v.to_string().as_bytes()).unwrap().print_setup.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_is_saved_with_the_setup_and_in_presets() {
|
||||
let (mut s, _) = session();
|
||||
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["output"]["overprintBlack"], false, "off by default");
|
||||
let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "overprintBlack": true}}})).unwrap();
|
||||
assert_eq!(v["settings"]["output"]["overprintBlack"], true);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert!(back.print_setup.as_ref().is_some_and(|p| p["output"]["overprintBlack"] == true), "kept in the native file");
|
||||
// Settings saved before the option load with it off; a value that is not true or false is refused.
|
||||
let old: vectorcraft_pdf::PrintSettings = serde_json::from_value(json!({"output": {"mode": "separations"}})).unwrap();
|
||||
assert!(!old.output.overprint_black);
|
||||
assert!(matches!(s.execute("print.setup", &json!({"settings": {"output": {"overprintBlack": "yes"}}})), Err(EngineError::BadParams { .. })));
|
||||
// Print presets keep it and list it as a change from [Default].
|
||||
let mut s = Session::new();
|
||||
s.execute("print.presets.save", &json!({"name": "Seps", "settings": {"output": {"overprintBlack": true}}})).unwrap();
|
||||
assert!(s.prefs.print_presets[0].settings.output.overprint_black);
|
||||
let v = s.execute("print.presets.list", &json!({})).unwrap();
|
||||
let changed: Vec<&str> = v["presets"][1]["changed"].as_array().unwrap().iter().map(|c| c["option"].as_str().unwrap()).collect();
|
||||
assert_eq!(changed, ["output.overprintBlack"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scale_link_keeps_width_and_height_equal() {
|
||||
let (mut s, _) = session();
|
||||
let scale = |s: &mut Session, p: Value| s.execute("print.setup", &json!({ "settings": p })).unwrap()["settings"]["scale"].clone();
|
||||
assert_eq!(scale(&mut s, json!({})), json!({"width": 100.0, "height": 100.0, "linked": true}), "on for a new job");
|
||||
// Linked, one percentage sets the other, whichever it is.
|
||||
assert_eq!(scale(&mut s, json!({"scaling": "custom", "scale": {"width": 40}})), json!({"width": 40.0, "height": 40.0, "linked": true}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"height": 250}})), json!({"width": 250.0, "height": 250.0, "linked": true}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"width": 60, "height": 60.0}})), json!({"width": 60.0, "height": 60.0, "linked": true}));
|
||||
// Two different percentages with linked: true are refused and keep what was saved.
|
||||
let apart = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}}));
|
||||
assert!(matches!(apart, Err(EngineError::BadParams { .. })), "{apart:?}");
|
||||
assert!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": true}}})).is_err());
|
||||
// `linked: null` keeps the saved link, as null keeps any saved setting.
|
||||
let kept = s.execute("print.setup", &json!({"settings": {"scale": {"width": 50, "height": 200, "linked": null}}}));
|
||||
assert!(matches!(kept, Err(EngineError::BadParams { .. })), "{kept:?}");
|
||||
assert_eq!(scale(&mut s, json!({}))["width"], 60.0);
|
||||
// Without linked, two different percentages turn the link off and print as given.
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"width": 50, "height": 200}})), json!({"width": 50.0, "height": 200.0, "linked": false}));
|
||||
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 200.0]));
|
||||
// Unlinked, each changes alone; turning the link on sets the height to the width.
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"height": 120}})), json!({"width": 50.0, "height": 120.0, "linked": false}));
|
||||
assert_eq!(scale(&mut s, json!({"scale": {"linked": true}})), json!({"width": 50.0, "height": 50.0, "linked": true}));
|
||||
assert_eq!(s.execute("print.preview", &json!({})).unwrap()["sheets"][0]["scale"], json!([50.0, 50.0]));
|
||||
// Kept in the native file and in print presets.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.print_setup.as_ref().map(|p| p["scale"].clone()), Some(json!({"width": 50.0, "height": 50.0, "linked": true})));
|
||||
s.execute("print.presets.save", &json!({"name": "Apart", "settings": {"scaling": "custom", "scale": {"width": 30, "height": 90}}})).unwrap();
|
||||
let preset = s.prefs.print_presets.iter().find(|p| p.name == "Apart").map(|p| p.settings.scale.clone());
|
||||
assert_eq!(preset.map(|p| (p.width, p.height, p.linked)), Some((30.0, 90.0, false)));
|
||||
assert_eq!(scale(&mut s, json!({}))["linked"], true, "saving a preset leaves the document's settings");
|
||||
let v = s.execute("print.setup", &json!({"preset": "Apart"})).unwrap();
|
||||
assert_eq!(v["settings"]["scale"], json!({"width": 30.0, "height": 90.0, "linked": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_saved_without_the_link_keeps_its_width_and_height() {
|
||||
let (mut s, _) = session();
|
||||
// Settings saved before the link had no `linked`: they print as they did, unlinked.
|
||||
let mut old = serde_json::to_value(vectorcraft_pdf::PrintSettings::default()).unwrap();
|
||||
old["scaling"] = json!("custom");
|
||||
old["scale"] = json!({"width": 50, "height": 200});
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
doc.print_setup = Some(old);
|
||||
s.doc_mut().unwrap().doc = std::sync::Arc::new(doc);
|
||||
let pv = s.execute("print.preview", &json!({})).unwrap();
|
||||
assert_eq!(pv["sheets"][0]["scale"], json!([50.0, 200.0]));
|
||||
assert_eq!(pv["settings"]["scale"]["linked"], false);
|
||||
// One percentage changes alone until the link is turned on.
|
||||
assert_eq!(s.execute("print.preview", &json!({"settings": {"scale": {"width": 80}}})).unwrap()["sheets"][0]["scale"], json!([80.0, 200.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_writes_the_saved_setup_with_overrides() {
|
||||
let (mut s, _) = session();
|
||||
@@ -316,3 +391,21 @@ fn for_a_printer_a_landscape_page_is_written_upright() {
|
||||
assert_eq!(size(&spooled), [(612.0, 792.0)]);
|
||||
assert_eq!(v["pages"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let ink = json!({"name": "Gold", "convertToProcess": true});
|
||||
let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "inks": [ink]}}})).unwrap();
|
||||
assert_eq!(v["settings"]["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}]));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.print_setup.as_ref().map(|p| p["output"]["inks"][0]["convertToProcess"].clone()), Some(json!(true)), "kept in the file");
|
||||
let pv = s.execute("print.preview", &json!({})).unwrap();
|
||||
let names = |list: &Value| list.as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&pv["inks"]), ["Cyan", "Magenta", "Yellow", "Black"], "no Gold plate");
|
||||
assert_eq!(names(&pv["documentInks"]), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]);
|
||||
assert_eq!(pv["documentInks"][4]["convertToProcess"], json!(true));
|
||||
assert_eq!(pv["documentInks"][0].get("convertToProcess"), None, "written only when on");
|
||||
}
|
||||
@@ -395,6 +395,56 @@ fn expand_rasterize_then_transform_matches_canvas() {
|
||||
assert!(matches!(&n.kind, vectorcraft_doc::NodeKind::Group { children, .. } if children.is_empty()), "{:?}", n.kind);
|
||||
}
|
||||
|
||||
/// With copies, the Transform effect after Rasterize places the one image on the original and on
|
||||
/// each copy: Expand Appearance and PDF export make a group of the image placed by each copy's
|
||||
/// map, the last copy lowest and the original on top, as the canvas draws it, all on the pixels
|
||||
/// Object › Rasterize makes of the art.
|
||||
#[test]
|
||||
fn expand_rasterize_then_copying_transform_places_the_image_on_each_copy() {
|
||||
let mut o = session();
|
||||
red_rectangle(&mut o);
|
||||
let made = id(&o.execute("object.rasterize", &json!({"ppi": 72, "background": "white", "addAround": 2})).unwrap());
|
||||
let od = &o.doc().unwrap().doc;
|
||||
let (w, h, xf, png, _) = rasterized(od, od.node(made).unwrap());
|
||||
let about =
|
||||
|m: vectorcraft_geom::Affine| vectorcraft_geom::Affine::translate((70.5, 65.25)) * m * vectorcraft_geom::Affine::translate((-70.5, -65.25));
|
||||
let turn = |deg: f64| about(vectorcraft_geom::Affine::rotate(-deg.to_radians()));
|
||||
let cases = [
|
||||
(json!({"moveH": 50, "copies": 2}), [vectorcraft_geom::Affine::translate((100.0, 0.0)), vectorcraft_geom::Affine::translate((50.0, 0.0))]),
|
||||
(json!({"rotate": 30, "copies": 2}), [turn(60.0), turn(30.0)]),
|
||||
];
|
||||
for (params, [lowest, middle]) in cases {
|
||||
let mut s = session();
|
||||
let r = red_rectangle(&mut s);
|
||||
let raster = json!({"useDocumentResolution": false, "resolution": 72, "background": "white", "addAround": 2});
|
||||
s.execute("effect.apply", &json!({"effect": "rasterize", "params": raster, "ids": [r.0]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": params.clone(), "ids": [r.0]})).unwrap();
|
||||
let check = |d: &Document, n: &vectorcraft_doc::Node, what: &str| {
|
||||
let NodeKind::Group { children, clip: false } = &n.kind else { panic!("{what} {params}: a group, {:?}", n.kind_label()) };
|
||||
assert_eq!(children.len(), 3, "{what} {params}");
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
for (c, map) in children.iter().zip([lowest, middle, vectorcraft_geom::Affine::IDENTITY]) {
|
||||
let (w2, h2, xf2, png2, _) = rasterized(d, c);
|
||||
assert_eq!((w2, h2), (w, h), "{what} {params}");
|
||||
assert!(png2 == png, "{what} {params}: the same pixels");
|
||||
let want = map * xf;
|
||||
assert!(xf2.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{what} {params}: {xf2:?} {want:?}");
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
keys.insert(im.key.clone());
|
||||
}
|
||||
}
|
||||
assert_eq!(keys.len(), 1, "{what} {params}: one image for the three placements");
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
n.walk(&mut |c| assert!(ids.insert(c.id), "{what} {params}: id {:?} twice", c.id));
|
||||
};
|
||||
let flat = crate::flatten_raster_effects(&s.doc().unwrap().doc).unwrap();
|
||||
check(&flat, &flat.layers[0].children().unwrap()[0], "PDF export");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [r.0]})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
check(d, d.node(r).unwrap(), "Expand Appearance");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_mask_follows_the_art_its_geometry_effects_draw() {
|
||||
let clip = |s: &Session, n: NodeId| match &s.doc().unwrap().doc.node(n).unwrap().kind {
|
||||
|
||||
@@ -369,3 +369,129 @@ fn scale_text_attributes_keeps_tracked_type_where_it_was() {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What Scale Text Attributes must leave as it was: the document-space bounds of an area's frame
|
||||
/// or a path type's path, each line's text, whether the text overflows, and where each glyph
|
||||
/// starts on the page.
|
||||
struct Placed {
|
||||
outline: Option<vectorcraft_geom::Rect>,
|
||||
lines: Vec<(usize, usize)>,
|
||||
overflow: bool,
|
||||
pens: Vec<Point>,
|
||||
}
|
||||
|
||||
fn placed(s: &Session, id: NodeId) -> Placed {
|
||||
let t = text(s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let outline = match &t.kind {
|
||||
vectorcraft_doc::TextKind::Area { frame } => Some(frame),
|
||||
vectorcraft_doc::TextKind::OnPath { path, .. } => Some(path),
|
||||
vectorcraft_doc::TextKind::Point => None,
|
||||
};
|
||||
Placed {
|
||||
outline: outline.and_then(|p| p.transformed(t.xf).bounds()),
|
||||
lines: lay.lines.iter().map(|l| (l.start, l.end)).collect(),
|
||||
overflow: lay.overflow,
|
||||
pens: lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn same_place(before: &Placed, after: &Placed) {
|
||||
let (Some(b), Some(a)) = (before.outline, after.outline) else { panic!("no frame or path: {:?} {:?}", before.outline, after.outline) };
|
||||
for (x, y) in [(b.x0, a.x0), (b.y0, a.y0), (b.x1, a.x1), (b.y1, a.y1)] {
|
||||
assert!((x - y).abs() < 1e-6, "frame {b:?} became {a:?}");
|
||||
}
|
||||
assert_eq!(after.lines, before.lines, "line breaks");
|
||||
assert_eq!(after.overflow, before.overflow, "overflow");
|
||||
assert_eq!(before.pens.len(), after.pens.len());
|
||||
for (b, a) in before.pens.iter().zip(&after.pens) {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{:?} {:?}", before.pens, after.pens);
|
||||
}
|
||||
}
|
||||
|
||||
/// #8297: Scale Text Attributes on scaled area type keeps the frame the scale gave it, so the
|
||||
/// lines break where they did and no text becomes overset. It used to leave the frame at its
|
||||
/// unscaled size, which then held two lines of the larger type and hid the rest.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_an_area_frame_and_its_lines() {
|
||||
for (sx, sy, size) in [(200, 200, 24.0), (200, 100, 12.0), (50, 50, 6.0)] {
|
||||
let mut s = session();
|
||||
let id = NodeId(
|
||||
s.execute(
|
||||
"text.create",
|
||||
&json!({"x": 40, "y": 60, "size": 12, "area": {"width": 120, "height": 80}, "text": "Bright river stones mark a gentle path past old trees."}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("object.scale", &json!({"sx": sx, "sy": sy, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(before.lines.len() >= 3 && !before.overflow, "{sx}x{sy}: {:?}", before.lines);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, size);
|
||||
same_place(&before, &placed(&s, id));
|
||||
if (sx, sy) == (200, 200) {
|
||||
let f = before.outline.unwrap();
|
||||
assert_eq!((f.x0.round(), f.y0.round(), f.x1.round(), f.y1.round()), (80.0, 120.0, 320.0, 280.0));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 12.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a path keeps its path: it used to shrink with the scale removed, so the type ran past
|
||||
/// its end.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_a_path_types_path() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M100 300 L300 300" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Along the way", "size": 12, "at": [100, 300]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(!before.overflow);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
|
||||
/// A non-uniform scale on type on a path: only the uniform part is baked and the stretch stays in
|
||||
/// the transform, so the brackets, which sit at fractions of the path's length, stay where they
|
||||
/// were. Baking the stretch into the path would move them: on this path, scaled 3 × 2, the length
|
||||
/// grows from 200 to 500 and not in proportion, so the same fraction lands elsewhere.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_path_type_on_a_stretched_path_where_it_was() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M0 0 L100 0 L100 100" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Corner", "size": 12, "at": [60, 0]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 300, "sy": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
let brackets = |s: &Session| match text(s, id).kind {
|
||||
vectorcraft_doc::TextKind::OnPath { start, end, .. } => (start, end),
|
||||
k => panic!("not path type: {k:?}"),
|
||||
};
|
||||
let before_brackets = brackets(&s);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
near(text(&s, id).runs[0].style.h_scale, 100.0);
|
||||
let left = text(&s, id).style_scale().unwrap();
|
||||
near(left.points, 1.0);
|
||||
near(left.horizontal, 1.5);
|
||||
assert_eq!(brackets(&s), before_brackets);
|
||||
same_place(&before, &placed(&s, id));
|
||||
// Only the stretch is left: there is nothing more to bake.
|
||||
assert!(s.execute("type.scaleTextAttributes", &json!({})).is_err());
|
||||
}
|
||||
@@ -523,3 +523,215 @@ fn setting_keys_are_their_json_values() {
|
||||
.unwrap();
|
||||
assert_eq!(serde_json::from_value::<cmd::webexport::WebSettings>(custom.to_json()).unwrap(), custom);
|
||||
}
|
||||
|
||||
fn optimize_to(s: &mut Session, p: Value) -> Value {
|
||||
run(s, "webExport.optimizeToFileSize", p)
|
||||
}
|
||||
|
||||
/// The size of the file the settings `p` write (the whole image, or slice `slice`).
|
||||
fn written(s: &mut Session, p: &Value) -> usize {
|
||||
run(s, "document.exportForWeb.preview", p.clone())["bytes"].as_u64().unwrap() as usize
|
||||
}
|
||||
|
||||
/// 20×20: 400 one-point squares of different colors (more than a palette holds).
|
||||
fn photo_like() -> Session {
|
||||
let mut s = session(20.0, 20.0);
|
||||
for i in 0..400 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
rect(&mut s, [x, y, 1.0, 1.0], &format!("#{:02x}{:02x}{:02x}", (i % 20) * 12, (i / 20) * 12, (i * 7) % 256));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_takes_the_highest_jpeg_quality_that_fits() {
|
||||
let mut s = many_colours();
|
||||
let start = json!({"format": "jpg", "quality": 90});
|
||||
let full = written(&mut s, &start);
|
||||
let k = (full * 3 / 4) as f64 / 1024.0;
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": k})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!(target, (k * 1024.0).floor() as usize);
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str(), r["images"].as_u64()), (Some(true), Some("jpg"), Some(1)), "{r}");
|
||||
let q = r["settings"]["quality"].as_u64().unwrap();
|
||||
assert!(q < 90, "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target, "{r}");
|
||||
// The size is the size of the file Save writes with the settings.
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert_eq!(one(&mut s, r["settings"].clone()).len(), bytes);
|
||||
// One quality step up is over the size.
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"quality": q + 1}))) > target);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
// The other settings stay.
|
||||
assert_eq!(r["settings"]["matte"], json!("white"));
|
||||
assert_eq!(r["settings"]["metadata"], json!("copyright"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_lowers_palette_colors() {
|
||||
let mut s = many_colours();
|
||||
for format in ["gif", "png8"] {
|
||||
let start = json!({"format": format, "dither": "none", "colors": 128});
|
||||
let full = written(&mut s, &start);
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (full * 3 / 4) as f64 / 1024.0})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str()), (Some(true), Some(format)), "{r}");
|
||||
let colors = r["settings"]["colors"].as_u64().unwrap();
|
||||
assert!(colors < 64, "{format}: {r}");
|
||||
assert_eq!((r["settings"]["lossy"].as_u64(), r["settings"]["dither"].as_str()), (Some(0), Some("none")), "{format}: {r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target && written(&mut s, &r["settings"]) == bytes, "{format}: {r}");
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"colors": colors + 1}))) > target, "{format}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_selects_gif_or_jpeg_by_content() {
|
||||
// Flat, opaque art: GIF, from a JPEG start.
|
||||
let mut flat = two_colours();
|
||||
let r = optimize_to(&mut flat, json!({"format": "jpg", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("gif"), Some(true)), "{r}");
|
||||
// More colors than a palette holds: JPEG, from a GIF start.
|
||||
let mut photo = photo_like();
|
||||
let r = optimize_to(&mut photo, json!({"format": "gif", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// Transparent pixels: GIF, which keeps them.
|
||||
let mut clear = session(40.0, 30.0);
|
||||
rect(&mut clear, [0.0, 0.0, 10.0, 10.0], "#000000");
|
||||
for (k, transparency, format) in [(100.0, true, "gif"), (100.0, false, "gif"), (0.01, true, "gif")] {
|
||||
let r = optimize_to(&mut clear, json!({"format": "jpg", "desiredK": k, "startWith": "auto", "transparency": transparency}));
|
||||
assert_eq!(r["format"].as_str(), Some(format), "{k} {transparency}: {r}");
|
||||
}
|
||||
// The current format stays without auto.
|
||||
let r = optimize_to(&mut photo, json!({"format": "png8", "desiredK": 100}));
|
||||
assert_eq!(r["format"].as_str(), Some("png8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_counts_the_colors_blended_over_the_matte() {
|
||||
// Three colors at 100 opacities: without transparency, 300 colors once blended over the matte.
|
||||
let mut s = session(20.0, 15.0);
|
||||
for i in 0..300 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
let id = rect(&mut s, [x, y, 1.0, 1.0], ["#000000", "#ff0000", "#0000ff"][i % 3]);
|
||||
run(&mut s, "transparency.set", json!({"ids": [id], "opacity": i / 3 + 1}));
|
||||
}
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 100, "startWith": "auto", "transparency": false, "antiAlias": "none"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// With transparency the pixels stay transparent: GIF.
|
||||
let r = optimize_to(&mut s, json!({"format": "jpg", "desiredK": 100, "startWith": "auto", "antiAlias": "none"}));
|
||||
assert_eq!(r["format"].as_str(), Some("gif"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_says_when_no_setting_fits() {
|
||||
let mut s = many_colours();
|
||||
for format in ["jpg", "gif", "png8"] {
|
||||
let start = json!({"format": format});
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": 0.01})));
|
||||
assert_eq!((r["targetBytes"].as_u64(), r["achieved"].as_bool(), r["format"].as_str()), (Some(10), Some(false), Some(format)), "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes > 10 && bytes <= written(&mut s, &start), "{format}: the smallest setting tried: {r}");
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
}
|
||||
// GIF tries lossy when 2 colors are over.
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 0.01}));
|
||||
assert_eq!(r["settings"]["lossy"], json!(100), "{r}");
|
||||
// PNG-24 has nothing to lower.
|
||||
let r = optimize_to(&mut s, json!({"format": "png24", "desiredK": 0.01}));
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(false), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&json!({"format": "png24"})).unwrap().to_json());
|
||||
// Settings that fit stay as they are.
|
||||
let p = json!({"format": "jpg", "quality": 80, "desiredK": 1000});
|
||||
let r = optimize_to(&mut s, p.clone());
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(true), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&p).unwrap().to_json());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_refuses_bad_params_and_changes_nothing() {
|
||||
let mut s = many_colours();
|
||||
run(&mut s, "webExport.settings", json!({"format": "jpg", "quality": 77}));
|
||||
let remembered = s.last_web_settings();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"desiredK": 0}),
|
||||
json!({"desiredK": -5}),
|
||||
json!({"desiredK": "10"}),
|
||||
json!({"desiredK": null}),
|
||||
json!({"desiredK": 2_000_000}),
|
||||
json!({"desiredK": 10, "startWith": "gif"}),
|
||||
json!({"desiredK": 10, "startWith": 1}),
|
||||
json!({"desiredK": 10, "use": "all"}),
|
||||
json!({"desiredK": 10, "slice": 0}),
|
||||
json!({"desiredK": 10, "slice": "1"}),
|
||||
json!({"desiredK": 10, "slice": 1, "use": "eachSlice"}),
|
||||
json!({"desiredK": 10, "slice": 99}),
|
||||
json!({"desiredK": 10, "percent": 0}),
|
||||
] {
|
||||
assert!(s.execute("webExport.optimizeToFileSize", &p).is_err(), "{p}");
|
||||
}
|
||||
optimize_to(&mut s, json!({"desiredK": 0.5, "format": "jpg"}));
|
||||
assert_eq!(s.last_web_settings(), remembered, "the search changes no remembered setting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_measures_the_slices_as_use_says() {
|
||||
let mut s = session(300.0, 200.0);
|
||||
rect(&mut s, [0.0, 0.0, 300.0, 200.0], "#336699");
|
||||
for i in 0..40 {
|
||||
rect(&mut s, [f64::from(i) * 7.0, f64::from(i) * 4.0, 30.0, 20.0], &format!("#{:02x}{:02x}40", i * 6, 255 - i * 6));
|
||||
}
|
||||
let a = rect(&mut s, [20.0, 20.0, 100.0, 60.0], "#ff8800");
|
||||
run(&mut s, "object.slice.make", json!({"ids": [a]}));
|
||||
let layout = run(&mut s, "slice.list", json!({}))["slices"].as_array().unwrap().clone();
|
||||
let start = json!({"format": "jpg", "quality": 95});
|
||||
let sizes = |s: &mut Session, p: &Value| files(&run(s, "document.exportForWeb", p.clone())).iter().map(|(_, b)| b.len()).collect::<Vec<_>>();
|
||||
let all = sizes(&mut s, &start);
|
||||
assert_eq!(all.len(), layout.len());
|
||||
let total: usize = all.iter().sum();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (total * 3 / 4) as f64 / 1024.0})));
|
||||
assert_eq!((r["achieved"].as_bool(), r["images"].as_u64()), (Some(true), Some(layout.len() as u64)), "{r}");
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(after.iter().sum::<usize>(), r["bytes"].as_u64().unwrap() as usize, "the slice files together");
|
||||
let largest = *all.iter().max().unwrap();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (largest * 3 / 4) as f64 / 1024.0, "use": "eachSlice"})));
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(*after.iter().max().unwrap(), r["bytes"].as_u64().unwrap() as usize, "the largest slice file");
|
||||
assert!(r["achieved"].as_bool().unwrap() && after.iter().all(|n| *n <= r["targetBytes"].as_u64().unwrap() as usize), "{r}");
|
||||
let n = layout[0]["number"].as_u64().unwrap();
|
||||
let one_slice = written(&mut s, &merge(&start, json!({"slice": n})));
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (one_slice / 2) as f64 / 1024.0, "slice": n})));
|
||||
assert_eq!(r["images"].as_u64(), Some(1));
|
||||
assert_eq!(written(&mut s, &merge(&r["settings"], json!({"slice": n}))), r["bytes"].as_u64().unwrap() as usize, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() {
|
||||
use cmd::webexport::{OPTIMIZE_SAMPLES, WebSettings, highest_within, set_quality};
|
||||
// Sizes that do not fall with the quality: 1 to 20 give 900 bytes, 21 to 70 give 400 to 449,
|
||||
// and 71 and up give over 1000.
|
||||
let size_of = |q: u8| match q {
|
||||
..=20 => 900,
|
||||
21..=70 => 400 + usize::from(q - 21),
|
||||
_ => 1000 + usize::from(q),
|
||||
};
|
||||
let start = WebSettings { quality: 90, ..WebSettings::default() };
|
||||
let mut measured = Vec::new();
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| {
|
||||
measured.push(s.quality);
|
||||
Ok(Some(size_of(s.quality)))
|
||||
};
|
||||
let found = highest_within(&mut size, &start, (1, 90), set_quality, 500, &mut smallest).unwrap();
|
||||
let (settings, bytes) = found.expect("a quality within 500 bytes");
|
||||
assert_eq!((settings.quality, bytes), (70, 449), "measured {measured:?}");
|
||||
assert!(measured.len() <= usize::from(OPTIMIZE_SAMPLES) + 7, "measured {measured:?}");
|
||||
// Nothing fits: the smallest size measured is kept.
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| Ok(Some(size_of(s.quality)));
|
||||
assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none());
|
||||
assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415)));
|
||||
}
|
||||
@@ -3827,6 +3827,83 @@ fn editing_text() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_meshes_never_panic`]'s cuts and edits: past the end of [`meshes_text`].
|
||||
const MESHES_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two gradient meshes: 2 × 3 patches whose
|
||||
/// rows of points are RGB, CMYK and gray, at half opacity and named; a 1 × 1 mesh with a point at
|
||||
/// 40% opacity; and an instance of a symbol whose art is a 2 × 1 mesh.
|
||||
fn meshes_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshPoint, grid_points, smooth_handles};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
let mesh = |r: Rect, rows: u32, cols: u32, color: &dyn Fn(usize) -> Color| {
|
||||
let pts = grid_points(r, rows, cols);
|
||||
let handles = smooth_handles(rows, cols, &pts);
|
||||
let width = cols as usize + 1;
|
||||
let points = pts
|
||||
.iter()
|
||||
.zip(handles)
|
||||
.enumerate()
|
||||
.map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width), opacity: 1.0, handles: h })
|
||||
.collect();
|
||||
GradientMesh { rows, cols, points }
|
||||
};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let sheet = mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, &|row| match row {
|
||||
0 => Color::rgb(1.0, 0.5, 0.0),
|
||||
1 => Color::cmyk(0.1, 0.6, 0.2, 0.05),
|
||||
_ => Color::gray(0.4),
|
||||
});
|
||||
let mut sheet = Node::new(doc.alloc_id(), NodeKind::Mesh(sheet));
|
||||
(sheet.name, sheet.opacity) = (Some("Sheet".into()), 0.5);
|
||||
doc.insert(Some(layer), usize::MAX, sheet).unwrap();
|
||||
let mut small = mesh(Rect::new(220.0, 20.0, 280.0, 80.0), 1, 1, &|row| Color::rgb(0.0, 0.3, 0.3 + 0.5 * row as f32));
|
||||
small.points[1].opacity = 0.4;
|
||||
let small = Node::new(doc.alloc_id(), NodeKind::Mesh(small));
|
||||
doc.insert(Some(layer), usize::MAX, small).unwrap();
|
||||
let patch = mesh(Rect::new(0.0, 0.0, 40.0, 30.0), 2, 1, &|row| Color::rgb(0.2 * row as f32, 0.6, 0.1));
|
||||
let patch = Node::new(doc.alloc_id(), NodeKind::Mesh(patch));
|
||||
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Patch".into(), art: std::sync::Arc::new(patch) });
|
||||
let instance =
|
||||
Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Patch".into(), xf: vectorcraft_geom::Affine::translate((20.0, 140.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_meshes_never_panic`] damages, as it is, opens with both meshes, the symbol
|
||||
/// with its mesh and its instance, and the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_meshes_fuzz_data_opens_as_meshes() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = meshes_text();
|
||||
assert!(text.chars().count() < MESHES_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI14_BeginSymbol", "%AI5_BeginLayer", "/Mesh X!", "%_[2 3] /Size X#", "%_/DeviceCMYK /CS X#", "/End X!", "/SymbolInstance :"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
let kinds: Vec<&str> = art
|
||||
.iter()
|
||||
.map(|n| match n.kind {
|
||||
NodeKind::Mesh(_) => "mesh",
|
||||
NodeKind::SymbolInstance { .. } => "instance",
|
||||
_ => "other",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds, ["mesh", "mesh", "instance"], "{warnings:?}");
|
||||
let patch = d.symbols.iter().find(|s| s.name == "Patch").map(|s| &s.art.kind);
|
||||
assert!(matches!(patch, Some(NodeKind::Mesh(_))), "{patch:?}");
|
||||
}
|
||||
|
||||
fn zstd(text: &str) -> Vec<u8> {
|
||||
ruzstd::encoding::compress_to_vec(text.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest)
|
||||
}
|
||||
@@ -4482,6 +4559,17 @@ proptest! {
|
||||
survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose gradient meshes, as the writer writes them, are damaged: the record's type,
|
||||
/// size, places, color spaces and corners on `%_` lines, its `/Mesh X!` and `/End X!`, and the
|
||||
/// mesh's transparency and name, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_meshes_never_panic(cut in 0usize..MESHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..MESHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '9', '-', '.', 'e', ' ', '\n', '[', ']', '(', ')', '/', '%', '_', 'X', '!', '#', 'N', 'P', 'E'])), 0..12)) {
|
||||
let text = mutate_text(meshes_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai meshes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai meshes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// The active artboard that a restored `.ai` opens on, read from damaged or hostile editing data.
|
||||
#[test]
|
||||
fn ai_active_artboard_never_panics(cut in 0usize..600, edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '/', ':', ';', ',', '%', '_'])), 0..12)) {
|
||||
@@ -5066,6 +5154,81 @@ proptest! {
|
||||
survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose blends, as the writer writes them, are damaged: the keys and spine on `%_`
|
||||
/// lines with their dictionaries, the drawn steps, the record's `XP` and its hex, and the
|
||||
/// blend's transparency, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_blends_never_panic(cut in 0usize..BLENDS_FUZZ_CHARS, edits in prop::collection::vec((0usize..BLENDS_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '8', '9', 'A', 'F', '-', '.', ' ', '\n', '(', ')', '/', ',', ';', '%', '_', 'u', 'U', 'K', 'S', 'X', 'P'])), 0..12)) {
|
||||
let text = mutate_text(blends_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai blends", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai blends, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_blends_never_panic`]'s cuts and edits: past the end of [`blends_text`].
|
||||
const BLENDS_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two blends: red to blue squares with
|
||||
/// three steps and no spine of its own, at half opacity; and three squares 25 pt apart on a spine
|
||||
/// edited on the canvas, aligned to the path.
|
||||
fn blends_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let square = |doc: &mut Document, x: f64, y: f64, c: Color| {
|
||||
Arc::new(Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)),
|
||||
Appearance::basic(Paint::solid(c), Paint::None, 0.0),
|
||||
))
|
||||
};
|
||||
let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0));
|
||||
let keys = vec![square(&mut doc, 20.0, 20.0, red), square(&mut doc, 120.0, 20.0, blue)];
|
||||
let mut fade = Node::new(
|
||||
doc.alloc_id(),
|
||||
NodeKind::Blend { children: keys, spec: Box::new(BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) },
|
||||
);
|
||||
fade.opacity = 0.5;
|
||||
doc.insert(Some(layer), usize::MAX, fade).unwrap();
|
||||
let keys = vec![square(&mut doc, 20.0, 80.0, red), square(&mut doc, 120.0, 80.0, blue), square(&mut doc, 170.0, 80.0, green)];
|
||||
let centers: Vec<Point> = [30.0, 130.0, 180.0].iter().map(|x| Point::new(*x, 90.0)).collect();
|
||||
let spec = BlendSpec {
|
||||
spacing: BlendSpacing::Distance(25.0),
|
||||
orientation: BlendOrientation::AlignToPath,
|
||||
spine: Some(PathData::single(SubPath::polyline(¢ers, false))),
|
||||
key_anchors: vec![0, 1, 2],
|
||||
..BlendSpec::default()
|
||||
};
|
||||
let path = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) });
|
||||
doc.insert(Some(layer), usize::MAX, path).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_blends_never_panic`] damages, as it is, opens with both blends live, and
|
||||
/// the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_blends_fuzz_data_opens_live() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = blends_text();
|
||||
assert!(text.chars().count() < BLENDS_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI5_BeginLayer", "%_(K) /String (ShapeBlendPathType) ,", "%_(S) /String (ShapeBlendPathType) ,", "1 0 92 XP", "1 0 116 XP"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
assert_eq!(art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect::<Vec<_>>(), [true, true], "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`].
|
||||
|
||||
@@ -1805,6 +1805,134 @@ fn linear_picks_show_and_snap_to_smart_guides() {
|
||||
assert_eq!(text(&s, id), "60.02 pt");
|
||||
}
|
||||
|
||||
/// A shape with a curve at each top corner, for the tests of where Linear picks land.
|
||||
const CURVED_TOP: &str = "M130 358 C185 358 230 315 230 260 L425 260 C490 260 541 305 541 358 L541 440 L130 440 Z";
|
||||
|
||||
/// Where the next Linear click lands (the last marker the overlays draw, and its size) and the
|
||||
/// labels shown, with the pointer at (`x`, `y`).
|
||||
fn linear_marker(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> (Option<(vectorcraft_geom::Point, f32)>, Vec<String>) {
|
||||
use vectorcraft_engine::tools::Overlay;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
|
||||
let o = s.overlays(view);
|
||||
let at = o.iter().filter_map(|o| if let Overlay::Anchor { p, size, .. } = o { Some((*p, *size)) } else { None }).next_back();
|
||||
let labels = o.iter().filter_map(|o| if let Overlay::Label { text, .. } = o { Some(text.clone()) } else { None }).collect();
|
||||
(at, labels)
|
||||
}
|
||||
|
||||
/// A plain click at (`x`, `y`): the pointer moves there, then presses and releases.
|
||||
fn linear_click(s: &mut Session, view: ViewInfo, x: f64, y: f64) {
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear picks land on the anchors and paths of the art with an "anchor" or "path" label, and on
|
||||
/// the ends and lines of dimensions already drawn, from as far as on the art's anchors: zoomed in,
|
||||
/// a dimension started a few pixels from the end of another starts exactly at that end.
|
||||
#[test]
|
||||
fn linear_picks_land_on_anchors_paths_and_drawn_dimensions() {
|
||||
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
|
||||
let mut s = session();
|
||||
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", plain).unwrap();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let hover = |s: &mut Session, view: ViewInfo, x: f64, y: f64| {
|
||||
let (at, labels) = linear_marker(s, view, x, y);
|
||||
(at.map(|(p, _)| p), labels)
|
||||
};
|
||||
// Beside the end of the curve: on the anchor, labeled.
|
||||
assert_eq!(hover(&mut s, plain, 231.0, 262.0), (Some(pt(230.0, 260.0)), vec!["anchor".to_string()]));
|
||||
// Beside the curve: on its closest point, labeled.
|
||||
let (at, labels) = hover(&mut s, plain, 200.0, 337.0);
|
||||
assert!(at.is_some_and(|q| q.distance(pt(200.0, 337.0)) < 6.0 && q != pt(200.0, 337.0)), "{at:?}");
|
||||
assert_eq!(labels, ["path"]);
|
||||
// A first dimension from the bottom of the curve to its top, placed above the art.
|
||||
linear_click(&mut s, plain, 130.0, 358.0);
|
||||
linear_click(&mut s, plain, 230.0, 260.0);
|
||||
linear_click(&mut s, plain, 180.0, 207.0);
|
||||
let first = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(130.0, 358.0), pt(230.0, 260.0)));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", zoomed).unwrap();
|
||||
// Zoomed in, 5.8 pixels from the end of its dimension line: on that end, marked as an anchor.
|
||||
assert_eq!(linear_marker(&mut s, zoomed, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec!["anchor".to_string()]));
|
||||
// 6.4 pixels beside its extension line: on the line.
|
||||
let (at, labels) = hover(&mut s, zoomed, 230.8, 230.0);
|
||||
assert!(at.is_some_and(|q| (q.x - 230.0).abs() < 1e-6 && (q.y - 230.0).abs() < 1e-6), "{at:?}");
|
||||
assert_eq!(labels, ["path"]);
|
||||
// The next dimension starts where the first one's line ends.
|
||||
linear_click(&mut s, zoomed, 230.6, 207.4);
|
||||
linear_click(&mut s, zoomed, 425.0, 260.0);
|
||||
linear_click(&mut s, zoomed, 330.0, 207.0);
|
||||
let second = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_ne!(second, first);
|
||||
let d = recipe(&s, second);
|
||||
assert!(near(d.a, pt(230.0, 207.0)) && near(d.b, pt(425.0, 260.0)), "{:?} {:?}", d.a, d.b);
|
||||
}
|
||||
|
||||
/// An anchor of the art that a dimension already measures takes a point picked beside it, not the
|
||||
/// end of the extension line a few points off it. A locked dimension pulls no point, and with
|
||||
/// Smart Guides and Snap to Point off no dimension pulls a point and no label shows. A press on
|
||||
/// the end of a dimension's line over a segment of the art that moves a few pixels before the
|
||||
/// release picks that end, as a press on an anchor does.
|
||||
#[test]
|
||||
fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
|
||||
let (plain, zoomed) = (ViewInfo::default(), ViewInfo { zoom: 8.0, ..ViewInfo::default() });
|
||||
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..zoomed };
|
||||
let mut s = session();
|
||||
run(&mut s, "path.create", json!({"d": CURVED_TOP}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", plain).unwrap();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
linear_click(&mut s, plain, 130.0, 358.0);
|
||||
linear_click(&mut s, plain, 230.0, 260.0);
|
||||
linear_click(&mut s, plain, 180.0, 207.0);
|
||||
let first = s.doc().unwrap().selection.objects[0].0;
|
||||
// Locked, the first dimension's line end does not pull a point 5.8 pixels away.
|
||||
run(&mut s, "object.lock", json!({}));
|
||||
let (at, _) = linear_marker(&mut s, zoomed, 230.6, 207.4);
|
||||
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)), "a locked dimension: {at:?}");
|
||||
run(&mut s, "object.unlockAll", json!({}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
// 2.5 pixels above the curve's top anchor and 1.5 pixels below the end of the extension line
|
||||
// that starts 4 points above it: on the anchor, linked to the art.
|
||||
assert_eq!(linear_marker(&mut s, plain, 230.0, 257.5), (Some((pt(230.0, 260.0), 10.0)), vec!["anchor".to_string()]));
|
||||
// Smart Guides and Snap to Point off: no pull to the dimension's line end, and no labels.
|
||||
let (at, labels) = linear_marker(&mut s, off, 230.6, 207.4);
|
||||
assert!(at.is_none_or(|(p, _)| p != pt(230.0, 207.0)) && labels.is_empty(), "{at:?} {labels:?}");
|
||||
let (at, labels) = linear_marker(&mut s, off, 230.1, 260.1);
|
||||
assert!(at.is_some_and(|(p, _)| p == pt(230.0, 260.0)) && labels.is_empty(), "{at:?} {labels:?}");
|
||||
// Snap to Point on and Smart Guides off: the line end takes the point, and no label shows.
|
||||
assert_eq!(linear_marker(&mut s, ViewInfo { snap_to_point: true, ..off }, 230.6, 207.4), (Some((pt(230.0, 207.0), 10.0)), vec![]));
|
||||
// A second dimension whose line lies on the bottom edge, from x 425 to x 541.
|
||||
linear_click(&mut s, plain, 425.0, 260.0);
|
||||
linear_click(&mut s, plain, 541.0, 358.0);
|
||||
linear_click(&mut s, plain, 480.0, 440.0);
|
||||
let second = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_ne!(second, first);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
// A press 1.4 pixels from its line's left end, on the bottom edge, moved 5 pixels: the end is
|
||||
// picked, and no dimension of the edge is dragged out.
|
||||
for (kind, x) in [(PointerKind::Move, 426.0), (PointerKind::Down, 426.0), (PointerKind::Drag, 431.0), (PointerKind::Up, 431.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, 441.0), plain).unwrap();
|
||||
}
|
||||
linear_click(&mut s, plain, 541.0, 440.0);
|
||||
linear_click(&mut s, plain, 480.0, 470.0);
|
||||
let third = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_ne!(third, second);
|
||||
let d = recipe(&s, third);
|
||||
assert!(near(d.a, pt(425.0, 440.0)) && near(d.b, pt(541.0, 440.0)), "{:?} {:?}", d.a, d.b);
|
||||
// A dimension of the left edge whose line lies 4 points off it, where its extension lines
|
||||
// start: zoomed in, the end of its line still takes a point 4.7 pixels away.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
linear_click(&mut s, plain, 130.0, 358.0);
|
||||
linear_click(&mut s, plain, 130.0, 440.0);
|
||||
linear_click(&mut s, plain, 126.0, 400.0);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
|
||||
}
|
||||
|
||||
/// The page content streams of exported PDF `v`, inflated.
|
||||
fn pdf_content(v: &Value) -> String {
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
|
||||
@@ -10,6 +10,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-eps = { workspace = true }
|
||||
craft-ps = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-color = { workspace = true }
|
||||
vectorcraft-doc = { workspace = true }
|
||||
|
||||
@@ -120,7 +120,9 @@
|
||||
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
|
||||
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
|
||||
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there,
|
||||
//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are
|
||||
//! in the canvas's space with y down.
|
||||
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
|
||||
//! group with live effects or linked to a graphic style is written as its drawn look (`u`, its
|
||||
//! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its
|
||||
@@ -147,6 +149,19 @@
|
||||
//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between
|
||||
//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end;
|
||||
//! any other graph, and a graph with art left out, as its art, with a warning.
|
||||
//! - Gradient meshes, as the reader reads them (`mesh.rs`): `/Mesh X!`, `2 /Version`, the grid's type
|
||||
//! and size, `/Data` (the reader passes over the version and `/Data`), and each patch's place, color
|
||||
//! space and four corners (color, opacity, point and handles) as `X#` entries on `%_` lines,
|
||||
//! `/End X!`; the mesh's transparency before it, its name and opacity mask after it
|
||||
//! (`writer::meshes`). A mesh is written as it is only when the reader reads it back so, when every
|
||||
//! patch turns the same way (a reflected mesh's columns are written in reverse order), and outside
|
||||
//! pattern tiles, art cut to a clipping object and a large canvas.
|
||||
//! - Blends, as the reader reads them (`blend.rs`): the blend's key objects and spine as a group on
|
||||
//! `%_` lines, each key's `/ArtDictionary` naming it a key and its id and the spine's naming it the
|
||||
//! spine (written when the blend has a spine of its own); its steps drawn, a group;
|
||||
//! the blend plugin's `1 0 n XP` line and the blend's record of its spacing, orientation and keys as hex
|
||||
//! on `%` lines; its name and transparency as a group's after its end (`writer::blends`). A blend is
|
||||
//! written live only when the reader reads it back with its settings.
|
||||
//!
|
||||
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
|
||||
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
|
||||
@@ -158,8 +173,9 @@
|
||||
//! art, the character and paragraph attributes the text document doesn't hold, freeform gradients, gradients
|
||||
//! along or across a stroke and gradients without stops, with more than 256 stops or without extent
|
||||
//! as their average color
|
||||
//! (gradients that dither or mix perceptually are written as classic ones, and gradient stops linked
|
||||
//! to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
|
||||
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
|
||||
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
|
||||
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
|
||||
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
|
||||
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
|
||||
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
|
||||
@@ -175,7 +191,10 @@
|
||||
//! and instances of
|
||||
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
|
||||
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
|
||||
//! guides, export types and dynamic type left out, live objects (placed documents included) as their art,
|
||||
//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as
|
||||
//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh
|
||||
//! on a large canvas as their drawn look, blends the reader wouldn't read back live as
|
||||
//! their steps, other live objects (placed documents included) as their art,
|
||||
//! strokes a plain line can't draw and the object's art style doesn't hold
|
||||
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
|
||||
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
|
||||
@@ -288,6 +307,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
let links = writer::style_links(doc);
|
||||
// Before baking, which leaves the wrap objects that may be written as they are unchanged.
|
||||
let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() };
|
||||
// The blends baking leaves as they are, which may be written live.
|
||||
let unbaked_blends = writer::unbaked_blends(doc);
|
||||
// Live geometry effects as their result, as the PDF part draws them.
|
||||
let baked = baked(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
@@ -318,6 +339,9 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
// On a large canvas the layers' symbol instances are written as their art.
|
||||
w.symbols_live = scale == 1.0;
|
||||
w.brushes_live = scale == 1.0;
|
||||
w.meshes_live = scale == 1.0;
|
||||
w.blends_live = scale == 1.0;
|
||||
w.unbaked_blends = unbaked_blends;
|
||||
w.symbol_doc = symbol_doc;
|
||||
w.max_objects = max_objects;
|
||||
w.wraps_held = wraps_held;
|
||||
|
||||
+1987
-45
File diff suppressed because it is too large.
Load diff
@@ -15,19 +15,26 @@ use vectorcraft_pathops::BoolOp;
|
||||
use crate::ai_ops::{self, unit};
|
||||
use crate::ps;
|
||||
|
||||
mod blends;
|
||||
mod brushes;
|
||||
mod envelopes;
|
||||
mod images;
|
||||
mod meshes;
|
||||
mod paints;
|
||||
mod styles;
|
||||
mod symbols;
|
||||
mod texts;
|
||||
mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) use blends::BLENDS;
|
||||
pub(super) use blends::unbaked_blends;
|
||||
#[cfg(test)]
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
#[cfg(test)]
|
||||
pub(super) use meshes::MESHES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
@@ -37,7 +44,9 @@ pub(super) use images::PAYLOAD;
|
||||
#[cfg(test)]
|
||||
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
|
||||
#[cfg(test)]
|
||||
pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name};
|
||||
pub(super) use paints::{
|
||||
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
#[cfg(test)]
|
||||
@@ -56,7 +65,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
@@ -302,6 +311,9 @@ pub(super) struct Writer<'a> {
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
pub(super) brushes_live: bool,
|
||||
/// Gradient meshes may be written as meshes; false on a large canvas, where they are written as
|
||||
/// their drawn look.
|
||||
pub(super) meshes_live: bool,
|
||||
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
|
||||
/// ([`Self::envelope`]).
|
||||
deform: bool,
|
||||
@@ -326,6 +338,14 @@ pub(super) struct Writer<'a> {
|
||||
series_tag: Option<String>,
|
||||
/// Where the `Go` lines of the graph being written start in [`Self::body`].
|
||||
graph_tags: Vec<usize>,
|
||||
/// Blends may be written live; false on a large canvas, where they are written as their steps.
|
||||
pub(super) blends_live: bool,
|
||||
/// How many more objects the reader's blends may lay out ([`crate::import::BLEND_BUDGET`]).
|
||||
blend_budget: usize,
|
||||
/// The entries naming a blend's key object in its dictionary, and the key's id.
|
||||
blend_role: Option<(NodeId, String)>,
|
||||
/// The blends baking left as they are ([`blends::unbaked_blends`]); only these are written live.
|
||||
pub(super) unbaked_blends: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -393,6 +413,7 @@ impl<'a> Writer<'a> {
|
||||
wrap_moved: false,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
meshes_live: true,
|
||||
deform: false,
|
||||
checks_left: crate::import::ENVELOPE_CHECKS,
|
||||
objects: 0,
|
||||
@@ -408,6 +429,10 @@ impl<'a> Writer<'a> {
|
||||
in_graph: false,
|
||||
series_tag: None,
|
||||
graph_tags: vec![],
|
||||
blends_live: true,
|
||||
blend_budget: crate::import::BLEND_BUDGET,
|
||||
blend_role: None,
|
||||
unbaked_blends: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -721,6 +746,11 @@ impl<'a> Writer<'a> {
|
||||
return self.styled_object(n, &orig, &name);
|
||||
}
|
||||
self.effects(n);
|
||||
// A gradient mesh the reader reads as it is; else it is written as its drawn look.
|
||||
let mut mesh = match &n.kind {
|
||||
NodeKind::Mesh(m) => self.mesh_record(m),
|
||||
_ => None,
|
||||
};
|
||||
self.state(n.locked, !n.visible);
|
||||
let mut xy = Xy::of(n);
|
||||
if masked_warp_pieces(n) {
|
||||
@@ -736,6 +766,11 @@ impl<'a> Writer<'a> {
|
||||
let charged = self.charges();
|
||||
match &n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Mesh(_) if mesh.is_some() => {
|
||||
if let Some(record) = mesh.take() {
|
||||
self.write_mesh(&record, xy);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => self.clip_group(children, xy),
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
if self.open_group("u") {
|
||||
@@ -838,7 +873,10 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
|
||||
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
|
||||
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
NodeKind::Mesh(_) => self.drawn_art(n, xy, Some(meshes::MESHES), true),
|
||||
NodeKind::Blend { .. } if self.blend(n, xy) => {}
|
||||
NodeKind::Blend { .. } => self.drawn_art(n, xy, Some(blends::BLENDS), true),
|
||||
NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
self.drawn_art(n, xy, Some(LIVE), true);
|
||||
}
|
||||
// Ruler guides are kept in the document's native copy only.
|
||||
@@ -917,7 +955,8 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
if self.nest < MAX_NEST {
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
@@ -953,9 +992,10 @@ impl<'a> Writer<'a> {
|
||||
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
|
||||
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
|
||||
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]). False when `n` has an opacity mask that is left out: nested too
|
||||
/// deep, or its art doesn't fit.
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]), or is a blend's key object (its part and id after the name, see
|
||||
/// [`blends`]). False when `n` has an opacity mask that is left out: nested too deep, or its art
|
||||
/// doesn't fit.
|
||||
fn dictionary(&mut self, n: &Node) -> bool {
|
||||
let name = n.name.as_deref().filter(|s| !s.is_empty());
|
||||
let moved = std::mem::take(&mut self.wrap_moved);
|
||||
@@ -975,7 +1015,11 @@ impl<'a> Writer<'a> {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() {
|
||||
let role = match &self.blend_role {
|
||||
Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() && role.is_none() {
|
||||
return mask_written;
|
||||
}
|
||||
let start = self.body.len();
|
||||
@@ -996,6 +1040,10 @@ impl<'a> Writer<'a> {
|
||||
self.bound.push((n.id, id, bound));
|
||||
}
|
||||
}
|
||||
let has_role = role.is_some();
|
||||
if let Some(r) = role {
|
||||
self.body.push_str(&r);
|
||||
}
|
||||
if let Some(w) = wrap {
|
||||
self.text_wrap(w);
|
||||
}
|
||||
@@ -1003,7 +1051,7 @@ impl<'a> Writer<'a> {
|
||||
if let Some(m) = mask
|
||||
&& !self.mask(m)
|
||||
{
|
||||
if !has_id && !has_entries && wrap.is_none() {
|
||||
if !has_id && !has_entries && wrap.is_none() && !has_role {
|
||||
self.body.truncate(start);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Blends: a live blend as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, `blend.rs`
|
||||
//! and `read/containers.rs`' `end_blend`).
|
||||
//!
|
||||
//! The blend's own art on `%_` lines: `0 Ae`, a group of its key objects, each with an
|
||||
//! `/ArtDictionary` naming it a key (`ShapeBlendPathType` `K`) and its id (`ShapeBlendPathID`, a
|
||||
//! letter or digit), and its spine as an unpainted path named the spine (`S`), written only when the
|
||||
//! blend has a spine of its own; then its steps drawn, a group on plain lines; then `0 Ae`,
|
||||
//! the `XP` line of the blend plugin ([`BLEND_PLUGIN`], `1 0 n XP`) and the blend's record, `n` bytes
|
||||
//! as hex on `%` lines; then the blend's name in an `/ArtDictionary` and its transparency, as a
|
||||
//! group's after its end. The record
|
||||
//! is `DCBA` and little-endian 32-bit words: 1, the spacing (0 Smooth Color, 1 Specified Steps, 2
|
||||
//! Specified Distance); 2, the distance as a float (Specified Steps: the spine's length shared out
|
||||
//! between the steps; Smooth Color: 4); 4, the steps between the first two keys; 5, the orientation
|
||||
//! (0 Align to Page, a float of 8 and the spine's starting angle in radians for Align to Path); 6,
|
||||
//! the next free id (0 after the 62nd); 9, 1; 10, the number of keys; then six words a key: its id,
|
||||
//! 0, the anchor of the spine it sits on as a float, two words of all ones, and the steps between
|
||||
//! it and the key before it. The reader reads words 1, 2 (for Specified Distance), 5 (0, or 8 or
|
||||
//! more), 10 and the keys' ids; the others are written as the record's form has them.
|
||||
//!
|
||||
//! Each blend is checked with the reader's own reading ([`crate::import::blend_reads`]) before it is
|
||||
//! written: one the reader would read with other settings is written as its steps.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_spine, blend_steps, blend_steps_settled, pin_spine};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy, hide};
|
||||
use crate::import::{BLEND_PLUGIN, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, blend_reads};
|
||||
|
||||
pub(in crate::ai_editing) const BLENDS: &str = "blends with easing, a color shift or start points of their own, blends with effects, an appearance or an opacity mask of their own, blends of objects other than paths, compound paths and groups, of clipping groups, of more than 62 key objects, of hidden key objects, of key objects that hold a blend, of key objects with geometry or Pathfinder effects or a group's own fills and strokes, or of key objects the editing copy would change (empty paths or subpaths, paths and compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with transparency or effects of their own, effects or opacity masks), blends where one key object has a fill or stroke of no paint or a stroke of no width and another has one that draws, blends inside objects with geometry or Pathfinder effects or a group's own fills and strokes, blends whose spine has more than one part, blends whose step count is close to where rounding changes it, blends that would open with other settings or not as they are drawn, blends in opacity masks, pattern tiles, symbols and art cut to a clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live objects, brushed strokes), blends whose art would pass the most objects the reader reads, and every blend on a large canvas are written as their steps in the editing data for other apps";
|
||||
|
||||
/// How far (pt) the lengths a blend counts its steps from may move when written (coordinates are
|
||||
/// written to 4 decimals and read back through art space) without changing a count.
|
||||
const SETTLE_LENGTH: f64 = 0.01;
|
||||
/// How far (pt) each segment of a spine may add to [`SETTLE_LENGTH`]: rounding moves each of its
|
||||
/// points by up to 0.00005 √2 pt, which moves the segment's length by up to six times that.
|
||||
const SETTLE_SEGMENT: f64 = 5e-4;
|
||||
/// How far a key's color (each channel, 0 to 1) may move when written without changing a Smooth
|
||||
/// Color count.
|
||||
const SETTLE_COLOR: f64 = 0.001;
|
||||
|
||||
/// The most dash lengths the reader reads; a stroke with more opens solid.
|
||||
const MAX_DASH_LENGTHS: usize = 64;
|
||||
|
||||
/// The ids the keys take, in their order (letters and digits, as the reader reads them).
|
||||
const IDS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
/// Hex digits on one `%` line of a record.
|
||||
const HEX_LINE: usize = 60;
|
||||
|
||||
/// A blend to write live.
|
||||
pub(super) struct LiveBlend {
|
||||
keys: Vec<Arc<Node>>,
|
||||
ids: Vec<String>,
|
||||
/// Its spine part; `None`: the blend has no spine of its own.
|
||||
spine: Option<PathData>,
|
||||
record: Vec<u8>,
|
||||
steps: Vec<Arc<Node>>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Blend `n` as the reader reads it live, or `None` when it would read other settings or none
|
||||
/// (the blend is then written as its steps).
|
||||
pub(super) fn live_blend(&mut self, n: &Node) -> Option<LiveBlend> {
|
||||
let NodeKind::Blend { children: keys, spec } = &n.kind else { return None };
|
||||
// Hidden lines (pattern tiles, opacity masks), symbols' definitions and art cut to a
|
||||
// clipping object aren't read as live blends. (No blend is drawn in a look: styled objects
|
||||
// hold only paths, compound paths and groups of them.)
|
||||
if !self.blends_live || self.hidden > 0 || self.in_symbol || self.clip.is_some() || self.nest >= MAX_NEST {
|
||||
return None;
|
||||
}
|
||||
// Baking changes its keys, or the art it sits in ([`unbaked_blends`]).
|
||||
if !self.unbaked_blends.contains(&n.id) {
|
||||
return None;
|
||||
}
|
||||
if !spec.ease.is_default() || spec.color_shift != 0.0 || !spec.starts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let own = &n.appearance;
|
||||
if !own.items.is_empty() || !own.effects.is_empty() || n.extras().mask.is_some() {
|
||||
return None;
|
||||
}
|
||||
// The reader shows every key object it reads.
|
||||
if keys.len() < 2 || keys.len() > IDS.len().min(MAX_BLEND_KEYS) || !keys.iter().all(|k| k.visible && plain_key(k)) {
|
||||
return None;
|
||||
}
|
||||
// A fill or stroke the editing copy leaves out is read back as none at all, and the steps
|
||||
// blend from it to another key's otherwise.
|
||||
if left_out_against_drawn(keys) {
|
||||
return None;
|
||||
}
|
||||
// The spine written: a replaced spine (no key anchors) with an anchor where each key sits, a
|
||||
// spine edited on the canvas with its keys' anchors moved onto them.
|
||||
let spec: &BlendSpec = spec;
|
||||
// The blend lays out along the spine's first subpath, and only that part is written: a
|
||||
// spine of more parts would open without the others.
|
||||
if spec.spine.as_ref().is_some_and(|s| s.subpaths.len() > 1) {
|
||||
return None;
|
||||
}
|
||||
let written = match &spec.spine {
|
||||
None => BlendSpec { key_anchors: vec![], ..spec.clone() },
|
||||
Some(_) if spec.key_anchors.is_empty() => {
|
||||
let (path, anchors) = pin_spine(keys, spec)?;
|
||||
let anchors = anchors.into_iter().map(u32::try_from).collect::<Result<Vec<u32>, _>>().ok()?;
|
||||
BlendSpec { spine: Some(path), key_anchors: anchors, ..spec.clone() }
|
||||
}
|
||||
Some(_) => BlendSpec { spine: Some(blend_spine(keys, spec)?.0), ..spec.clone() },
|
||||
};
|
||||
// The record holds Specified Distance as a 32-bit float, which the reader reads back as its
|
||||
// shortest decimal (10 mm comes back as 28.346457 pt): the blend is compared with that
|
||||
// distance, and kept live only when it lays out as many steps with it.
|
||||
let written = match written.spacing {
|
||||
BlendSpacing::Distance(d) => {
|
||||
let read: f64 = (d as f32).to_string().parse().ok().filter(|r: &f64| r.is_finite() && *r > 0.0)?;
|
||||
let stored = BlendSpec { spacing: BlendSpacing::Distance(read), ..written.clone() };
|
||||
if blend_steps(keys, &stored) != blend_steps(keys, &written) {
|
||||
return None;
|
||||
}
|
||||
stored
|
||||
}
|
||||
_ => written,
|
||||
};
|
||||
// As many objects as the reader lays out for one blend, twice within what its budget has left,
|
||||
// counted before the steps are drawn.
|
||||
let objects = blend_steps(keys, &written).into_iter().fold(keys.len(), usize::saturating_add);
|
||||
if objects > MAX_BLEND_OBJECTS || objects.saturating_mul(2) > self.blend_budget {
|
||||
return None;
|
||||
}
|
||||
// The reader counts the steps from the keys as written, rounded: a count that rounding can
|
||||
// change may come back other than drawn. Specified Distance counts from the spine's length,
|
||||
// and every segment of the spine adds to how far that may move.
|
||||
let segments = written.spine.as_ref().and_then(|s| s.subpaths.first()).map_or(0, |s| s.segment_count());
|
||||
let settle = match written.spacing {
|
||||
BlendSpacing::Distance(_) => SETTLE_LENGTH + segments as f64 * SETTLE_SEGMENT,
|
||||
_ => SETTLE_LENGTH,
|
||||
};
|
||||
if !blend_steps_settled(keys, &written, settle, SETTLE_COLOR) {
|
||||
return None;
|
||||
}
|
||||
let ids: Vec<String> = IDS.iter().take(keys.len()).map(|c| char::from(*c).to_string()).collect();
|
||||
let record = self.record(keys, &written)?;
|
||||
let steps: Vec<Arc<Node>> = vectorcraft_effects::expand_live_deep(Some(self.doc), n).children().cloned().unwrap_or_default();
|
||||
let drawn: Vec<Node> = steps.iter().map(|s| (**s).clone()).collect();
|
||||
// The spine part as written: the first subpath of the spine laid out.
|
||||
let part = written.spine.as_ref().and_then(|s| s.subpaths.first()).map(|sp| PathData::single(sp.clone()));
|
||||
let mut budget = self.blend_budget;
|
||||
let read = blend_reads(keys, &ids, part.as_ref(), &record, &drawn, &mut budget)?;
|
||||
if read != written {
|
||||
return None;
|
||||
}
|
||||
self.blend_budget = budget;
|
||||
Some(LiveBlend { keys: keys.clone(), ids, spine: part, record, steps })
|
||||
}
|
||||
|
||||
/// The record of a blend of `keys` with the settings `spec` (its spine as written).
|
||||
fn record(&self, keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Vec<u8>> {
|
||||
let (spine, anchors) = blend_spine(keys, spec)?;
|
||||
let steps = blend_steps(keys, spec);
|
||||
let first = u32::try_from(*steps.first()?).ok()?;
|
||||
let (spacing, value) = match spec.spacing {
|
||||
BlendSpacing::SmoothColor => (0, 4.0),
|
||||
BlendSpacing::Steps(n) => (1, spine.length() / (f64::from(n) + 1.0)),
|
||||
BlendSpacing::Distance(d) => (2, d),
|
||||
};
|
||||
let orientation = match spec.orientation {
|
||||
BlendOrientation::AlignToPage => 0.0,
|
||||
BlendOrientation::AlignToPath => 8.0 + self.starting_angle(&spine)?,
|
||||
};
|
||||
let count = u32::try_from(keys.len()).ok()?;
|
||||
let next = IDS.get(keys.len()).copied().map_or(0, u32::from);
|
||||
let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), spacing, (value as f32).to_bits(), 0, first, (orientation as f32).to_bits()];
|
||||
words.extend([next, 0, 0, 1, count]);
|
||||
for (i, id) in IDS.iter().take(keys.len()).enumerate() {
|
||||
let anchor = anchors.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(i);
|
||||
let before = i.checked_sub(1).and_then(|j| steps.get(j)).copied().unwrap_or(0);
|
||||
words.extend([u32::from(*id), 0, (anchor as f32).to_bits(), u32::MAX, u32::MAX, u32::try_from(before).ok()?]);
|
||||
}
|
||||
Some(words.iter().flat_map(|w| w.to_le_bytes()).collect())
|
||||
}
|
||||
|
||||
/// The angle in art space (radians, from 0 to 2π) at which `spine` starts.
|
||||
fn starting_angle(&self, spine: &PathData) -> Option<f64> {
|
||||
let sp = spine.subpaths.first()?;
|
||||
let first = sp.anchors.first()?;
|
||||
let towards = if (first.h_out - first.p).hypot() > 1e-9 { first.h_out } else { sp.anchors.get(1)?.p };
|
||||
let (a, b) = (self.to_art * first.p, self.to_art * towards);
|
||||
let angle = (b.y - a.y).atan2(b.x - a.x);
|
||||
Some(if angle < 0.0 { angle + std::f64::consts::TAU } else { angle })
|
||||
}
|
||||
|
||||
/// Blend `n`, of transparency `xy`, written live ([`Self::live_blend`]): its own art on `%_`
|
||||
/// lines, its steps and its record, then the state block of its transparency, before which the
|
||||
/// object's dictionary (its name, text wrap options and variables) goes. False, writing
|
||||
/// nothing, when it is written as its steps: the reader would read it otherwise, or art in it
|
||||
/// would be left out at the object limit ([`Self::take_objects`]).
|
||||
pub(super) fn blend(&mut self, n: &Node, xy: Xy) -> bool {
|
||||
let budget = self.blend_budget;
|
||||
let Some(b) = self.live_blend(n) else { return false };
|
||||
let start = self.body.len();
|
||||
let (state, gs, charges, bound, warnings) = (self.state, self.gs, self.charges(), self.bound.len(), self.warnings.len());
|
||||
let outer = std::mem::take(&mut self.body);
|
||||
self.hidden += 1;
|
||||
self.line("0 Ae");
|
||||
let opened = self.open_group("u");
|
||||
if opened {
|
||||
for (k, id) in b.keys.iter().zip(&b.ids) {
|
||||
self.blend_role = Some((k.id, format!("%_(K) /String (ShapeBlendPathType) ,\n%_({id}) /String (ShapeBlendPathID) ,\n")));
|
||||
self.node(k);
|
||||
self.blend_role = None;
|
||||
}
|
||||
if let Some(spine) = &b.spine {
|
||||
self.plain_object(spine, FillRule::NonZero, None, None, Xy::OPAQUE);
|
||||
self.body.push_str("%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n%_\n");
|
||||
}
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
self.hidden -= 1;
|
||||
let part = std::mem::replace(&mut self.body, outer);
|
||||
hide(&part, &mut self.body);
|
||||
// Readers of the printed form skip the hidden lines: the steps set their own state.
|
||||
(self.state, self.gs) = (None, None);
|
||||
self.state(n.locked, !n.visible);
|
||||
let steps = self.open_group("u");
|
||||
if steps {
|
||||
// The steps are drawn art: copies of the keys carry no text wrap options of their own.
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for s in &b.steps {
|
||||
self.node(s);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
self.state(n.locked, !n.visible);
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
if !opened || !steps || self.left_out_since(charges) {
|
||||
let lines = self.body.split_off(start);
|
||||
self.give_back(charges, &lines);
|
||||
self.bound.truncate(bound);
|
||||
// The warnings of art written as its steps again are those steps'.
|
||||
if !self.left_out_since(charges) {
|
||||
self.warnings.truncate(warnings);
|
||||
}
|
||||
(self.state, self.gs, self.block_end, self.blend_budget) = (state, gs, usize::MAX, budget);
|
||||
return false;
|
||||
}
|
||||
self.line("0 Ae");
|
||||
let hex: String = b.record.iter().map(|x| format!("{x:02X}")).collect();
|
||||
let _ = writeln!(self.body, "({BLEND_PLUGIN}) 1 0 {} XP", b.record.len());
|
||||
for chunk in hex.as_bytes().chunks(HEX_LINE) {
|
||||
self.body.push('%');
|
||||
self.body.push_str(&String::from_utf8_lossy(chunk));
|
||||
self.body.push('\n');
|
||||
}
|
||||
// The blend's dictionary goes after the record and before this block ([`Self::node`]).
|
||||
self.state_block(xy);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The blends on `doc`'s layers that baking leaves as they are: blends with nothing in them that
|
||||
/// [`vectorcraft_effects::needs_bake`] evaluates (geometry and Pathfinder effects, a group's own
|
||||
/// fills and strokes), inside no object that has such things of its own. Baking changes the keys
|
||||
/// of the others, so they are written as their steps.
|
||||
pub(in crate::ai_editing) fn unbaked_blends(doc: &Document) -> HashSet<NodeId> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut HashSet<NodeId>) {
|
||||
for n in nodes {
|
||||
if matches!(n.kind, NodeKind::Blend { .. }) {
|
||||
if !vectorcraft_effects::needs_bake(n) {
|
||||
out.insert(n.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(children) = n.children() else { continue };
|
||||
let mut own = (**n).clone();
|
||||
if let Some(c) = own.children_mut() {
|
||||
c.clear();
|
||||
}
|
||||
if !vectorcraft_effects::needs_bake(&own) {
|
||||
walk(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
walk(&doc.layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the reader read stroke `s`'s dashes back as they are (`read/ops.rs`' `d`): at most 64
|
||||
/// lengths, each finite and not negative, and a finite offset? It reads other dashes as a solid
|
||||
/// line.
|
||||
fn dash_read_back(s: &StrokeLayer) -> bool {
|
||||
s.dash
|
||||
.as_ref()
|
||||
.is_none_or(|d| d.pattern.len() <= MAX_DASH_LENGTHS && d.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && d.offset.is_finite())
|
||||
}
|
||||
|
||||
/// Do the keys hold a fill or stroke that the editing copy leaves out (a fill of no paint; a stroke
|
||||
/// of no paint or of no width, as `visible_items` leaves them out) where another holds one of the
|
||||
/// same kind that it writes? The steps blend the width, paint and settings of the one left out, and
|
||||
/// the keys read back blend from no fill or stroke, so the steps would open otherwise.
|
||||
fn left_out_against_drawn(keys: &[Arc<Node>]) -> bool {
|
||||
// [fill, stroke]: is one left out somewhere, is one written somewhere.
|
||||
let mut left_out = [false; 2];
|
||||
let mut drawn = [false; 2];
|
||||
for k in keys {
|
||||
k.walk(&mut |n| {
|
||||
for i in &n.appearance.items {
|
||||
let (kind, out) = match i {
|
||||
AppearanceItem::Fill(f) => (0, f.paint.is_none()),
|
||||
AppearanceItem::Stroke(s) => (1, s.paint.is_none() || !(s.width > 0.0 && s.width.is_finite())),
|
||||
};
|
||||
if out {
|
||||
left_out[kind] = true;
|
||||
} else {
|
||||
drawn[kind] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
(left_out[0] && drawn[0]) || (left_out[1] && drawn[1])
|
||||
}
|
||||
|
||||
/// Can `k` be a key object written live, as the reader reads it back: paths, compound paths and
|
||||
/// groups other than clipping groups (holding no blend), without effects or opacity masks, each with
|
||||
/// at most one fill and one plain stroke over it (a line the data draws as it is), each fill and
|
||||
/// stroke shown, in a color other than Lab or none, opaque in the normal blending mode? (A group's own fills and
|
||||
/// strokes are baked into art of their own, and such blends aren't [`unbaked_blends`].)
|
||||
fn plain_key(k: &Node) -> bool {
|
||||
let mut plain = true;
|
||||
k.walk(&mut |n| {
|
||||
// A clipping group may be written as its art cut to the clipping object.
|
||||
let kind = match &n.kind {
|
||||
// The writer leaves out a path with nothing to draw and subpaths without anchors, and
|
||||
// writes a path of several subpaths as a compound path.
|
||||
NodeKind::Path { path, guide: false, .. } => matches!(path.subpaths.as_slice(), [one] if !one.anchors.is_empty()),
|
||||
// A compound path is written as one path, and read back with a member for each
|
||||
// subpath.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
!children.is_empty()
|
||||
&& children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1))
|
||||
}
|
||||
NodeKind::Group { clip: false, .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
let items = &n.appearance.items;
|
||||
let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count();
|
||||
let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]);
|
||||
let quiet = items.iter().all(|i| {
|
||||
i.visible()
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
// A color that names no global or spot swatch is written in RGB, so a Lab color
|
||||
// would come back as another.
|
||||
&& !matches!(i.paint(), Paint::Solid { color: Color::Lab { .. }, .. })
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
plain
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use super::{Writer, Xy};
|
||||
use crate::ai_ops;
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art or its opacity masks' art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, or opacity masks on a compound path's members or more than seven deep in one another's art, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
|
||||
/// Most brushes written (the reader's limit).
|
||||
const MAX_BRUSHES: usize = 4096;
|
||||
@@ -213,17 +213,38 @@ fn art_params(a: &ArtBrush, art: &str) -> Option<String> {
|
||||
Some(format!("2 / {art}/ / / / / 0 0/ 5 0 0 0 / {}", nums6(&numbers)))
|
||||
}
|
||||
|
||||
/// Most opacity masks in one another's art in a brush's art: a brush's art section writes its art
|
||||
/// one level inside, and masks at [`super::MAX_NEST`] levels are left out ([`super::DEEP_MASKS`]).
|
||||
const MAX_MASK_NEST: u32 = super::MAX_NEST - 1;
|
||||
|
||||
/// Is `art` written as the reader reads it back, within a brush: paths and compound paths with
|
||||
/// points and groups with members (not clipping, without paint of their own), each opaque in the
|
||||
/// normal blending mode, without effects or opacity masks, with at most one fill and one plain
|
||||
/// stroke (no brush, width profile, arrowheads, alignment off the path or dashes fitted to corners)
|
||||
/// over it, each in a color or none? A path without points isn't written ([`Writer::plain_object`]).
|
||||
/// normal blending mode, without effects, with at most one fill and one plain stroke (no brush,
|
||||
/// width profile, arrowheads, alignment off the path or dashes fitted to corners) over it, each in a
|
||||
/// color or none, and opacity masks whose art is such art too, at most [`MAX_MASK_NEST`] deep and
|
||||
/// none on a compound path's members? A path without points isn't written
|
||||
/// ([`Writer::plain_object`]).
|
||||
fn plain_art(art: &Node) -> bool {
|
||||
plain_within(art, MAX_MASK_NEST)
|
||||
}
|
||||
|
||||
/// Does no object of `art` have an opacity mask?
|
||||
fn unmasked(art: &Node) -> bool {
|
||||
let mut unmasked = true;
|
||||
art.walk(&mut |n| unmasked &= n.extras().mask.is_none());
|
||||
unmasked
|
||||
}
|
||||
|
||||
/// [`plain_art`] with at most `masks` opacity masks in one another's art.
|
||||
fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
let mut plain = true;
|
||||
art.walk(&mut |n| {
|
||||
let kind = match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => path.subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
NodeKind::Compound { .. } => super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
// A compound path is written as one path of its members' subpaths, without their masks.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
children.iter().all(|c| unmasked(c)) && super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty())
|
||||
}
|
||||
NodeKind::Group { children, clip: false } => !children.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
@@ -247,7 +268,7 @@ fn plain_art(art: &Node) -> bool {
|
||||
&& order
|
||||
&& quiet
|
||||
&& n.appearance.effects.is_empty()
|
||||
&& n.extras().mask.is_none()
|
||||
&& n.extras().mask.as_deref().is_none_or(|m| masks > 0 && plain_within(&m.art, masks - 1))
|
||||
&& n.opacity >= 1.0
|
||||
&& n.blend == BlendMode::Normal;
|
||||
});
|
||||
@@ -258,8 +279,13 @@ fn plain_art(art: &Node) -> bool {
|
||||
/// compound path with the subpaths of all its members as one path ([`super::compound_path`]), is
|
||||
/// written as one path when it has one subpath with points and as a compound path when it has more
|
||||
/// ([`Writer::plain_object`]); the reader reads that compound path as one path for each subpath,
|
||||
/// each with the object's paint.
|
||||
/// each with the object's paint. An opacity mask's art is written shown ([`Writer::mask`]).
|
||||
fn as_read(art: &mut Node) {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
let mask_art = Arc::make_mut(&mut m.art);
|
||||
mask_art.visible = true;
|
||||
as_read(mask_art);
|
||||
}
|
||||
let (subpaths, rule) = match &art.kind {
|
||||
NodeKind::Path { path, rule, .. } => (path.subpaths.clone(), *rule),
|
||||
NodeKind::Compound { rule, .. } => (super::compound_path(art).subpaths, *rule),
|
||||
@@ -390,7 +416,7 @@ impl Writer<'_> {
|
||||
}
|
||||
let mut read = a.clone();
|
||||
if *to_section == Affine::IDENTITY {
|
||||
read.transform(Affine::FLIP_Y, false);
|
||||
crate::import::turn_brush_art_over(&mut read);
|
||||
}
|
||||
as_read(&mut read);
|
||||
Some(read)
|
||||
@@ -427,6 +453,9 @@ impl Writer<'_> {
|
||||
// The art is the brush's own: not on `%_` lines, in a drawn look or in a symbol that
|
||||
// first uses the brush.
|
||||
(std::mem::take(&mut self.hidden), std::mem::take(&mut self.in_look), std::mem::take(&mut self.in_symbol)),
|
||||
// The layers' objects written with art styles, by id: none of them is the brush's art,
|
||||
// which may hold objects with the same ids.
|
||||
std::mem::take(&mut self.styled),
|
||||
);
|
||||
(self.to_art, self.grad_space, self.canvas, self.block_end) = (to_section, to_section, to_section, usize::MAX);
|
||||
self.state(false, false);
|
||||
@@ -462,6 +491,7 @@ impl Writer<'_> {
|
||||
(self.clip, self.shown),
|
||||
(self.block_start, self.block_end),
|
||||
(self.hidden, self.in_look, self.in_symbol),
|
||||
self.styled,
|
||||
) = saved;
|
||||
let text = std::mem::replace(&mut self.body, body);
|
||||
if !std::mem::replace(&mut self.warnings, warnings).is_empty() {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
|
||||
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
|
||||
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! contents in an `X=` … `X+` block (in a symbol's art, in the canvas's space with y down; while
|
||||
//! they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side
|
||||
@@ -401,7 +402,13 @@ impl Writer<'_> {
|
||||
if *editing {
|
||||
self.grid(record.grid.as_ref());
|
||||
} else if self.open_group("u") {
|
||||
// In a symbol's art, the contents in the dictionary are in the canvas's space, y down.
|
||||
let to_art = self.to_art;
|
||||
if self.in_symbol {
|
||||
self.to_art = Affine::translate(self.canvas_origin) * to_art;
|
||||
}
|
||||
self.contents(content, true);
|
||||
self.to_art = to_art;
|
||||
self.end_group("U", Xy::PLAIN);
|
||||
}
|
||||
let block = std::mem::replace(&mut self.body, outer);
|
||||
@@ -448,15 +455,17 @@ impl Writer<'_> {
|
||||
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
|
||||
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
|
||||
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
|
||||
/// towards the previous one and a weight, in art space), from its top left one down, across and
|
||||
/// up, and `/E`. One object.
|
||||
/// towards the previous one and a weight, in art space; in a symbol's art, in the space a
|
||||
/// gradient mesh's corners are written in there), from its top left one down, across and up,
|
||||
/// and `/E`. One object.
|
||||
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
|
||||
let Some((rows, cols, pts)) = grid else { return };
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
let (rows, cols, width) = (*rows, *cols, cols + 1);
|
||||
let to_art = self.to_art;
|
||||
// In a symbol's art, corners are written in the space a gradient mesh's are written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
let s = &mut self.body;
|
||||
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
|
||||
let num = |s: &mut String, v: f64| {
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Gradient meshes: a mesh as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader,
|
||||
//! `mesh.rs` and `read/art.rs`' `end_mesh`).
|
||||
//!
|
||||
//! `/Mesh X!`, then on `%_` lines `value /key X#` entries: `2 /Version` (corners with an opacity),
|
||||
//! `/Cartesian /Type`, `[rows cols] /Size`, `/Data` (the patches follow), and for each patch, row by
|
||||
//! row, its place `[row col] /P`, the color space (`/DeviceGray`,
|
||||
//! `/DeviceRGB` or `/DeviceCMYK`) with `/CS` where it changes, its four corners with `/N` and `/E`;
|
||||
//! then `/End X!`. A corner is `[color… opacity x y nx ny 1 px py 1]` in art space (in a symbol's
|
||||
//! art, in the canvas's space turned y up about art space's origin there, as an image's matrix in
|
||||
//! it is): its color (gray as lightness), its opacity, the point, the
|
||||
//! handle towards the next corner and the handle towards the one before it, each with a weight of 1.
|
||||
//! The corners go from the patch's top left mesh point to the one below it, then to the right, then
|
||||
//! up: the first index of `/P` runs along the first edge. The mesh's transparency is set before it
|
||||
//! (`0 XR`, `Xy`), its name and opacity mask follow `/End X!` in an `/ArtDictionary`, then `0 0 Xd`
|
||||
//! and `6 () XW`.
|
||||
//!
|
||||
//! Each record is read back with the reader's mesh reading ([`crate::import::mesh_reads`], the
|
||||
//! patches and how they join; not the rest of the `.ai` reader) before it is written: a mesh it
|
||||
//! would read otherwise is written as its drawn look, as are folded meshes (patches whose corners
|
||||
//! turn different ways, along the handles there, or a corner with no angle), meshes in pattern
|
||||
//! tiles and in art cut to a clipping object, and every mesh on a large canvas. A reflected mesh,
|
||||
//! whose patches all turn the negative way, is written with its columns in reverse order: it draws
|
||||
//! the same patches, and reads back with each row's points in reverse order.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{Writer, Xy};
|
||||
use crate::ai_ops::unit;
|
||||
use crate::import::{MAX_MESH_SIDE, mesh_reads};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const MESHES: &str = "gradient meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes that would not open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every gradient mesh on a large canvas are written as their drawn look in the editing data for other apps";
|
||||
|
||||
/// How far (in the document's units, at a scale of 1) a written point or handle's end may move:
|
||||
/// coordinates are written to 4 decimals, which moves a point at most 0.00005 along each axis.
|
||||
const SETTLE_POINT: f64 = 1e-4;
|
||||
/// How far a written color channel or opacity may move: they are written to 4 decimals too.
|
||||
const SETTLE_COLOR: f32 = 1e-4;
|
||||
|
||||
/// The color space a corner's color is written in.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Space {
|
||||
Gray,
|
||||
Rgb,
|
||||
Cmyk,
|
||||
}
|
||||
|
||||
impl Space {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Space::Gray => "/DeviceGray",
|
||||
Space::Rgb => "/DeviceRGB",
|
||||
Space::Cmyk => "/DeviceCMYK",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Mesh `m`'s record as the reader reads it, or `None` when it would read it otherwise (the
|
||||
/// mesh is then written as its drawn look).
|
||||
pub(super) fn mesh_record(&self, m: &GradientMesh) -> Option<String> {
|
||||
// Art cut to a clipping object is written cut, which a mesh can't be. Meshes in pattern
|
||||
// tiles and on a large canvas are written as their drawn look too. (A mesh holds no objects,
|
||||
// so it is written as a mesh however deep it is nested.) A grid the reader doesn't read as
|
||||
// one mesh is left before its record is built.
|
||||
if !self.meshes_live
|
||||
|| self.clip.is_some()
|
||||
|| !self.defining.is_empty()
|
||||
|| !m.is_valid()
|
||||
|| m.rows as usize > MAX_MESH_SIDE
|
||||
|| m.cols as usize > MAX_MESH_SIDE
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// In a symbol's art, corners are written in the space an image's matrix is written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
// Every patch turns the positive way where it is written: from its first corner, the second
|
||||
// (below it) then the fourth (beside it) go anticlockwise, y up. A reflected mesh, whose
|
||||
// patches all turn the other way, is written with its columns in reverse order, which turns
|
||||
// each of them the positive way and draws the same mesh; any other mesh with a patch that
|
||||
// doesn't turn the positive way is written as its drawn look.
|
||||
let reversed;
|
||||
let m = match turns(m, to_art)? {
|
||||
true => m,
|
||||
false => {
|
||||
reversed = columns_reversed(m);
|
||||
&reversed
|
||||
}
|
||||
};
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
// Version 2: each corner has an opacity.
|
||||
let mut s = String::from("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n");
|
||||
let _ = writeln!(s, "%_[{rows} {cols}] /Size X#\n%_/Data X#");
|
||||
let mut space = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let _ = writeln!(s, "%_[{r} {c}] /P X#");
|
||||
// From the top left point down, right and up; each with its handles towards the
|
||||
// next corner and the one before it.
|
||||
for (p, next, prev) in
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)]
|
||||
{
|
||||
corner(&mut s, &mut space, to_art, p, next, prev)?;
|
||||
}
|
||||
s.push_str("%_/E X#\n");
|
||||
}
|
||||
}
|
||||
s.push_str("/End X!\n");
|
||||
let read = mesh_reads(s.as_bytes(), to_art.inverse())?;
|
||||
same_mesh(&read, m, SETTLE_POINT * to_art.inverse().determinant().abs().sqrt().max(1.0)).then_some(s)
|
||||
}
|
||||
|
||||
/// Mesh `n` written as `record`: its transparency before it (`xy`), the record, and the block
|
||||
/// its name and opacity mask go before ([`Self::node`]). The mesh is one object
|
||||
/// ([`Self::take_objects`]); nothing is written when there is no room for it.
|
||||
pub(super) fn write_mesh(&mut self, record: &str, xy: Xy) {
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
self.set_object_xy(xy.object());
|
||||
self.body.push_str(record);
|
||||
self.block_start = self.body.len();
|
||||
self.line("0 0 Xd\n6 () XW");
|
||||
self.block_end = self.body.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way every patch of `m` turns where `to_art` takes it, at each of its four corners, from
|
||||
/// its top left point to the one below it, then right and up, y up: `Some(true)` when all turn
|
||||
/// anticlockwise, `Some(false)` when all turn clockwise, and `None` when they differ (a patch
|
||||
/// folded across itself, or patches folded over each other) or a corner has no angle. Each corner
|
||||
/// is measured twice: along the straight lines to the next corners, and along its handles (towards
|
||||
/// the next corners where a handle is zero), where the patch's edges leave it.
|
||||
fn turns(m: &GradientMesh, to_art: Affine) -> Option<bool> {
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
let mut way = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
// Each corner with the slots of its handles towards the next corner and the one before it.
|
||||
let corners =
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)];
|
||||
for i in 0..4 {
|
||||
let (before, (here, next, prev), after) = (corners[(i + 3) % 4].0, corners[i], corners[(i + 1) % 4].0);
|
||||
let line = |to: &MeshPoint| to_art * to.p - to_art * here.p;
|
||||
let along = |h: usize, to: &MeshPoint| -> Option<Vec2> {
|
||||
let h = *here.handles.get(h)?;
|
||||
Some(if h == Vec2::ZERO { line(to) } else { to_art * (here.p + h) - to_art * here.p })
|
||||
};
|
||||
for cross in [line(after).cross(line(before)), along(next, after)?.cross(along(prev, before)?)] {
|
||||
let positive = match cross {
|
||||
x if x > 0.0 => true,
|
||||
x if x < 0.0 => false,
|
||||
_ => return None,
|
||||
};
|
||||
if *way.get_or_insert(positive) != positive {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
way
|
||||
}
|
||||
|
||||
/// `m` with its columns in reverse order: each row's points from the last to the first, each
|
||||
/// point's handles to the right and left swapped. It draws the same mesh.
|
||||
fn columns_reversed(m: &GradientMesh) -> GradientMesh {
|
||||
let width = m.cols as usize + 1;
|
||||
let points = m
|
||||
.points
|
||||
.chunks(width)
|
||||
.flat_map(|row| {
|
||||
row.iter().rev().map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.handles.swap(H_RIGHT, H_LEFT);
|
||||
p
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
GradientMesh { rows: m.rows, cols: m.cols, points }
|
||||
}
|
||||
|
||||
/// A corner `p` of a patch: its color space when it changes (in `space`), then `[color… opacity x y
|
||||
/// nx ny 1 px py 1] /N X#` with its handles `next` and `prev`, `to_art` taking the document to the
|
||||
/// space the corners are written in.
|
||||
fn corner(s: &mut String, space: &mut Option<Space>, to_art: Affine, p: &MeshPoint, next: usize, prev: usize) -> Option<()> {
|
||||
let (sp, values): (Space, Vec<f32>) = match p.color {
|
||||
// The format's gray is lightness.
|
||||
Color::Gray { k } => (Space::Gray, vec![1.0 - unit(k)]),
|
||||
Color::Rgb { r, g, b } => (Space::Rgb, vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (Space::Cmyk, vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
// The reader reads no Lab mesh colors.
|
||||
Color::Lab { .. } => return None,
|
||||
};
|
||||
if *space != Some(sp) {
|
||||
let _ = writeln!(s, "%_{} /CS X#", sp.name());
|
||||
*space = Some(sp);
|
||||
}
|
||||
let art = |q: Point| to_art * q;
|
||||
let (at, n, b) = (art(p.p), art(p.p + *p.handles.get(next)?), art(p.p + *p.handles.get(prev)?));
|
||||
s.push_str("%_[");
|
||||
for v in values {
|
||||
ps::push_num(s, f64::from(v));
|
||||
s.push(' ');
|
||||
}
|
||||
ps::push_num(s, f64::from(unit(p.opacity)));
|
||||
for v in [at.x, at.y, n.x, n.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1");
|
||||
for v in [b.x, b.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1] /N X#\n");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether `read` is `m` as written: the same grid, each point within `tol` of its place, each
|
||||
/// handle that points into the grid within `tol` (the reader gives the others none, and they draw
|
||||
/// nothing), each color in the same model and within [`SETTLE_COLOR`] a channel, and each opacity
|
||||
/// within it.
|
||||
fn same_mesh(read: &GradientMesh, m: &GradientMesh, tol: f64) -> bool {
|
||||
if (read.rows, read.cols) != (m.rows, m.cols) || read.points.len() != m.points.len() {
|
||||
return false;
|
||||
}
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let near = |a: Point, b: Point| (a - b).hypot() <= tol * (1.0 + 1e-9 * a.to_vec2().hypot());
|
||||
read.points.iter().zip(&m.points).enumerate().all(|(i, (a, b))| {
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
let inside = [c < cols, c > 0, r < rows, r > 0];
|
||||
let handles = [H_RIGHT, H_LEFT, H_DOWN, H_UP].iter().zip(inside).all(|(&h, inside)| {
|
||||
!inside || near(a.p + a.handles.get(h).copied().unwrap_or(Vec2::ZERO), b.p + b.handles.get(h).copied().unwrap_or(Vec2::ZERO))
|
||||
});
|
||||
near(a.p, b.p) && handles && same_color(&a.color, &b.color) && (a.opacity - unit(b.opacity)).abs() <= SETTLE_COLOR
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `a` is `b` as written: the same model, each channel within [`SETTLE_COLOR`] of `b`'s
|
||||
/// clamped to 0 to 1.
|
||||
fn same_color(a: &Color, b: &Color) -> bool {
|
||||
let close = |x: &[f32], y: &[f32]| x.iter().zip(y).all(|(x, y)| (x - unit(*y)).abs() <= SETTLE_COLOR);
|
||||
match (a, b) {
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => close(&[*k], &[*k2]),
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => close(&[*r, *g, *b], &[*r2, *g2, *b2]),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => close(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,8 @@ pub(in crate::ai_editing) const GRADIENTS: &str =
|
||||
pub(in crate::ai_editing) const GRADIENT_SHAPES: &str = "gradients without stops or with more than 256, gradients whose ramp has no length and radial gradients flattened to a line are written as their average color in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str =
|
||||
"the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const GRADIENT_MIX: &str =
|
||||
"gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const GRADIENT_DITHER: &str = "gradients that dither are written without dither's noise in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const GRADIENT_PERCEPTUAL: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const GRADIENT_HUE: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256), in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const CONIC: &str =
|
||||
"conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps";
|
||||
@@ -57,13 +57,14 @@ fn writable_gradient(g: &Gradient) -> bool {
|
||||
g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS
|
||||
}
|
||||
|
||||
/// `g` as the data holds its colors: one mixed around the hue wheel (the data's gradients mix
|
||||
/// their stops' colors directly) as a classic gradient of the stops on its curve
|
||||
/// ([`Gradient::as_classic_curve`]), no more than the `.ai` reader reads when it pads
|
||||
/// ([`GRADIENT_HUE`]); others as they are.
|
||||
fn hue_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
|
||||
/// `g` as the data holds its colors: one mixed by the Perceptual method or around the hue wheel
|
||||
/// (the data's gradients mix their stops' colors directly) as a classic gradient of the stops on
|
||||
/// its curve in process colors ([`Gradient::as_classic_curve`]), no more than the `.ai` reader
|
||||
/// reads when it pads ([`GRADIENT_PERCEPTUAL`], [`GRADIENT_HUE`]); a classic one, and one the
|
||||
/// data can't hold as a gradient ([`writable_gradient`]), as it is.
|
||||
fn curve_as_stops(g: &Gradient) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if !g.method.is_hue() {
|
||||
if g.method.is_classic() || !writable_gradient(g) {
|
||||
return Cow::Borrowed(g);
|
||||
}
|
||||
let curve = g.as_classic_curve();
|
||||
@@ -88,6 +89,16 @@ pub(in crate::ai_editing) fn free_gradient_name(next: &mut u64, mut taken: impl
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `stop` linked to a global process color of `doc` (one [`Writer::stop_color`] writes as its
|
||||
/// color, [`STOP_LINKS`])?
|
||||
fn links_global_process(doc: &vectorcraft_doc::Document, stop: &GradientStop) -> bool {
|
||||
stop.swatch
|
||||
.as_deref()
|
||||
.filter(|n| *n != REGISTRATION)
|
||||
.and_then(|name| doc.swatch(name))
|
||||
.is_some_and(|sw| matches!(sw.paint, Paint::Solid { swatch: None, .. }) && !sw.spot && sw.global)
|
||||
}
|
||||
|
||||
/// The stops of `g` in order of their place on the ramp.
|
||||
fn sorted_stops(g: &Gradient) -> Vec<&GradientStop> {
|
||||
let mut stops: Vec<&GradientStop> = g.stops.iter().collect();
|
||||
@@ -100,10 +111,11 @@ impl Writer<'_> {
|
||||
pub(in crate::ai_editing) fn reserve_swatch_gradients(&mut self) {
|
||||
let doc = self.doc;
|
||||
for sw in doc.swatches_iter() {
|
||||
// As `swatch_paint` writes it: one mixed around the hue wheel as the stops on its curve,
|
||||
// and the stops of one that repeats or reflects repeated.
|
||||
// As `swatch_paint` writes it: one mixed by the Perceptual method or around the hue
|
||||
// wheel as the stops on its curve, and the stops of one that repeats or reflects
|
||||
// repeated.
|
||||
if let Paint::Gradient(g) = &sw.paint
|
||||
&& let stops = hue_as_stops(&g.gradient)
|
||||
&& let stops = curve_as_stops(&g.gradient)
|
||||
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
@@ -165,9 +177,11 @@ impl Writer<'_> {
|
||||
// The data has no spread: a gradient that repeats or reflects is written with its stops
|
||||
// repeated over `area` (a conic one, written linear, around its turn).
|
||||
let mut g: GradientPaint = (**g).clone();
|
||||
if g.gradient.method.is_hue() {
|
||||
self.warn(GRADIENT_HUE);
|
||||
g.gradient = hue_as_stops(&g.gradient).into_owned();
|
||||
// A gradient written as its average color (a freeform one, or one without stops or with
|
||||
// more than the reader reads) keeps its own stops.
|
||||
if !g.gradient.method.is_classic() && writable_gradient(&g.gradient) {
|
||||
self.warn_curve(&g.gradient);
|
||||
g.gradient = curve_as_stops(&g.gradient).into_owned();
|
||||
}
|
||||
if g.gradient.is_spread() {
|
||||
self.warn(SPREAD);
|
||||
@@ -192,6 +206,18 @@ impl Writer<'_> {
|
||||
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..g }))
|
||||
}
|
||||
|
||||
/// The warnings for gradient `g`, mixed by the Perceptual method or around the hue wheel,
|
||||
/// written as the stops on its curve ([`curve_as_stops`]): [`GRADIENT_PERCEPTUAL`] or
|
||||
/// [`GRADIENT_HUE`], and [`STOP_LINKS`] when one of its stops is linked to a global process
|
||||
/// color (the stops on the curve hold no links).
|
||||
fn warn_curve(&mut self, g: &Gradient) {
|
||||
self.warn(if g.method.is_hue() { GRADIENT_HUE } else { GRADIENT_PERCEPTUAL });
|
||||
let doc = self.doc;
|
||||
if g.stops.iter().any(|s| links_global_process(doc, s)) {
|
||||
self.warn(STOP_LINKS);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills and strokes of `n` that paint (outline `bp`), their gradients placed
|
||||
/// ([`Self::placed`]): a fill's on the shape's bounds, a stroke's on what it paints, the stops
|
||||
/// of one that repeats or reflects repeated over the box the stroke paints, miter spikes
|
||||
@@ -363,8 +389,8 @@ impl Writer<'_> {
|
||||
/// linear gradient's from the last to the first and a radial one's from the first to the last,
|
||||
/// `BD`, `%AI5_EndGradient`.
|
||||
fn gradient_def(&mut self, s: &mut String, d: &GradientDef) {
|
||||
if d.gradient.dither || !d.gradient.method.is_classic() {
|
||||
self.warn(GRADIENT_MIX);
|
||||
if d.gradient.dither {
|
||||
self.warn(GRADIENT_DITHER);
|
||||
}
|
||||
if d.gradient.kind == GradientKind::Conic {
|
||||
self.warn(CONIC);
|
||||
@@ -587,16 +613,17 @@ impl Writer<'_> {
|
||||
/// be written.
|
||||
pub(super) fn swatch_paint(&mut self, s: &mut String, sw: &vectorcraft_color::swatch::Swatch) -> bool {
|
||||
// A swatch has no placement: one that repeats or reflects holds its stops repeated along
|
||||
// its vector, and one mixed around the hue wheel the stops on its curve.
|
||||
// its vector, and one mixed by the Perceptual method or around the hue wheel the stops on
|
||||
// its curve.
|
||||
let stops = match &sw.paint {
|
||||
Paint::Gradient(g) => Some(hue_as_stops(&g.gradient)),
|
||||
Paint::Gradient(g) => Some(curve_as_stops(&g.gradient)),
|
||||
_ => None,
|
||||
};
|
||||
let unrolled = stops.as_deref().map(|g| g.unrolled_within(crate::import::MAX_GRADIENT_STOPS));
|
||||
match &sw.paint {
|
||||
Paint::Gradient(g) if unrolled.as_deref().is_some_and(writable_gradient) => {
|
||||
if g.gradient.method.is_hue() {
|
||||
self.warn(GRADIENT_HUE);
|
||||
if !g.gradient.method.is_classic() {
|
||||
self.warn_curve(&g.gradient);
|
||||
}
|
||||
if g.gradient.is_spread() {
|
||||
self.warn(SPREAD);
|
||||
|
||||
@@ -90,9 +90,10 @@ pub use ai::NameEncoding;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::objects_read;
|
||||
pub(crate) use ai::{
|
||||
BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object,
|
||||
read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS,
|
||||
MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads,
|
||||
brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list,
|
||||
style_moves_with, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN};
|
||||
|
||||
@@ -34,14 +34,20 @@ use std::io::Read as _;
|
||||
use super::lex::find;
|
||||
use crate::ps;
|
||||
|
||||
pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object};
|
||||
pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads};
|
||||
pub(crate) use brush::{
|
||||
BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over,
|
||||
};
|
||||
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
|
||||
pub(crate) use envelope::MAX_CHECKED;
|
||||
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
|
||||
pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright};
|
||||
pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID};
|
||||
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
|
||||
#[cfg(test)]
|
||||
pub(crate) use frames::TEXT_FRAME_SCANS;
|
||||
pub(crate) use frames::text_frames;
|
||||
pub(crate) use mesh::{MAX_SIDE as MAX_MESH_SIDE, mesh_reads};
|
||||
pub use obj::{NameEncoding, Names};
|
||||
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
|
||||
#[cfg(test)]
|
||||
@@ -50,14 +56,14 @@ pub(crate) use read::objects_read;
|
||||
pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame,
|
||||
slot_of, style_moves_with, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
pub(crate) use read::{
|
||||
MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, slot_of,
|
||||
style_moves_with, symbol_art_member,
|
||||
};
|
||||
|
||||
pub(crate) use read::is_look_slot;
|
||||
pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number};
|
||||
|
||||
@@ -15,11 +15,14 @@
|
||||
//!
|
||||
//! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is
|
||||
//! Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2
|
||||
//! is the distance in points, as a 32-bit float. Word 10 is the number of keys, and the words after
|
||||
//! it are a record of six words per key that starts with the key's id. For Specified Steps, the
|
||||
//! steps between two keys are counted from the steps drawn. The orientation is taken from the steps
|
||||
//! drawn: whichever one lays the blend out as they are drawn. A blend whose parts don't agree,
|
||||
//! whose spacing isn't one of these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
//! is the distance in points, as a 32-bit float. Word 5 is 0 for Align to Page and, for Align to
|
||||
//! Path, a 32-bit float of 8 or more. Word 10 is the number of keys, and the words after it are a
|
||||
//! record of six words per key that starts with the key's id. For Specified Steps, the steps
|
||||
//! between two keys are counted from the steps drawn. The orientation is the record's when it lays
|
||||
//! the blend out as the steps are drawn, else whichever one does (the closest when both do). A blend
|
||||
//! with no spine part whose record names its keys in their order has no spine of its own: it runs
|
||||
//! straight between its keys' centers. A blend whose parts don't agree, whose spacing isn't one of
|
||||
//! these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -28,19 +31,19 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_expand, blend_steps};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
use vectorcraft_geom::{ParamCurve, PathData, Point, SubPath};
|
||||
|
||||
/// The plugin that writes blends.
|
||||
pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
pub(crate) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
/// The most bytes of a blend's record read.
|
||||
pub(super) const MAX_RECORD: usize = 4096;
|
||||
/// The most keys read from one blend.
|
||||
const MAX_KEYS: usize = 64;
|
||||
pub(crate) const MAX_KEYS: usize = 64;
|
||||
/// The most steps between two keys (Blend Options' limit).
|
||||
const MAX_STEPS: usize = 1000;
|
||||
/// The most objects (keys and steps) one blend may lay out to be read live; more keep their
|
||||
/// drawn steps.
|
||||
pub(super) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
pub(crate) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
/// How far (pt) a step laid out here may be from where the file draws it.
|
||||
const PLACE_TOLERANCE: f64 = 0.5;
|
||||
/// How far a step's colour (each channel, 0 to 1) may be from the drawn one.
|
||||
@@ -66,6 +69,8 @@ pub(super) struct Record {
|
||||
pub(super) ids: Vec<String>,
|
||||
/// `None`: Specified Steps, whose steps the reader counts from the drawn ones.
|
||||
pub(super) spacing: Option<BlendSpacing>,
|
||||
/// The orientation word 5 names, when it names one.
|
||||
pub(super) orientation: Option<BlendOrientation>,
|
||||
}
|
||||
|
||||
/// A blend's record, or `None` for a record that isn't one or whose spacing isn't read: an
|
||||
@@ -82,7 +87,18 @@ pub(super) fn record(bytes: &[u8]) -> Option<Record> {
|
||||
_ => return None,
|
||||
};
|
||||
let ids = record_ids(&words)?;
|
||||
Some(Record { ids, spacing })
|
||||
let orientation = words.get(5).and_then(|w| orientation(*w));
|
||||
Some(Record { ids, spacing, orientation })
|
||||
}
|
||||
|
||||
/// The orientation in a record's word 5: 0 is Align to Page, a 32-bit float of 8 or more Align to
|
||||
/// Path; anything else names none.
|
||||
fn orientation(bits: u32) -> Option<BlendOrientation> {
|
||||
if bits == 0 {
|
||||
return Some(BlendOrientation::AlignToPage);
|
||||
}
|
||||
let a = f32::from_bits(bits);
|
||||
(a.is_finite() && a >= 8.0).then_some(BlendOrientation::AlignToPath)
|
||||
}
|
||||
|
||||
/// The distance in a record's word `bits` (a 32-bit float), as the shortest decimal that reads
|
||||
@@ -131,6 +147,7 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if keys.len() < 2 || named.len() != keys.len() || ids.len() != keys.len() {
|
||||
return None;
|
||||
}
|
||||
let in_order = named.iter().zip(ids).all(|(n, id)| *n == id.as_str());
|
||||
named.sort_unstable();
|
||||
let mut listed: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
listed.sort_unstable();
|
||||
@@ -150,12 +167,20 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
})
|
||||
.collect();
|
||||
// A blend whose spine was never edited has none written: its spine is the straight lines
|
||||
// between the keys' centres, in the record's order.
|
||||
let spine = match spine {
|
||||
Some(spine) => spine,
|
||||
None => straight_spine(&keys, ids, roles)?,
|
||||
// between the keys' centers, in the record's order. With the keys in that order it is the
|
||||
// spine of a blend that has none of its own.
|
||||
let (spine, key_anchors) = match spine {
|
||||
Some(spine) => {
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
None if in_order => (None, vec![]),
|
||||
None => {
|
||||
let spine = straight_spine(&keys, ids, roles)?;
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
};
|
||||
let key_anchors = on_spine(&keys, &spine)?;
|
||||
let spacing = match record.spacing {
|
||||
// Specified Steps: the steps between two keys are the drawn objects that aren't keys,
|
||||
// shared out.
|
||||
@@ -170,26 +195,68 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if cost > *budget {
|
||||
return None;
|
||||
}
|
||||
let spec = BlendSpec { spacing, spine: Some(spine), key_anchors, ..BlendSpec::default() };
|
||||
let spec = BlendSpec { spacing, spine, key_anchors, ..BlendSpec::default() };
|
||||
// As many objects as the spacing lays out between each pair of keys (the orientation doesn't
|
||||
// change how many), counted before anything is laid out: as many as are drawn.
|
||||
if blend_steps(&keys, &spec).into_iter().fold(keys.len(), usize::saturating_add) != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
*budget -= cost;
|
||||
// The drawn steps' centres and paints, once.
|
||||
let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::<Option<_>>()?;
|
||||
// The orientation that lays the steps out as drawn, the closest when both do.
|
||||
[BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
// The drawn steps as the check compares them, once.
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d)).collect::<Option<_>>()?;
|
||||
// The orientations that lay the steps out as drawn (the check compares the steps' centers, which
|
||||
// turning the steps along the spine leaves in place). Of those that also lay them out at their
|
||||
// drawn sizes and turned as drawn, the record's, else the closest; when none does, the closest
|
||||
// of them all.
|
||||
let fits: Vec<(f64, BlendSpec, Vec<Node>)> = [BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
.into_iter()
|
||||
.filter_map(|orientation| {
|
||||
let spec = BlendSpec { orientation, ..spec.clone() };
|
||||
let laid = blend_expand(&keys, &spec);
|
||||
let off = how_far(&laid, &drawn)?;
|
||||
Some((off, spec))
|
||||
let off = how_far(&laid, &drawn, false)?;
|
||||
Some((off, spec, laid))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, spec)| NodeKind::Blend { children: keys, spec: Box::new(spec) })
|
||||
.collect();
|
||||
let as_drawn: Vec<&(f64, BlendSpec, Vec<Node>)> = fits.iter().filter(|(_, _, laid)| how_far(laid, &drawn, true).is_some()).collect();
|
||||
as_drawn
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(_, s, _)| Some(s.orientation) == record.orientation)
|
||||
.or_else(|| as_drawn.iter().copied().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.or_else(|| fits.iter().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.map(|(_, spec, _)| NodeKind::Blend { children: keys, spec: Box::new(spec.clone()) })
|
||||
}
|
||||
|
||||
/// What the reader makes of a blend written as the key objects `keys`, named by `ids` in their
|
||||
/// order, the spine `spine` (`None`: no spine part), the record `bytes` and the drawn steps `drawn`:
|
||||
/// the live blend's settings, or `None` where it keeps the drawn steps. Takes from `budget` as
|
||||
/// [`live_blend`] does.
|
||||
pub(crate) fn blend_reads(
|
||||
keys: &[Arc<Node>],
|
||||
ids: &[String],
|
||||
spine: Option<&PathData>,
|
||||
bytes: &[u8],
|
||||
drawn: &[Node],
|
||||
budget: &mut usize,
|
||||
) -> Option<BlendSpec> {
|
||||
let record = record(bytes)?;
|
||||
let mut roles = Roles::new();
|
||||
let mut parts: Vec<Arc<Node>> = Vec::with_capacity(keys.len() + 1);
|
||||
for (k, id) in keys.iter().zip(ids) {
|
||||
roles.insert(k.id, ("K".to_string(), Some(id.clone())));
|
||||
parts.push(k.clone());
|
||||
}
|
||||
if let Some(s) = spine {
|
||||
let id = NodeId(u64::MAX);
|
||||
roles.insert(id, ("S".to_string(), None));
|
||||
parts.push(Arc::new(Node::path(id, s.clone(), Default::default())));
|
||||
}
|
||||
let edit = Node::new(NodeId(u64::MAX - 1), NodeKind::Group { children: parts, clip: false });
|
||||
let drawn = Node::new(NodeId(u64::MAX - 2), NodeKind::Group { children: drawn.iter().cloned().map(Arc::new).collect(), clip: false });
|
||||
match live_blend(&edit, &drawn, &record, &roles, budget)? {
|
||||
NodeKind::Blend { spec, .. } => Some(*spec),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a
|
||||
@@ -227,6 +294,117 @@ fn centre(n: &Node) -> Option<Point> {
|
||||
n.geometric_bounds().map(|b| b.center()).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The most anchors of an object's paths the check compares; an object with more is compared by its
|
||||
/// size alone.
|
||||
const MAX_MARK_ANCHORS: usize = 64;
|
||||
/// The most drawn objects whose outlines one check compares, spread evenly from the first to the
|
||||
/// last; the rest are compared by their sizes alone (the orientation turns every step alike).
|
||||
const MAX_OUTLINE_CHECKS: usize = 16;
|
||||
/// The most outline comparisons one check makes (a drawn object compared can have more than one
|
||||
/// laid object in its place); past them, a drawn object whose outline is to be compared matches
|
||||
/// none.
|
||||
const MAX_OUTLINE_COMPARISONS: usize = 4 * MAX_OUTLINE_CHECKS;
|
||||
|
||||
/// An object as the check compares it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Drawn<'a> {
|
||||
centre: Point,
|
||||
fill: Fill,
|
||||
/// Its width and height.
|
||||
size: Point,
|
||||
/// The object, for its paths' outline ([`outline`]), which turning it moves.
|
||||
node: &'a Node,
|
||||
}
|
||||
|
||||
/// `n` as the check compares it, or `None` when it has no finite bounds.
|
||||
fn drawn_as(n: &Node) -> Option<Drawn<'_>> {
|
||||
let size = n.geometric_bounds().map(|b| Point::new(b.width(), b.height())).filter(|p| p.x.is_finite() && p.y.is_finite())?;
|
||||
Some(Drawn { centre: centre(n)?, fill: fill(n), size, node: n })
|
||||
}
|
||||
|
||||
/// How the check compares an object's turn.
|
||||
enum Outline {
|
||||
/// By its outline: every subpath of more than one anchor of its paths, in any order, each with
|
||||
/// its path's fill, so that a turn that trades the places of paths painted differently doesn't
|
||||
/// pass.
|
||||
Paths(Vec<(Fill, SubPath)>),
|
||||
/// By its size alone: it holds art whose drawing isn't its members (a blend, an envelope, a
|
||||
/// repeat), art past eight levels down, more than [`MAX_MARK_ANCHORS`] anchors or no subpath to
|
||||
/// compare.
|
||||
Size,
|
||||
}
|
||||
|
||||
/// How the check compares `n`'s turn (the members of its groups and compound paths looked through,
|
||||
/// at most eight levels down; a compound path's members take its fill).
|
||||
fn outline(n: &Node) -> Outline {
|
||||
/// What the walk found.
|
||||
#[derive(Default)]
|
||||
struct Walk {
|
||||
subpaths: Vec<(Fill, SubPath)>,
|
||||
anchors: usize,
|
||||
/// Art compared by the size alone, or too many anchors.
|
||||
size_only: bool,
|
||||
}
|
||||
fn add(n: &Node, depth: usize, painted: Option<Fill>, w: &mut Walk) {
|
||||
if w.size_only {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
// A subpath of one anchor has no segment to compare with.
|
||||
for s in path.subpaths.iter().filter(|s| s.anchors.len() > 1) {
|
||||
w.anchors = w.anchors.saturating_add(s.anchors.len());
|
||||
if w.anchors > MAX_MARK_ANCHORS {
|
||||
w.size_only = true;
|
||||
return;
|
||||
}
|
||||
w.subpaths.push((f, s.clone()));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } if depth < 8 => {
|
||||
for c in children {
|
||||
add(c, depth + 1, painted, w);
|
||||
}
|
||||
}
|
||||
NodeKind::Compound { children, .. } if depth < 8 => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
for c in children {
|
||||
add(c, depth + 1, Some(f), w);
|
||||
}
|
||||
}
|
||||
_ => w.size_only = true,
|
||||
}
|
||||
}
|
||||
let mut w = Walk::default();
|
||||
add(n, 0, None, &mut w);
|
||||
if w.size_only || w.subpaths.is_empty() { Outline::Size } else { Outline::Paths(w.subpaths) }
|
||||
}
|
||||
|
||||
/// Do two outlines ([`Outline::Paths`]) draw the same lines in the same fills: each anchor of one,
|
||||
/// and the points a quarter, half and three quarters along each of its segments (which show how a
|
||||
/// curved side bends), within `tolerance` of the other's subpaths of a fill that matches its own?
|
||||
/// Where a path starts, how many anchors it has on a straight or curved stretch, and the order of
|
||||
/// the paths don't count.
|
||||
fn same_outline(a: &[(Fill, SubPath)], b: &[(Fill, SubPath)], tolerance: f64) -> bool {
|
||||
let on = |from: &[(Fill, SubPath)], to: &[(Fill, SubPath)]| {
|
||||
from.iter().all(|(f, s)| {
|
||||
// Fills the check can't compare (gradients, patterns) are compared with each other by
|
||||
// their outline alone.
|
||||
let to = PathData::new(
|
||||
to.iter().filter(|(g, _)| same_fill(*f, *g) || (*f == Fill::Other && *g == Fill::Other)).map(|(_, t)| t.clone()).collect(),
|
||||
);
|
||||
let near = |p: Point| to.nearest(p).is_some_and(|(.., d)| d <= tolerance);
|
||||
s.anchors.iter().all(|p| near(p.p))
|
||||
&& (0..s.segment_count()).all(|i| {
|
||||
let c = s.segment(i);
|
||||
[0.25, 0.5, 0.75].into_iter().all(|t| near(c.eval(t)))
|
||||
})
|
||||
})
|
||||
};
|
||||
on(a, b) && on(b, a)
|
||||
}
|
||||
|
||||
/// An object's fill, as far as the check compares it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fill {
|
||||
@@ -267,31 +445,76 @@ fn same_fill(a: Fill, b: Fill) -> bool {
|
||||
/// farthest, each drawn object matched to a laid one of its own within the tolerance (each laid
|
||||
/// one matches one drawn one: the nearest still free; through a grid of cells the tolerance wide,
|
||||
/// so each finds its neighbours without looking at them all), when they are as many and each
|
||||
/// matches in place and fill; else `None` (also when that matching leaves one out).
|
||||
fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option<f64> {
|
||||
/// matches in place and fill, and with `turned` also in width and height and, for at most
|
||||
/// [`MAX_OUTLINE_CHECKS`] drawn objects spread from the first to the last, in the outline of its
|
||||
/// paths (each within twice the tolerance), which turning an object changes; else `None` (also when
|
||||
/// that matching leaves one out, and when it would take more than [`MAX_OUTLINE_COMPARISONS`]
|
||||
/// outline comparisons).
|
||||
fn how_far(laid: &[Node], drawn: &[Drawn], turned: bool) -> Option<f64> {
|
||||
if laid.len() != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
let cell = |p: Point| ((p.x / PLACE_TOLERANCE).floor() as i64, (p.y / PLACE_TOLERANCE).floor() as i64);
|
||||
let laid: Vec<(Point, Fill)> = laid.iter().map(|l| Some((centre(l)?, fill(l)))).collect::<Option<_>>()?;
|
||||
let laid: Vec<Drawn> = laid.iter().map(drawn_as).collect::<Option<_>>()?;
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::with_capacity(laid.len());
|
||||
for (i, (p, _)) in laid.iter().enumerate() {
|
||||
grid.entry(cell(*p)).or_default().push(i);
|
||||
for (i, l) in laid.iter().enumerate() {
|
||||
grid.entry(cell(l.centre)).or_default().push(i);
|
||||
}
|
||||
let close = |a: Point, b: Point| (a.x - b.x).abs() <= 2.0 * PLACE_TOLERANCE && (a.y - b.y).abs() <= 2.0 * PLACE_TOLERANCE;
|
||||
// The drawn objects whose outlines are compared: all of them, or as many as the limit allows,
|
||||
// spread evenly so that the first and the last are among them.
|
||||
let mut compare_outline = vec![drawn.len() <= MAX_OUTLINE_CHECKS; drawn.len()];
|
||||
if drawn.len() > MAX_OUTLINE_CHECKS {
|
||||
for j in 0..MAX_OUTLINE_CHECKS {
|
||||
if let Some(c) = compare_outline.get_mut(j * (drawn.len() - 1) / (MAX_OUTLINE_CHECKS - 1)) {
|
||||
*c = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let outlines_compared = std::cell::Cell::new(0usize);
|
||||
let same_turn = |l: &Drawn, d: &Drawn, compare: bool| {
|
||||
if !turned {
|
||||
return true;
|
||||
}
|
||||
if !close(l.size, d.size) || !compare {
|
||||
return close(l.size, d.size);
|
||||
}
|
||||
// An outline that isn't compared doesn't count as the same.
|
||||
if outlines_compared.get() >= MAX_OUTLINE_COMPARISONS {
|
||||
return false;
|
||||
}
|
||||
outlines_compared.set(outlines_compared.get() + 1);
|
||||
match (outline(l.node), outline(d.node)) {
|
||||
(Outline::Paths(a), Outline::Paths(b)) => same_outline(&a, &b, 2.0 * PLACE_TOLERANCE),
|
||||
// Live art against its drawing, too many anchors, or no paths: compared by the size
|
||||
// alone.
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let mut used = vec![false; laid.len()];
|
||||
let mut worst: f64 = 0.0;
|
||||
for &(c, f) in drawn {
|
||||
for (k, d) in drawn.iter().enumerate() {
|
||||
let (c, f) = (d.centre, d.fill);
|
||||
let compare = compare_outline.get(k).copied().unwrap_or(false);
|
||||
let (cx, cy) = cell(c);
|
||||
// Coordinates far out saturate the cells: the neighbours' keys saturate too.
|
||||
let (i, near) = (-1i64..=1)
|
||||
let candidates = (-1i64..=1)
|
||||
.flat_map(|dx| (-1i64..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy))))
|
||||
.filter_map(|k| grid.get(&k))
|
||||
.flatten()
|
||||
.filter(|&&i| !used.get(i).copied().unwrap_or(true))
|
||||
.filter_map(|&i| laid.get(i).map(|l| (i, l)))
|
||||
.filter(|(_, (p, lf))| (*p - c).hypot() <= PLACE_TOLERANCE && same_fill(*lf, f))
|
||||
.map(|(i, (p, _))| (i, (*p - c).hypot()))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
.filter(|(_, l)| (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f));
|
||||
let (i, near) = if turned && compare {
|
||||
// Outlines are tried nearest first, so that steps crowded in one place don't spend the
|
||||
// outline comparisons on candidates farther off.
|
||||
let mut nearest: Vec<(usize, f64)> =
|
||||
candidates.filter(|(_, l)| close(l.size, d.size)).map(|(i, l)| (i, (l.centre - c).hypot())).collect();
|
||||
nearest.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
nearest.into_iter().find(|(i, _)| laid.get(*i).is_some_and(|l| same_turn(l, d, true)))?
|
||||
} else {
|
||||
candidates.filter(|(_, l)| same_turn(l, d, false)).map(|(i, l)| (i, (l.centre - c).hypot())).min_by(|a, b| a.1.total_cmp(&b.1))?
|
||||
};
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
@@ -364,7 +587,7 @@ mod tests {
|
||||
let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false });
|
||||
let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false });
|
||||
let mut budget = 1;
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
assert!(live_blend(&edit, &drawn, &record, &Roles::new(), &mut budget).is_none());
|
||||
assert_eq!(budget, 1);
|
||||
}
|
||||
@@ -396,7 +619,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_blend_takes_from_the_budget_only_when_it_is_laid_out() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
let mut budget = 10;
|
||||
assert!(matches!(live_blend(&edit, &drawn, &steps, &roles, &mut budget), Some(NodeKind::Blend { .. })));
|
||||
assert_eq!(budget, 0);
|
||||
@@ -417,7 +640,7 @@ mod tests {
|
||||
let NodeKind::Group { children, .. } = &drawn.kind else { panic!("a group") };
|
||||
let keys_alone = [children[0].clone(), children[4].clone()];
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: keys_alone.to_vec(), clip: false });
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)) };
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)), orientation: None };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &far, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.spacing, BlendSpacing::Distance(150.0));
|
||||
@@ -427,6 +650,44 @@ mod tests {
|
||||
assert_eq!(budget, 6);
|
||||
}
|
||||
|
||||
/// Word 5 names the orientation: 0 Align to Page, a 32-bit float of 8 or more (8 and an angle)
|
||||
/// Align to Path; any other value names none, and a record too short to hold it names none.
|
||||
#[test]
|
||||
fn records_say_their_orientation() {
|
||||
let magic = u32::from_le_bytes(*b"DCBA");
|
||||
let words = |w5: u32| {
|
||||
[magic, 1, 50f32.to_bits(), 0, 3, w5, 'C' as u32, 0, 0, 1, 2, 'A' as u32, 0, 0, u32::MAX, u32::MAX, 0, 'B' as u32, 0, 1f32.to_bits()]
|
||||
.into_iter()
|
||||
.chain([u32::MAX, u32::MAX, 3])
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect::<Vec<u8>>()
|
||||
};
|
||||
let orientation = |w5: u32| record(&words(w5)).map(|r| r.orientation);
|
||||
assert_eq!(orientation(0), Some(Some(BlendOrientation::AlignToPage)));
|
||||
assert_eq!(orientation(8f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
assert_eq!(orientation(11.141593f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
for other in [1f32.to_bits(), 7.9f32.to_bits(), (-9f32).to_bits(), f32::NAN.to_bits(), f32::INFINITY.to_bits()] {
|
||||
assert_eq!(orientation(other), Some(None), "{other:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a level straight spine both orientations lay two squares' steps out alike: the blend takes
|
||||
/// the record's orientation, and Align to Page when the record names none.
|
||||
#[test]
|
||||
fn the_records_orientation_is_kept_where_both_lay_out_alike() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
for (named, want) in [
|
||||
(Some(BlendOrientation::AlignToPath), BlendOrientation::AlignToPath),
|
||||
(Some(BlendOrientation::AlignToPage), BlendOrientation::AlignToPage),
|
||||
(None, BlendOrientation::AlignToPage),
|
||||
] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: named };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, want, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two drawn steps on one laid object don't both match it: each laid object matches one drawn
|
||||
/// one, so a drawing the blend doesn't lay out isn't taken for it.
|
||||
#[test]
|
||||
@@ -435,12 +696,261 @@ mod tests {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
// `laid` against the objects `drawn` as the check compares them.
|
||||
let check = |laid: &[Node], drawn: &[Node], turned: bool| {
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d).expect("bounds")).collect();
|
||||
how_far(laid, &drawn, turned)
|
||||
};
|
||||
let laid = [square(0.0), square(50.0)];
|
||||
let c = |x: f64| (Point::new(x + 5.0, 5.0), Fill::None);
|
||||
assert!(how_far(&laid, &[c(0.0), c(50.0)]).is_some());
|
||||
assert!(how_far(&laid, &[c(0.0), c(0.1)]).is_none(), "both drawn steps near the first laid one");
|
||||
assert!(check(&laid, &[square(0.0), square(50.0)], true).is_some());
|
||||
assert!(check(&laid, &[square(0.0), square(0.1)], false).is_none(), "both drawn steps near the first laid one");
|
||||
// Sizes and outlines count only when asked for: a wider rectangle with the same center, and
|
||||
// a triangle turned a half turn.
|
||||
let wide = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, 2.5, x + 15.0, 7.5));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], true).is_none());
|
||||
// Steps on one center match by their size, in whichever order they are drawn.
|
||||
let big = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, -5.0, x + 15.0, 15.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&[square(0.0), big(0.0)], &[big(0.0), square(0.0)], true).is_some());
|
||||
// A group's members in close reds match in whichever order they are drawn.
|
||||
let reds = |x: f64, order: [usize; 3]| {
|
||||
let member = |k: usize| {
|
||||
let left = x + k as f64 * 10.0;
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(left, 0.0, left + 8.0, 8.0));
|
||||
let red = [0.25, 0.265, 0.28].get(k).copied().unwrap_or(0.0);
|
||||
Arc::new(Node::path(NodeId(0), path, vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(red, 0.0, 0.0)), Paint::None, 0.0)))
|
||||
};
|
||||
Node::group(NodeId(0), order.iter().map(|k| member(*k)).collect())
|
||||
};
|
||||
assert!(check(&[reds(0.0, [0, 1, 2]), reds(50.0, [0, 1, 2])], &[reds(0.0, [1, 0, 2]), reds(50.0, [1, 0, 2])], true).is_some());
|
||||
// A triangle turned a half turn has its anchors elsewhere.
|
||||
let polygon = |points: &[Point]| Node::path(NodeId(0), PathData::single(SubPath::polyline(points, true)), Default::default());
|
||||
let triangle = |x: f64, turn: f64| {
|
||||
let mut n = polygon(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [triangle(0.0, 0.0), triangle(50.0, 0.0)];
|
||||
let turned = |x: f64| triangle(x, std::f64::consts::PI);
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], true).is_none());
|
||||
// So has one in a group, filled with a gradient, which the check compares by its outline.
|
||||
let graded = |x: f64, turn: f64| {
|
||||
let mut t = triangle(x, turn);
|
||||
let gradient = vectorcraft_color::gradient::GradientPaint::new(vectorcraft_color::gradient::Gradient::default());
|
||||
t.appearance.set_fill(Paint::Gradient(Box::new(gradient)));
|
||||
Node::group(NodeId(0), vec![Arc::new(t)])
|
||||
};
|
||||
let in_groups = [graded(0.0, 0.0), graded(50.0, 0.0)];
|
||||
assert!(check(&in_groups, &[graded(0.0, 0.0), graded(50.0, 0.0)], true).is_some());
|
||||
assert!(check(&in_groups, &[graded(0.0, std::f64::consts::PI), graded(50.0, std::f64::consts::PI)], true).is_none());
|
||||
// The same triangle drawn from another of its anchors matches.
|
||||
let shifted = |x: f64| polygon(&[Point::new(x + 10.0, 5.0), Point::new(x, 0.0), Point::new(x, 10.0)]);
|
||||
assert!(check(&laid, &[shifted(0.0), shifted(50.0)], true).is_some());
|
||||
// So does the same triangle drawn with another anchor on one of its sides.
|
||||
let split = |x: f64| polygon(&[Point::new(x, 0.0), Point::new(x, 5.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
assert!(check(&laid, &[split(0.0), split(50.0)], true).is_some());
|
||||
// A square with its top side bent inward has the same corners as its half turn, whose bent
|
||||
// side is at the bottom: the points along its sides tell them apart.
|
||||
let bent = |x: f64, turn: f64| {
|
||||
let (tl, tr) = (Point::new(x, 0.0), Point::new(x + 10.0, 0.0));
|
||||
let anchors = vec![
|
||||
vectorcraft_geom::Anchor::with_handles(tl, tl, Point::new(x + 3.0, 4.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(tr, Point::new(x + 7.0, 4.0), tr),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x + 10.0, 10.0)),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x, 10.0)),
|
||||
];
|
||||
let mut n = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, true)), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let upright = [bent(0.0, 0.0), bent(50.0, 0.0)];
|
||||
assert!(check(&upright, &[bent(0.0, 0.0), bent(50.0, 0.0)], true).is_some());
|
||||
let half = std::f64::consts::PI;
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], false).is_some());
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], true).is_none(), "the bent side at the bottom");
|
||||
// Past the limit of outlines compared, the last object is still among them.
|
||||
let row = |last: Node| {
|
||||
let mut row: Vec<Node> = (0..MAX_OUTLINE_CHECKS).map(|i| square(20.0 * i as f64)).collect();
|
||||
row.push(last);
|
||||
row
|
||||
};
|
||||
let end = 20.0 * MAX_OUTLINE_CHECKS as f64;
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, 0.0)), true).is_some());
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, half)), true).is_none(), "the last one turned");
|
||||
// A hundred steps crowded within the tolerance of each other match their drawn copies:
|
||||
// each drawn one is compared with the nearest laid one first.
|
||||
let crowd = |turn: f64| (0..100u32).map(|i| triangle(0.4 * f64::from(i) / 99.0, turn)).collect::<Vec<_>>();
|
||||
assert!(check(&crowd(0.0), &crowd(0.0), true).is_some());
|
||||
assert!(check(&crowd(0.0), &crowd(half), true).is_none(), "the crowd turned");
|
||||
// A compound path matches with its contours in another order, and not turned a half turn.
|
||||
let pair = |x: f64, flip: bool, turn: f64| {
|
||||
let a = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 4.0), Point::new(x + 10.0, 2.0)], true);
|
||||
let b = SubPath::polyline(&[Point::new(x, 6.0), Point::new(x, 10.0), Point::new(x + 4.0, 8.0)], true);
|
||||
let subpaths = if flip { vec![b, a] } else { vec![a, b] };
|
||||
let mut n = Node::path(NodeId(0), PathData::new(subpaths), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [pair(0.0, false, 0.0), pair(50.0, false, 0.0)];
|
||||
assert!(check(&laid, &[pair(0.0, true, 0.0), pair(50.0, true, 0.0)], true).is_some());
|
||||
assert!(check(&laid, &[pair(0.0, true, std::f64::consts::PI), pair(50.0, true, std::f64::consts::PI)], true).is_none());
|
||||
// A lone anchor in a path draws nothing: the same path with one matches itself.
|
||||
let dotted = |x: f64| {
|
||||
let triangle = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)], true);
|
||||
let dot = SubPath::polyline(&[Point::new(x + 3.0, 5.0)], false);
|
||||
Node::path(NodeId(0), PathData::new(vec![triangle, dot]), Default::default())
|
||||
};
|
||||
assert!(check(&[dotted(0.0), dotted(50.0)], &[dotted(0.0), dotted(50.0)], true).is_some());
|
||||
// A live blend draws more than its keys: one is compared with its drawn copy by size alone.
|
||||
let blend = |x: f64| {
|
||||
let keys = vec![Arc::new(triangle(x, 0.0)), Arc::new(triangle(x, 0.0))];
|
||||
Node::new(NodeId(0), NodeKind::Blend { children: keys, spec: Box::default() })
|
||||
};
|
||||
let expanded = |x: f64| {
|
||||
let inside = SubPath::polyline(&[Point::new(x + 3.0, 4.0), Point::new(x + 3.0, 6.0)], false);
|
||||
let inside = Node::path(NodeId(0), PathData::single(inside), Default::default());
|
||||
Node::group(NodeId(0), vec![Arc::new(triangle(x, 0.0)), Arc::new(inside)])
|
||||
};
|
||||
assert!(check(&[blend(0.0), blend(50.0)], &[expanded(0.0), expanded(50.0)], true).is_some());
|
||||
// Coordinates far out don't overflow the grid.
|
||||
let far = [square(1e300), square(-1e300)];
|
||||
let _ = how_far(&far, &[c(1e300), c(-1e300)]);
|
||||
let _ = check(&far, &[square(1e300), square(-1e300)], false);
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine running right to left, with their steps drawn pointing
|
||||
/// right: Align to Path would turn each one (keys included) a half turn, which leaves their
|
||||
/// centers and sizes as they are but not their points. A record naming Align to Path doesn't
|
||||
/// make the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_turned_as_drawn() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 100.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| triangle(20 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine 1 pt long running right to left, with 998 steps drawn
|
||||
/// unturned, so that every step sits within the tolerance of each one. Align to Path would turn
|
||||
/// each one to point left. A record naming Align to Path doesn't make the blend Align to Path,
|
||||
/// however many steps one step's place matches; a record naming Align to Page keeps it.
|
||||
#[test]
|
||||
fn the_records_orientation_is_checked_on_crowded_steps() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(11.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 1.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..1000u32).map(|i| triangle(20 + u64::from(i), 1.0 - f64::from(i) / 999.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = MAX_BLEND_OBJECTS;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups of a red square on the left and a blue one on the right, on a spine running right to
|
||||
/// left, with their steps drawn unturned: Align to Path would give each a half turn, which keeps
|
||||
/// the group's outline but trades the squares' places. A record naming Align to Path doesn't make
|
||||
/// the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_keep_each_member_where_it_is_drawn() {
|
||||
let square = |id: u64, x: f64, color: Color| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, vectorcraft_doc::Appearance::basic(Paint::solid(color), Paint::None, 0.0)))
|
||||
};
|
||||
let pair = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(1.0, 0.0, 0.0)), square(id * 10 + 1, x + 10.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(4), NodeKind::Group { children: vec![pair(1, 100.0), pair(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| pair(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
// Drawn turned, blue on the left: the blend is Align to Path, whichever orientation the
|
||||
// record names.
|
||||
let turned = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(0.0, 0.0, 1.0)), square(id * 10 + 1, x + 10.0, Color::rgb(1.0, 0.0, 0.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let steps = (0..5u32).map(|i| turned(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPath, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangles 20 pt wide and 10 pt high on a vertical spine, with their steps drawn upright: Align
|
||||
/// to Path would turn each one (keys included) a quarter turn, which leaves the centers in place
|
||||
/// but not the sizes. A record naming Align to Path doesn't make the blend Align to Path; a
|
||||
/// record naming Align to Page does.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_at_their_drawn_sizes() {
|
||||
let rect = |id: u64, y: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, y, 20.0, y + 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(10.0, 5.0), Point::new(10.0, 105.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![rect(1, 0.0), rect(2, 100.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| rect(20 + u64::from(i), f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@
|
||||
//! at None so the art keeps its own colors.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::Affine;
|
||||
use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation};
|
||||
@@ -474,6 +475,30 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result<
|
||||
Ok(BrushDraft { name: name.to_string(), kind })
|
||||
}
|
||||
|
||||
/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with
|
||||
/// their objects too: the art changes the space it is in, and no object moves over its mask.
|
||||
pub(crate) fn turn_over(art: &mut Node) {
|
||||
art.transform(Affine::scale_non_uniform(1.0, -1.0), false);
|
||||
turn_unlinked_masks(art);
|
||||
}
|
||||
|
||||
/// Turn over the art of the opacity masks in `n` that a transform of `n` leaves in place (the masks
|
||||
/// that don't move with their objects), in members and in other masks' art too.
|
||||
fn turn_unlinked_masks(n: &mut Node) {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
let linked = m.linked;
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
if linked {
|
||||
turn_unlinked_masks(art);
|
||||
} else {
|
||||
turn_over(art);
|
||||
}
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
turn_unlinked_masks(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
|
||||
/// The brushes of `drafts`, their art from the sections `art` (by name), in the brush manager's
|
||||
/// `order` (brushes it doesn't list after those it does, in the order of their objects), each
|
||||
/// kept within its ranges → the brushes and how many were left out: those whose art isn't read,
|
||||
@@ -553,7 +578,7 @@ pub(super) fn finish_brushes_within(
|
||||
DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| {
|
||||
// The side of the section with y up draws on the right of the path, and a brush
|
||||
// draws art's y (down here) on the left of the path.
|
||||
a.transform(Affine::scale_non_uniform(1.0, -1.0), false);
|
||||
turn_over(&mut a);
|
||||
if let ArtScale::BetweenGuides { start, end } = &mut brush.scale {
|
||||
// Guides that leave no art between them stretch the whole art.
|
||||
let length = a.geometric_bounds().map_or(0.0, |b| b.width());
|
||||
|
||||
@@ -21,9 +21,17 @@ const MAX_OBJECTS: usize = 100_000;
|
||||
const MAX_OBJECT: usize = 256 << 10;
|
||||
const OBJECT: &[u8] = b"/AI11Text :";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`text_frames`] has scanned an editing copy on this thread.
|
||||
pub(crate) static TEXT_FRAME_SCANS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The `/Art` path of each text object of `data` (an editing copy's document text), in art space
|
||||
/// (y up), by its story and frame. Objects without a readable path are left out.
|
||||
pub(crate) fn text_frames(data: &[u8]) -> HashMap<(u32, usize), BezPath> {
|
||||
#[cfg(test)]
|
||||
TEXT_FRAME_SCANS.set(TEXT_FRAME_SCANS.get() + 1);
|
||||
let mut out = HashMap::new();
|
||||
let mut at = 0;
|
||||
while let Some(i) = data.get(at..).and_then(|d| find(d, OBJECT)) {
|
||||
|
||||
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user