mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 08:11:41 +00:00
Merge main into feat/proof-setup-save-load
This commit is contained in:
Generated
+143
-17
@@ -508,6 +508,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit_field"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -981,7 +987,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
@@ -991,7 +997,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1033,6 +1039,36 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"craft-jpeg",
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
@@ -1090,12 +1126,23 @@ dependencies = [
|
||||
"unicode-normalization",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
"roxmltree 0.21.2",
|
||||
@@ -1105,6 +1152,15 @@ dependencies = [
|
||||
"vectorcraft-pathops 0.18.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -1203,6 +1259,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -1715,6 +1780,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exr"
|
||||
version = "1.74.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
|
||||
dependencies = [
|
||||
"bit_field",
|
||||
"half",
|
||||
"lebe",
|
||||
"miniz_oxide 0.8.9",
|
||||
"multiversion",
|
||||
"rayon-core",
|
||||
"smallvec",
|
||||
"zune-inflate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
@@ -2747,6 +2828,7 @@ dependencies = [
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png 0.18.1",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core 0.5.3",
|
||||
"zune-jpeg 0.5.15",
|
||||
@@ -3200,6 +3282,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
|
||||
|
||||
[[package]]
|
||||
name = "lebe"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
@@ -3399,6 +3487,28 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
|
||||
dependencies = [
|
||||
"multiversion-macros",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion-macros"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"target-features",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multiversion_no_op"
|
||||
version = "1.0.0"
|
||||
@@ -4349,21 +4459,21 @@ dependencies = [
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "psd"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a25f9b8cfffd65d911baf31a033239f7a0facb755faa2481575b70db5dc9195"
|
||||
dependencies = [
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pxfm"
|
||||
version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "qoi"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
@@ -5734,6 +5844,12 @@ dependencies = [
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "target-features"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
@@ -6546,6 +6662,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-proof",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
@@ -6558,7 +6675,6 @@ dependencies = [
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
"same-file",
|
||||
@@ -6734,6 +6850,7 @@ dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
"craft-pdf",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
@@ -6744,7 +6861,6 @@ dependencies = [
|
||||
"md-5",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -6785,16 +6901,16 @@ dependencies = [
|
||||
name = "vectorcraft-render"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"psd",
|
||||
"serde_json",
|
||||
"tiff",
|
||||
"unicode-general-category",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-color",
|
||||
@@ -6917,6 +7033,7 @@ dependencies = [
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -8371,6 +8488,15 @@ version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
|
||||
|
||||
[[package]]
|
||||
name = "zune-inflate"
|
||||
version = "0.2.54"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-jpeg"
|
||||
version = "0.4.21"
|
||||
|
||||
+6
-1
@@ -30,9 +30,14 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
|
||||
@@ -133,6 +133,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
|
||||
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-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-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.
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
description = "VectorCraft CAD interchange: DXF export through craft-dxf and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
+19
-4
@@ -1,4 +1,4 @@
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
|
||||
//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on
|
||||
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
|
||||
//!
|
||||
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
|
||||
@@ -15,7 +15,7 @@
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
@@ -24,7 +24,6 @@ mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
@@ -136,11 +135,27 @@ impl DxfVersion {
|
||||
self >= Self::R2004
|
||||
}
|
||||
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
|
||||
fn utf8(self) -> bool {
|
||||
pub fn utf8(self) -> bool {
|
||||
self >= Self::R2007
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DxfVersion> for craft_dxf::drawing::Format {
|
||||
fn from(v: DxfVersion) -> Self {
|
||||
match v {
|
||||
DxfVersion::R12 => Self::R12,
|
||||
DxfVersion::R13 => Self::R13,
|
||||
DxfVersion::R14 => Self::R14,
|
||||
DxfVersion::R2000 => Self::R2000,
|
||||
DxfVersion::R2004 => Self::R2004,
|
||||
DxfVersion::R2007 => Self::R2007,
|
||||
DxfVersion::R2010 => Self::R2010,
|
||||
DxfVersion::R2013 => Self::R2013,
|
||||
DxfVersion::R2018 => Self::R2018,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
|
||||
/// (with the nearest index for apps that read only the index).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
|
||||
@@ -14,8 +14,8 @@ use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
|
||||
use crate::aci::nearest_aci;
|
||||
use crate::writer::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, fixed};
|
||||
use crate::{CAP_HEIGHT, ColorDepth, DxfImage, DxfOptions, DxfOutput, MAX_NEST, Preserve, RasterFormat};
|
||||
use craft_dxf::drawing::{Codes, Drawing, EntityStyle, Handle, ImageDef, Layer, LineType, STANDARD_STYLE, fixed};
|
||||
|
||||
/// Curves are flattened to within this distance (points) where DXF needs straight segments
|
||||
/// (hatch boundaries, R12 polylines).
|
||||
@@ -543,7 +543,7 @@ impl<'a> Scene<'a> {
|
||||
o,
|
||||
to_dxf: Affine::new([k, 0.0, 0.0, -k, -r.x0 * k, r.y1 * k]),
|
||||
k,
|
||||
e: Codes::new(o.version),
|
||||
e: Codes::new(o.version.into()),
|
||||
next: fixed::FIRST_FREE,
|
||||
layers: vec![],
|
||||
layer_names: Names::with(&["0", "Defpoints"]),
|
||||
@@ -551,7 +551,7 @@ impl<'a> Scene<'a> {
|
||||
flags: LayerFlags { off: false, locked: false, plot: true },
|
||||
linetypes: vec![],
|
||||
styles: vec![],
|
||||
style_names: Names::with(&[crate::writer::STANDARD_STYLE]),
|
||||
style_names: Names::with(&[STANDARD_STYLE]),
|
||||
images: vec![],
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
@@ -579,7 +579,7 @@ impl<'a> Scene<'a> {
|
||||
let one = (self.o.scale - 1.0).abs() < 1e-12;
|
||||
let insunits = if one { crate::insunits_code(self.o.unit).unwrap_or(0) } else { 0 };
|
||||
let drawing = Drawing {
|
||||
version: self.o.version,
|
||||
version: self.o.version.into(),
|
||||
layers: self.layers,
|
||||
linetypes: self.linetypes,
|
||||
styles: self.styles,
|
||||
|
||||
@@ -1451,3 +1451,23 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data");
|
||||
let cases: [(&str, DxfVersion, Document); 2] =
|
||||
[("shapes_r12.dxf", DxfVersion::R12, shapes_doc()), ("shapes_r2018.dxf", DxfVersion::R2018, shapes_doc())];
|
||||
for (name, version, doc) in cases {
|
||||
let out = export(&doc, &DxfOptions { version, ..opts(&doc) }).unwrap();
|
||||
let got = std::str::from_utf8(&out.bytes).expect("UTF-8 DXF");
|
||||
let path = dir.join(name);
|
||||
if std::env::var_os("WRITE_DXF_GOLDENS").is_some() {
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(&path, got).unwrap();
|
||||
continue;
|
||||
}
|
||||
let expected = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
|
||||
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,674 +0,0 @@
|
||||
//! The ASCII DXF file: group codes, handles, and the sections, tables and objects around the
|
||||
//! entities. DXF R13 and later give every object a handle and subclass markers; R2000 and later
|
||||
//! add layouts and plot styles, which CAD apps expect to find.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::DxfVersion;
|
||||
|
||||
/// An object handle (written in hex).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Handle(pub u32);
|
||||
|
||||
/// The handles of the fixed objects every drawing has. Entities and table entries count up from
|
||||
/// [`FIRST_FREE`].
|
||||
pub(crate) mod fixed {
|
||||
use super::Handle;
|
||||
pub const LAYER_TABLE: Handle = Handle(0x1);
|
||||
pub const LTYPE_TABLE: Handle = Handle(0x2);
|
||||
pub const APPID_TABLE: Handle = Handle(0x3);
|
||||
pub const DIMSTYLE_TABLE: Handle = Handle(0x4);
|
||||
pub const STYLE_TABLE: Handle = Handle(0x5);
|
||||
pub const UCS_TABLE: Handle = Handle(0x6);
|
||||
pub const VIEW_TABLE: Handle = Handle(0x7);
|
||||
pub const VPORT_TABLE: Handle = Handle(0x8);
|
||||
pub const BLOCK_RECORD_TABLE: Handle = Handle(0x9);
|
||||
pub const ROOT: Handle = Handle(0xA);
|
||||
pub const GROUPS: Handle = Handle(0xB);
|
||||
pub const LAYOUTS: Handle = Handle(0xC);
|
||||
pub const MODEL_RECORD: Handle = Handle(0xD);
|
||||
pub const PAPER_RECORD: Handle = Handle(0xE);
|
||||
pub const MODEL_BLOCK: Handle = Handle(0xF);
|
||||
pub const MODEL_END: Handle = Handle(0x10);
|
||||
pub const PAPER_BLOCK: Handle = Handle(0x11);
|
||||
pub const PAPER_END: Handle = Handle(0x12);
|
||||
pub const MODEL_LAYOUT: Handle = Handle(0x13);
|
||||
pub const PAPER_LAYOUT: Handle = Handle(0x14);
|
||||
pub const ACTIVE_VPORT: Handle = Handle(0x15);
|
||||
pub const ACAD_APPID: Handle = Handle(0x16);
|
||||
pub const STANDARD_DIMSTYLE: Handle = Handle(0x17);
|
||||
pub const IMAGE_DICT: Handle = Handle(0x18);
|
||||
pub const IMAGE_VARS: Handle = Handle(0x19);
|
||||
pub const PLOT_STYLES: Handle = Handle(0x1A);
|
||||
pub const PLOT_NORMAL: Handle = Handle(0x1B);
|
||||
pub const FIRST_FREE: u32 = 0x30;
|
||||
}
|
||||
|
||||
/// A number as DXF writes it: up to 6 decimals, no trailing zeros, 0 for anything not finite.
|
||||
pub(crate) fn num(v: f64) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{v:.6}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.into() }
|
||||
}
|
||||
|
||||
/// Text as a DXF string value: one line, `^` escaped, and before DXF 2007 (which reads UTF-8)
|
||||
/// every character outside ASCII as `\U+XXXX`.
|
||||
pub(crate) fn text(s: &str, utf8: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\r' | '\n' | '\t' => out.push(' '),
|
||||
c if c.is_control() => {}
|
||||
'^' => out.push_str("^ "),
|
||||
c if !utf8 && !c.is_ascii() => match u16::try_from(u32::from(c)) {
|
||||
Ok(u) => _ = write!(out, "\\U+{u:04X}"),
|
||||
Err(_) => out.push('?'),
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Group-code/value pairs in the order they are written.
|
||||
pub(crate) struct Codes {
|
||||
pub v: DxfVersion,
|
||||
out: String,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
pub fn new(v: DxfVersion) -> Self {
|
||||
Self { v, out: String::new() }
|
||||
}
|
||||
|
||||
pub fn into_string(self) -> String {
|
||||
self.out
|
||||
}
|
||||
|
||||
pub fn append(&mut self, other: &str) {
|
||||
self.out.push_str(other);
|
||||
}
|
||||
|
||||
/// A value written as it is (names and keywords the writer itself chose).
|
||||
pub fn raw(&mut self, code: u16, value: &str) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
/// Text from the document, encoded for the version (see [`text`]).
|
||||
pub fn str(&mut self, code: u16, value: &str) {
|
||||
let t = text(value, self.v.utf8());
|
||||
self.raw(code, &t);
|
||||
}
|
||||
|
||||
pub fn int(&mut self, code: u16, value: i64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{value}");
|
||||
}
|
||||
|
||||
pub fn num(&mut self, code: u16, value: f64) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{}", num(value));
|
||||
}
|
||||
|
||||
pub fn handle(&mut self, code: u16, h: Handle) {
|
||||
_ = writeln!(self.out, "{code:>3}\n{:X}", h.0);
|
||||
}
|
||||
|
||||
/// A 2D point at `code` (x), `code + 10` (y).
|
||||
pub fn xy(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.num(code, x);
|
||||
self.num(code + 10, y);
|
||||
}
|
||||
|
||||
/// A 3D point at `code`, `code + 10`, `code + 20` (z = 0).
|
||||
pub fn xyz(&mut self, code: u16, x: f64, y: f64) {
|
||||
self.xy(code, x, y);
|
||||
self.num(code + 20, 0.0);
|
||||
}
|
||||
|
||||
/// The extrusion direction of planar entities: the z axis.
|
||||
pub fn normal(&mut self) {
|
||||
self.num(210, 0.0);
|
||||
self.num(220, 0.0);
|
||||
self.num(230, 1.0);
|
||||
}
|
||||
|
||||
/// The start of an object: its type, and from R13 its handle, owner and first subclass.
|
||||
fn object(&mut self, kind: &str, h: Handle, owner: Handle, subclass: &str) {
|
||||
self.raw(0, kind);
|
||||
if self.v.handles() {
|
||||
self.handle(if kind == "DIMSTYLE" { 105 } else { 5 }, h);
|
||||
self.handle(330, owner);
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
/// A table entry: the shared record subclass, then the table's own (from R13).
|
||||
fn record(&mut self, kind: &str, h: Handle, table: Handle, subclass: &str) {
|
||||
self.object(kind, h, table, "AcDbSymbolTableRecord");
|
||||
if self.v.handles() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, name: &str) {
|
||||
self.raw(0, "SECTION");
|
||||
self.raw(2, name);
|
||||
}
|
||||
|
||||
fn end_section(&mut self) {
|
||||
self.raw(0, "ENDSEC");
|
||||
}
|
||||
|
||||
fn table(&mut self, name: &str, h: Handle, count: usize) {
|
||||
self.raw(0, "TABLE");
|
||||
self.raw(2, name);
|
||||
if self.v.handles() {
|
||||
self.handle(5, h);
|
||||
self.raw(330, "0");
|
||||
self.raw(100, "AcDbSymbolTable");
|
||||
}
|
||||
self.int(70, count as i64);
|
||||
if name == "DIMSTYLE" && self.v.r2000() {
|
||||
self.raw(100, "AcDbDimStyleTable");
|
||||
}
|
||||
}
|
||||
|
||||
fn end_table(&mut self) {
|
||||
self.raw(0, "ENDTAB");
|
||||
}
|
||||
}
|
||||
|
||||
/// How an entity is drawn: its colour index, true colour, lineweight, linetype and transparency.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct EntityStyle {
|
||||
pub aci: u8,
|
||||
/// `0xRRGGBB` (DXF 2004 and later).
|
||||
pub rgb: Option<u32>,
|
||||
/// Hundredths of a millimetre (DXF 2000 and later).
|
||||
pub lineweight: Option<i32>,
|
||||
pub linetype: Option<String>,
|
||||
/// Opacity 0–255 (DXF 2004 and later; opaque is left out).
|
||||
pub alpha: Option<u8>,
|
||||
}
|
||||
|
||||
impl Codes {
|
||||
/// The start of an entity of `kind` owned by `owner` (model space, or a polyline for its
|
||||
/// vertices) on `layer` with its style, ending with `subclass` (none when empty).
|
||||
pub fn entity(&mut self, kind: &str, h: Handle, owner: Handle, layer: &str, style: &EntityStyle, subclass: &str) {
|
||||
self.object(kind, h, owner, "AcDbEntity");
|
||||
self.str(8, layer);
|
||||
if let Some(lt) = &style.linetype {
|
||||
self.str(6, lt);
|
||||
}
|
||||
self.int(62, i64::from(style.aci.max(1)));
|
||||
if self.v.r2000()
|
||||
&& let Some(lw) = style.lineweight
|
||||
{
|
||||
self.int(370, i64::from(lw));
|
||||
}
|
||||
if self.v.true_color() {
|
||||
if let Some(rgb) = style.rgb {
|
||||
self.int(420, i64::from(rgb));
|
||||
}
|
||||
if let Some(a) = style.alpha {
|
||||
self.int(440, 0x0200_0000 | i64::from(a));
|
||||
}
|
||||
}
|
||||
if self.v.handles() && !subclass.is_empty() {
|
||||
self.raw(100, subclass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A DXF layer.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Layer {
|
||||
pub name: String,
|
||||
pub aci: u8,
|
||||
/// Switched off (a hidden layer).
|
||||
pub off: bool,
|
||||
pub locked: bool,
|
||||
/// Plotted (printable).
|
||||
pub plot: bool,
|
||||
}
|
||||
|
||||
/// A dash pattern: dash, gap, dash… lengths in drawing units.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct LineType {
|
||||
pub name: String,
|
||||
pub pattern: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A placed image file and the image entities that show it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ImageDef {
|
||||
pub name: String,
|
||||
pub size: (u32, u32),
|
||||
pub handle: Handle,
|
||||
/// `(reactor, image entity)` per image entity.
|
||||
pub reactors: Vec<(Handle, Handle)>,
|
||||
}
|
||||
|
||||
/// Everything around the entities, collected while they were written.
|
||||
pub(crate) struct Drawing {
|
||||
pub version: DxfVersion,
|
||||
pub layers: Vec<Layer>,
|
||||
pub linetypes: Vec<LineType>,
|
||||
/// Text styles: (style name, font family).
|
||||
pub styles: Vec<(String, String)>,
|
||||
pub images: Vec<ImageDef>,
|
||||
/// The entities' group codes.
|
||||
pub entities: String,
|
||||
/// `[x0, y0, x1, y1]` of everything written (drawing units).
|
||||
pub extents: [f64; 4],
|
||||
/// The export region (drawing units).
|
||||
pub limits: [f64; 4],
|
||||
/// `$INSUNITS`.
|
||||
pub insunits: u8,
|
||||
pub metric: bool,
|
||||
/// The next free handle.
|
||||
pub next: u32,
|
||||
}
|
||||
|
||||
/// The text style every drawing has.
|
||||
pub(crate) const STANDARD_STYLE: &str = "Standard";
|
||||
|
||||
impl Drawing {
|
||||
/// The whole file.
|
||||
pub fn write(self) -> String {
|
||||
let v = self.version;
|
||||
let mut c = Codes::new(v);
|
||||
// Table entries get the handles after the entities'.
|
||||
let mut next = self.next;
|
||||
let mut take = |n: usize| {
|
||||
let start = next;
|
||||
next = next.saturating_add(u32::try_from(n).unwrap_or(u32::MAX));
|
||||
start
|
||||
};
|
||||
let ltype_base = take(3 + self.linetypes.len());
|
||||
let layer_base = take(1 + self.layers.len());
|
||||
let style_base = take(1 + self.styles.len());
|
||||
self.header(&mut c, next);
|
||||
if v.handles() {
|
||||
self.classes(&mut c);
|
||||
}
|
||||
c.section("TABLES");
|
||||
self.vport(&mut c);
|
||||
self.ltypes(&mut c, ltype_base);
|
||||
self.layer_table(&mut c, layer_base);
|
||||
self.style_table(&mut c, style_base);
|
||||
if v.handles() {
|
||||
for (name, h) in [("VIEW", fixed::VIEW_TABLE), ("UCS", fixed::UCS_TABLE)] {
|
||||
c.table(name, h, 0);
|
||||
c.end_table();
|
||||
}
|
||||
c.table("APPID", fixed::APPID_TABLE, 1);
|
||||
c.record("APPID", fixed::ACAD_APPID, fixed::APPID_TABLE, "AcDbRegAppTableRecord");
|
||||
c.raw(2, "ACAD");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("DIMSTYLE", fixed::DIMSTYLE_TABLE, 1);
|
||||
c.record("DIMSTYLE", fixed::STANDARD_DIMSTYLE, fixed::DIMSTYLE_TABLE, "AcDbDimStyleTableRecord");
|
||||
c.raw(2, "Standard");
|
||||
c.int(70, 0);
|
||||
c.end_table();
|
||||
c.table("BLOCK_RECORD", fixed::BLOCK_RECORD_TABLE, 2);
|
||||
for (name, h, layout) in
|
||||
[("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_LAYOUT), ("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_LAYOUT)]
|
||||
{
|
||||
c.record("BLOCK_RECORD", h, fixed::BLOCK_RECORD_TABLE, "AcDbBlockTableRecord");
|
||||
c.raw(2, name);
|
||||
if v.r2000() {
|
||||
c.handle(340, layout);
|
||||
c.int(70, 0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
c.section("BLOCKS");
|
||||
for (name, record, begin, end) in [
|
||||
("*Model_Space", fixed::MODEL_RECORD, fixed::MODEL_BLOCK, fixed::MODEL_END),
|
||||
("*Paper_Space", fixed::PAPER_RECORD, fixed::PAPER_BLOCK, fixed::PAPER_END),
|
||||
] {
|
||||
c.object("BLOCK", begin, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockBegin");
|
||||
c.raw(2, name);
|
||||
c.int(70, 0);
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
c.raw(3, name);
|
||||
c.raw(1, "");
|
||||
c.object("ENDBLK", end, record, "AcDbEntity");
|
||||
c.raw(8, "0");
|
||||
c.raw(100, "AcDbBlockEnd");
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
c.section("ENTITIES");
|
||||
c.append(&self.entities);
|
||||
c.end_section();
|
||||
if v.handles() {
|
||||
self.objects(&mut c);
|
||||
}
|
||||
c.raw(0, "EOF");
|
||||
c.into_string()
|
||||
}
|
||||
|
||||
fn header(&self, c: &mut Codes, handseed: u32) {
|
||||
let v = self.version;
|
||||
let var = |c: &mut Codes, name: &str| c.raw(9, name);
|
||||
c.section("HEADER");
|
||||
var(c, "$ACADVER");
|
||||
c.raw(1, v.acadver());
|
||||
var(c, "$DWGCODEPAGE");
|
||||
c.raw(3, "ANSI_1252");
|
||||
var(c, "$INSBASE");
|
||||
c.xyz(10, 0.0, 0.0);
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
var(c, "$EXTMIN");
|
||||
c.xyz(10, x0, y0);
|
||||
var(c, "$EXTMAX");
|
||||
c.xyz(10, x1, y1);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
var(c, "$LIMMIN");
|
||||
c.xy(10, lx0, ly0);
|
||||
var(c, "$LIMMAX");
|
||||
c.xy(10, lx1, ly1);
|
||||
if v.r2000() {
|
||||
var(c, "$LWDISPLAY");
|
||||
c.int(290, 1);
|
||||
var(c, "$INSUNITS");
|
||||
c.int(70, i64::from(self.insunits));
|
||||
var(c, "$MEASUREMENT");
|
||||
c.int(70, i64::from(self.metric));
|
||||
}
|
||||
if v.handles() {
|
||||
var(c, "$HANDSEED");
|
||||
c.handle(5, Handle(handseed));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
fn classes(&self, c: &mut Codes) {
|
||||
let mut classes: Vec<(&str, &str, &str, i64, bool)> = vec![];
|
||||
if self.version.r2000() {
|
||||
classes.extend([
|
||||
("ACDBDICTIONARYWDFLT", "AcDbDictionaryWithDefault", "ObjectDBX Classes", 0, false),
|
||||
("ACDBPLACEHOLDER", "AcDbPlaceHolder", "ObjectDBX Classes", 0, false),
|
||||
("LAYOUT", "AcDbLayout", "ObjectDBX Classes", 0, false),
|
||||
]);
|
||||
}
|
||||
if !self.images.is_empty() {
|
||||
classes.extend([
|
||||
("RASTERVARIABLES", "AcDbRasterVariables", "ISM", 0, false),
|
||||
("IMAGE", "AcDbRasterImage", "ISM", 2175, true),
|
||||
("IMAGEDEF", "AcDbRasterImageDef", "ISM", 0, false),
|
||||
("IMAGEDEF_REACTOR", "AcDbRasterImageDefReactor", "ISM", 1, false),
|
||||
]);
|
||||
}
|
||||
c.section("CLASSES");
|
||||
for (name, cpp, app, flags, entity) in classes {
|
||||
c.raw(0, "CLASS");
|
||||
c.raw(1, name);
|
||||
c.raw(2, cpp);
|
||||
c.raw(3, app);
|
||||
c.int(90, flags);
|
||||
if self.version.true_color() {
|
||||
c.int(91, 0);
|
||||
}
|
||||
c.int(280, 0);
|
||||
c.int(281, i64::from(entity));
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// The active viewport, zoomed to the drawing's extents.
|
||||
fn vport(&self, c: &mut Codes) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.table("VPORT", fixed::VPORT_TABLE, 1);
|
||||
c.record("VPORT", fixed::ACTIVE_VPORT, fixed::VPORT_TABLE, "AcDbViewportTableRecord");
|
||||
c.raw(2, if self.version.handles() { "*Active" } else { "*ACTIVE" });
|
||||
c.int(70, 0);
|
||||
c.xy(10, 0.0, 0.0);
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.xy(12, (x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
c.xy(13, 0.0, 0.0);
|
||||
c.xy(14, 1.0, 1.0);
|
||||
c.xy(15, 10.0, 10.0);
|
||||
// The view direction looks down the z axis: (0, 0, 1), each code once.
|
||||
c.xy(16, 0.0, 0.0);
|
||||
c.num(36, 1.0);
|
||||
c.xyz(17, 0.0, 0.0);
|
||||
let (w, h) = ((x1 - x0).abs(), (y1 - y0).abs());
|
||||
// The view's height, with a margin; its width follows from the aspect ratio.
|
||||
c.num(40, (h.max(w / 1.5) * 1.1).max(1.0));
|
||||
c.num(41, 1.5);
|
||||
c.num(42, 50.0);
|
||||
c.num(43, 0.0);
|
||||
c.num(44, 0.0);
|
||||
c.num(50, 0.0);
|
||||
c.num(51, 0.0);
|
||||
for (code, value) in [(71, 0), (72, 1000), (73, 1), (74, 3), (75, 0), (76, 0), (77, 0), (78, 0)] {
|
||||
c.int(code, value);
|
||||
}
|
||||
if self.version.r2000() {
|
||||
c.int(281, 0);
|
||||
c.int(65, 0);
|
||||
c.num(146, 0.0);
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn ltypes(&self, c: &mut Codes, base: u32) {
|
||||
c.table("LTYPE", fixed::LTYPE_TABLE, 3 + self.linetypes.len());
|
||||
let solid = [("ByBlock", ""), ("ByLayer", ""), ("Continuous", "Solid line")];
|
||||
let rows = solid.iter().map(|(n, d)| (*n, *d, &[][..])).chain(self.linetypes.iter().map(|l| (l.name.as_str(), "", l.pattern.as_slice())));
|
||||
for (i, (name, desc, pattern)) in rows.enumerate() {
|
||||
c.record("LTYPE", Handle(base.saturating_add(i as u32)), fixed::LTYPE_TABLE, "AcDbLinetypeTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.str(3, if pattern.is_empty() { desc } else { "Dashed" });
|
||||
c.int(72, 65);
|
||||
c.int(73, pattern.len() as i64);
|
||||
c.num(40, pattern.iter().map(|v| v.abs()).sum());
|
||||
for v in pattern {
|
||||
c.num(49, *v);
|
||||
if self.version.handles() {
|
||||
c.int(74, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn layer_table(&self, c: &mut Codes, base: u32) {
|
||||
let zero = Layer { name: "0".into(), aci: 7, off: false, locked: false, plot: true };
|
||||
c.table("LAYER", fixed::LAYER_TABLE, 1 + self.layers.len());
|
||||
for (i, l) in std::iter::once(&zero).chain(&self.layers).enumerate() {
|
||||
c.record("LAYER", Handle(base.saturating_add(i as u32)), fixed::LAYER_TABLE, "AcDbLayerTableRecord");
|
||||
c.str(2, &l.name);
|
||||
c.int(70, if l.locked { 4 } else { 0 });
|
||||
// A negative colour switches the layer off.
|
||||
let aci = i64::from(l.aci.max(1));
|
||||
c.int(62, if l.off { -aci } else { aci });
|
||||
c.raw(6, "Continuous");
|
||||
if self.version.r2000() {
|
||||
c.int(290, i64::from(l.plot));
|
||||
c.int(370, -3);
|
||||
c.handle(390, fixed::PLOT_NORMAL);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn style_table(&self, c: &mut Codes, base: u32) {
|
||||
c.table("STYLE", fixed::STYLE_TABLE, 1 + self.styles.len());
|
||||
let standard = (STANDARD_STYLE.to_string(), String::new());
|
||||
for (i, (name, family)) in std::iter::once(&standard).chain(&self.styles).enumerate() {
|
||||
c.record("STYLE", Handle(base.saturating_add(i as u32)), fixed::STYLE_TABLE, "AcDbTextStyleTableRecord");
|
||||
c.str(2, name);
|
||||
c.int(70, 0);
|
||||
c.num(40, 0.0);
|
||||
c.num(41, 1.0);
|
||||
c.num(50, 0.0);
|
||||
c.int(71, 0);
|
||||
c.num(42, 2.5);
|
||||
// The font file; from 2000 the family name too, which is how CAD apps find a TrueType font.
|
||||
if family.is_empty() {
|
||||
c.raw(3, "txt");
|
||||
} else {
|
||||
c.str(3, &format!("{family}.ttf"));
|
||||
}
|
||||
c.raw(4, "");
|
||||
if self.version.r2000() && !family.is_empty() {
|
||||
c.raw(1001, "ACAD");
|
||||
c.str(1000, family);
|
||||
c.int(1071, 0);
|
||||
}
|
||||
}
|
||||
c.end_table();
|
||||
}
|
||||
|
||||
fn objects(&self, c: &mut Codes) {
|
||||
let v = self.version;
|
||||
let images = !self.images.is_empty();
|
||||
c.section("OBJECTS");
|
||||
let dict = |c: &mut Codes, h: Handle, owner: Handle, entries: &[(&str, Handle)]| {
|
||||
c.object("DICTIONARY", h, owner, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
for (name, e) in entries {
|
||||
c.str(3, name);
|
||||
c.handle(350, *e);
|
||||
}
|
||||
};
|
||||
let mut root = vec![("ACAD_GROUP", fixed::GROUPS)];
|
||||
if images {
|
||||
root.extend([("ACAD_IMAGE_DICT", fixed::IMAGE_DICT), ("ACAD_IMAGE_VARS", fixed::IMAGE_VARS)]);
|
||||
}
|
||||
if v.r2000() {
|
||||
root.extend([("ACAD_LAYOUT", fixed::LAYOUTS), ("ACAD_PLOTSTYLENAME", fixed::PLOT_STYLES)]);
|
||||
}
|
||||
dict(c, fixed::ROOT, Handle(0), &root);
|
||||
dict(c, fixed::GROUPS, fixed::ROOT, &[]);
|
||||
if v.r2000() {
|
||||
dict(c, fixed::LAYOUTS, fixed::ROOT, &[("Layout1", fixed::PAPER_LAYOUT), ("Model", fixed::MODEL_LAYOUT)]);
|
||||
c.object("ACDBDICTIONARYWDFLT", fixed::PLOT_STYLES, fixed::ROOT, "AcDbDictionary");
|
||||
c.int(281, 1);
|
||||
c.raw(3, "Normal");
|
||||
c.handle(350, fixed::PLOT_NORMAL);
|
||||
c.raw(100, "AcDbDictionaryWithDefault");
|
||||
c.handle(340, fixed::PLOT_NORMAL);
|
||||
// A placeholder has no data and no subclass marker of its own.
|
||||
c.raw(0, "ACDBPLACEHOLDER");
|
||||
c.handle(5, fixed::PLOT_NORMAL);
|
||||
c.handle(330, fixed::PLOT_STYLES);
|
||||
self.layout(c, fixed::MODEL_LAYOUT, "Model", 0, fixed::MODEL_RECORD);
|
||||
self.layout(c, fixed::PAPER_LAYOUT, "Layout1", 1, fixed::PAPER_RECORD);
|
||||
}
|
||||
if images {
|
||||
c.object("RASTERVARIABLES", fixed::IMAGE_VARS, fixed::ROOT, "AcDbRasterVariables");
|
||||
c.int(90, 0);
|
||||
c.int(70, 0);
|
||||
c.int(71, 1);
|
||||
c.int(72, 0);
|
||||
let entries: Vec<(&str, Handle)> = self.images.iter().map(|i| (i.name.as_str(), i.handle)).collect();
|
||||
dict(c, fixed::IMAGE_DICT, fixed::ROOT, &entries);
|
||||
for img in &self.images {
|
||||
c.raw(0, "IMAGEDEF");
|
||||
c.handle(5, img.handle);
|
||||
c.raw(102, "{ACAD_REACTORS");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
for (reactor, _) in &img.reactors {
|
||||
c.handle(330, *reactor);
|
||||
}
|
||||
c.raw(102, "}");
|
||||
c.handle(330, fixed::IMAGE_DICT);
|
||||
c.raw(100, "AcDbRasterImageDef");
|
||||
c.int(90, 0);
|
||||
c.str(1, &img.name);
|
||||
c.xy(10, f64::from(img.size.0), f64::from(img.size.1));
|
||||
c.xy(11, 1.0, 1.0);
|
||||
c.int(280, 1);
|
||||
c.int(281, 0);
|
||||
for (reactor, image) in &img.reactors {
|
||||
c.object("IMAGEDEF_REACTOR", *reactor, *image, "AcDbRasterImageDefReactor");
|
||||
c.int(90, 2);
|
||||
c.handle(330, *image);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.end_section();
|
||||
}
|
||||
|
||||
/// A layout (DXF 2000 and later): its plot settings, then the layout itself.
|
||||
fn layout(&self, c: &mut Codes, h: Handle, name: &str, tab: i64, record: Handle) {
|
||||
let [x0, y0, x1, y1] = self.extents;
|
||||
c.object("LAYOUT", h, fixed::LAYOUTS, "AcDbPlotSettings");
|
||||
c.raw(1, "");
|
||||
c.raw(2, "none_device");
|
||||
c.raw(4, "");
|
||||
c.raw(6, "");
|
||||
for code in 40..=49 {
|
||||
c.num(code, 0.0);
|
||||
}
|
||||
c.num(140, 0.0);
|
||||
c.num(141, 0.0);
|
||||
c.num(142, 1.0);
|
||||
c.num(143, 1.0);
|
||||
// Plot flags; 1024 marks the model space layout.
|
||||
c.int(70, if record == fixed::MODEL_RECORD { 688 | 1024 } else { 688 });
|
||||
c.int(72, 1);
|
||||
c.int(73, 0);
|
||||
c.int(74, 5);
|
||||
c.raw(7, "");
|
||||
c.int(75, 16);
|
||||
if self.version.true_color() {
|
||||
// Shade plot mode (as displayed), resolution level (normal) and custom DPI.
|
||||
c.int(76, 0);
|
||||
c.int(77, 2);
|
||||
c.int(78, 300);
|
||||
}
|
||||
c.num(147, 1.0);
|
||||
// The paper image origin is 148 (x) and 149 (y), not a point at 148 and 158.
|
||||
c.num(148, 0.0);
|
||||
c.num(149, 0.0);
|
||||
c.raw(100, "AcDbLayout");
|
||||
c.raw(1, name);
|
||||
c.int(70, 1);
|
||||
c.int(71, tab);
|
||||
let [lx0, ly0, lx1, ly1] = self.limits;
|
||||
c.xy(10, lx0, ly0);
|
||||
c.xy(11, lx1, ly1);
|
||||
c.xyz(12, 0.0, 0.0);
|
||||
c.xyz(14, x0, y0);
|
||||
c.xyz(15, x1, y1);
|
||||
c.num(146, 0.0);
|
||||
c.xyz(13, 0.0, 0.0);
|
||||
c.xyz(16, 1.0, 0.0);
|
||||
c.xyz(17, 0.0, 1.0);
|
||||
c.int(76, 1);
|
||||
c.handle(330, record);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_and_text_are_written_plainly() {
|
||||
assert_eq!(num(1.5), "1.5");
|
||||
assert_eq!(num(-0.0000001), "0");
|
||||
assert_eq!(num(2.0), "2");
|
||||
assert_eq!(num(f64::NAN), "0");
|
||||
assert_eq!(text("a^b\nc", true), "a^ b c");
|
||||
assert_eq!(text("Größe 😀", false), "Gr\\U+00F6\\U+00DFe ?");
|
||||
assert_eq!(text("Größe", true), "Größe");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
HEADER
|
||||
9
|
||||
$ACADVER
|
||||
1
|
||||
AC1009
|
||||
9
|
||||
$DWGCODEPAGE
|
||||
3
|
||||
ANSI_1252
|
||||
9
|
||||
$INSBASE
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMIN
|
||||
10
|
||||
10
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
9
|
||||
$EXTMAX
|
||||
10
|
||||
180
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
9
|
||||
$LIMMIN
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
9
|
||||
$LIMMAX
|
||||
10
|
||||
200
|
||||
20
|
||||
100
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
TABLES
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
VPORT
|
||||
70
|
||||
1
|
||||
0
|
||||
VPORT
|
||||
2
|
||||
*ACTIVE
|
||||
70
|
||||
0
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
11
|
||||
1
|
||||
21
|
||||
1
|
||||
12
|
||||
95
|
||||
22
|
||||
55
|
||||
13
|
||||
0
|
||||
23
|
||||
0
|
||||
14
|
||||
1
|
||||
24
|
||||
1
|
||||
15
|
||||
10
|
||||
25
|
||||
10
|
||||
16
|
||||
0
|
||||
26
|
||||
0
|
||||
36
|
||||
1
|
||||
17
|
||||
0
|
||||
27
|
||||
0
|
||||
37
|
||||
0
|
||||
40
|
||||
124.666667
|
||||
41
|
||||
1.5
|
||||
42
|
||||
50
|
||||
43
|
||||
0
|
||||
44
|
||||
0
|
||||
50
|
||||
0
|
||||
51
|
||||
0
|
||||
71
|
||||
0
|
||||
72
|
||||
1000
|
||||
73
|
||||
1
|
||||
74
|
||||
3
|
||||
75
|
||||
0
|
||||
76
|
||||
0
|
||||
77
|
||||
0
|
||||
78
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LTYPE
|
||||
70
|
||||
3
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByBlock
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
ByLayer
|
||||
70
|
||||
0
|
||||
3
|
||||
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
LTYPE
|
||||
2
|
||||
Continuous
|
||||
70
|
||||
0
|
||||
3
|
||||
Solid line
|
||||
72
|
||||
65
|
||||
73
|
||||
0
|
||||
40
|
||||
0
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
LAYER
|
||||
70
|
||||
2
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
0
|
||||
70
|
||||
0
|
||||
62
|
||||
7
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
LAYER
|
||||
2
|
||||
LAYER_1
|
||||
70
|
||||
0
|
||||
62
|
||||
171
|
||||
6
|
||||
Continuous
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
TABLE
|
||||
2
|
||||
STYLE
|
||||
70
|
||||
1
|
||||
0
|
||||
STYLE
|
||||
2
|
||||
Standard
|
||||
70
|
||||
0
|
||||
40
|
||||
0
|
||||
41
|
||||
1
|
||||
50
|
||||
0
|
||||
71
|
||||
0
|
||||
42
|
||||
2.5
|
||||
3
|
||||
txt
|
||||
4
|
||||
|
||||
0
|
||||
ENDTAB
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
SECTION
|
||||
2
|
||||
ENTITIES
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
1
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
1
|
||||
41
|
||||
1
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
90
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
110
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
10
|
||||
10
|
||||
20
|
||||
40
|
||||
30
|
||||
0
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
7
|
||||
0
|
||||
POLYLINE
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
66
|
||||
1
|
||||
10
|
||||
0
|
||||
20
|
||||
0
|
||||
30
|
||||
0
|
||||
70
|
||||
1
|
||||
40
|
||||
2
|
||||
41
|
||||
2
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
120
|
||||
20
|
||||
50
|
||||
30
|
||||
0
|
||||
42
|
||||
-2.414214
|
||||
0
|
||||
VERTEX
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
10
|
||||
150
|
||||
20
|
||||
20
|
||||
30
|
||||
0
|
||||
42
|
||||
-0.414214
|
||||
0
|
||||
SEQEND
|
||||
8
|
||||
LAYER_1
|
||||
62
|
||||
5
|
||||
0
|
||||
ENDSEC
|
||||
0
|
||||
EOF
|
||||
File diff suppressed because it is too large
Load Diff
+17
-3
@@ -664,9 +664,6 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
|
||||
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
|
||||
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
|
||||
for (i, chunk) in chunks.iter().enumerate() {
|
||||
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
|
||||
@@ -676,6 +673,23 @@ pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
|
||||
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
|
||||
segments.extend_from_slice(chunk);
|
||||
}
|
||||
with_icc_segments(bytes, segments)
|
||||
}
|
||||
|
||||
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
|
||||
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
|
||||
/// segments before the scan can't be read.
|
||||
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
with_icc_segments(bytes, vec![])
|
||||
}
|
||||
|
||||
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
|
||||
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
|
||||
/// their segments before the scan can't be read.
|
||||
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
|
||||
if !bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() + segments.len());
|
||||
out.extend_from_slice(&[0xFF, 0xD8]);
|
||||
let mut icc_segments = Some(segments);
|
||||
|
||||
+39
-4
@@ -1121,10 +1121,12 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool {
|
||||
stroke_contains(&path.to_bezpath(), 0.0, tol, p)
|
||||
}
|
||||
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]).
|
||||
/// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art
|
||||
/// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and
|
||||
/// nothing more is tested once the limit is used up.
|
||||
fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
// Hidden art does not hit.
|
||||
if !n.visible {
|
||||
if !n.visible || ArtWalk::charged() && !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
// Nor art whose reach does not hold `p`, as in [`may_hit`]: a blend's steps far from `p` are
|
||||
@@ -1257,8 +1259,12 @@ struct FindPart<'a> {
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each
|
||||
/// object it visits inside `n` from the [`ArtWalk`] limit.
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols))
|
||||
let placed = self.art.place(n, whole)?;
|
||||
let _charged = ArtWalk::charge();
|
||||
hit_any(&placed, self.p, opt, self.symbols)
|
||||
}
|
||||
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
@@ -1268,7 +1274,7 @@ impl FindPart<'_> {
|
||||
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
|
||||
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
@@ -1277,6 +1283,9 @@ impl FindPart<'_> {
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
if !ArtWalk::take(1) {
|
||||
return None;
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
@@ -1370,6 +1379,8 @@ thread_local! {
|
||||
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
|
||||
/// `None` outside one.
|
||||
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// Whether [`hit_any`] is testing symbol art that [`FindPart`] placed ([`ArtWalk::charge`]).
|
||||
static ART_WALK_CHARGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1420,6 +1431,19 @@ impl ArtWalk {
|
||||
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
|
||||
rest.is_some()
|
||||
}
|
||||
|
||||
/// While the guard lives, each object [`hit_any`] visits takes one object from what is left:
|
||||
/// [`FindPart`] holds one while it tests a placed object of symbol art, so that the members of an
|
||||
/// Intertwine group, and the objects of groups nested deeper than
|
||||
/// [`crate::symbol_overrides::MAX_PATH_DEPTH`], count toward the limit.
|
||||
fn charge() -> ArtWalkCharge {
|
||||
ArtWalkCharge { was: ART_WALK_CHARGED.replace(true) }
|
||||
}
|
||||
|
||||
/// Does [`hit_any`] take the objects it visits from what is left ([`Self::charge`])?
|
||||
fn charged() -> bool {
|
||||
ART_WALK_CHARGED.get()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ArtWalk {
|
||||
@@ -1430,6 +1454,17 @@ impl Drop for ArtWalk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard of [`ArtWalk::charge`].
|
||||
struct ArtWalkCharge {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl Drop for ArtWalkCharge {
|
||||
fn drop(&mut self) {
|
||||
ART_WALK_CHARGED.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
|
||||
@@ -2140,6 +2140,37 @@ fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit(
|
||||
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
|
||||
}
|
||||
|
||||
/// The members of an Intertwine group in symbol art count toward the art walk's limit of objects
|
||||
/// for a click, as the members of a plain group do. A click on a member's path past the instance's
|
||||
/// box is still found within the limit.
|
||||
#[test]
|
||||
fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_limit() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// A clip group whose clipping region `test.move` moves to 100..200 × 0..100, past the 0..100
|
||||
// box, over an Intertwine group of 200 squares at 140..160 × 40..60.
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, _) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let squares = (0..200)
|
||||
.map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(140.0, 40.0, 160.0, 60.0)), Appearance::default_art())))
|
||||
.collect();
|
||||
let woven = Arc::new(Node::new(d.alloc_id(), NodeKind::Intertwine { children: squares }));
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), woven]);
|
||||
clip.set_clips(true);
|
||||
group_symbol(&mut d, "Woven", vec![Arc::new(clip)]);
|
||||
let inst = instance_of(&mut d, "Woven");
|
||||
let id = inst.id;
|
||||
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
let opt = HitOptions { path_only: true, ..HitOptions::default() };
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
// Inside the squares and away from their paths, every member is tested and none is hit.
|
||||
let (hit, leaves, _) = with_art_limit(100, || at(150.0));
|
||||
assert_eq!(hit, None);
|
||||
assert!(leaves <= 100, "{leaves} leaves tested");
|
||||
assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
@@ -18,8 +18,8 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
|
||||
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
|
||||
@@ -180,6 +180,18 @@ pub struct CharStyle {
|
||||
/// these characters are drawn in, whatever digits were typed.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub digits: Digits,
|
||||
/// Adjust Horizontal Diacritic Position (Character panel, Middle Eastern options): the font's
|
||||
/// mark glyphs among these characters (GDEF class 3, such as Arabic harakat and Hebrew points)
|
||||
/// move right by a positive value and left by a negative one, relative to their letters, in
|
||||
/// 1/1000 em of the size, from -[`MAX_DIACRITIC_POSITION`] to [`MAX_DIACRITIC_POSITION`].
|
||||
/// Saved only when not 0.
|
||||
/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=549>
|
||||
#[serde(default, rename = "diacriticHorizontal", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_horizontal: f64,
|
||||
/// Adjust Vertical Diacritic Position: the mark glyphs move up by a positive value and down by
|
||||
/// a negative one, as [`Self::diacritic_horizontal`] moves them across.
|
||||
#[serde(default, rename = "diacriticVertical", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub diacritic_vertical: f64,
|
||||
/// Font height reference (Character panel menu › Show Font Height Options): the height of the
|
||||
/// font that [`Self::size`] measures, the em box by default.
|
||||
#[serde(default, rename = "fontHeightReference", skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -553,6 +565,10 @@ pub const MAX_AKI: f64 = 1000.0;
|
||||
/// The largest Tsume ([`CharStyle::tsume`]), in percent: all the blank space beside the ink.
|
||||
pub const MAX_TSUME: f64 = 100.0;
|
||||
|
||||
/// The largest Adjust Horizontal or Vertical Diacritic Position either way
|
||||
/// ([`CharStyle::diacritic_horizontal`]), in 1/1000 em: one em.
|
||||
pub const MAX_DIACRITIC_POSITION: f64 = 1000.0;
|
||||
|
||||
/// The number of lines a warichu block may be stacked on ([`CharStyle::warichu_lines`]).
|
||||
pub const WARICHU_LINES: std::ops::RangeInclusive<u8> = 1..=6;
|
||||
|
||||
@@ -684,6 +700,8 @@ impl Default for CharStyle {
|
||||
warichu_align: WarichuAlign::Auto,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
diacritic_horizontal: 0.0,
|
||||
diacritic_vertical: 0.0,
|
||||
font_height_reference: FontHeightReference::EmBox,
|
||||
no_break: false,
|
||||
language: None,
|
||||
@@ -707,7 +725,8 @@ impl CharStyle {
|
||||
/// same way. The Warichu Settings Lines and Scale
|
||||
/// are kept to [`WARICHU_LINES`] and [`WARICHU_SCALE`]; a gap or scale that is not a number becomes its default. The gap is kept to 0 to
|
||||
/// [`crate::MAX_COORD`], as the baseline shift is, since a scaled type object holds it in its
|
||||
/// own units.
|
||||
/// own units. The Adjust Horizontal and Vertical Diacritic Positions are kept within
|
||||
/// [`MAX_DIACRITIC_POSITION`] either way, and one that is not a number becomes 0.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
@@ -723,6 +742,9 @@ impl CharStyle {
|
||||
self.aki_left = aki(self.aki_left);
|
||||
self.aki_right = aki(self.aki_right);
|
||||
self.tsume = if self.tsume.is_nan() { 0.0 } else { self.tsume.clamp(0.0, MAX_TSUME) };
|
||||
let diacritic = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION) };
|
||||
self.diacritic_horizontal = diacritic(self.diacritic_horizontal);
|
||||
self.diacritic_vertical = diacritic(self.diacritic_vertical);
|
||||
self.warichu_lines = self.warichu_lines.clamp(*WARICHU_LINES.start(), *WARICHU_LINES.end());
|
||||
self.warichu_gap = if self.warichu_gap.is_nan() { default.warichu_gap } else { self.warichu_gap.clamp(0.0, crate::MAX_COORD) };
|
||||
self.warichu_scale =
|
||||
|
||||
@@ -511,6 +511,8 @@ impl crate::Document {
|
||||
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
|
||||
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
|
||||
st.tsume = num("tsume").unwrap_or(st.tsume);
|
||||
st.diacritic_horizontal = num("diacriticHorizontal").unwrap_or(st.diacritic_horizontal);
|
||||
st.diacritic_vertical = num("diacriticVertical").unwrap_or(st.diacritic_vertical);
|
||||
st.warichu_gap = num("warichuGap").unwrap_or(st.warichu_gap);
|
||||
st.warichu_scale = num("warichuScale").unwrap_or(st.warichu_scale);
|
||||
st.keep_dimensions_in_range();
|
||||
@@ -537,6 +539,8 @@ impl crate::Document {
|
||||
("akiLeft", Some(st.aki_left)),
|
||||
("akiRight", Some(st.aki_right)),
|
||||
("tsume", Some(st.tsume)),
|
||||
("diacriticHorizontal", Some(st.diacritic_horizontal)),
|
||||
("diacriticVertical", Some(st.diacritic_vertical)),
|
||||
("leading", st.leading),
|
||||
];
|
||||
for (k, v) in kept {
|
||||
|
||||
@@ -129,6 +129,42 @@ fn insert_aki_is_saved_only_when_set() {
|
||||
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position are 0 by default and saved only when not 0,
|
||||
/// each on its own; styles written before them read as 0, and a value out of range from a file is
|
||||
/// kept within one em either way.
|
||||
#[test]
|
||||
fn diacritic_positions_are_saved_only_when_set() {
|
||||
let st = CharStyle::default();
|
||||
assert_eq!((st.diacritic_horizontal, st.diacritic_vertical), (0.0, 0.0));
|
||||
let saved = serde_json::to_value(&st).unwrap();
|
||||
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
|
||||
for set in [
|
||||
CharStyle { diacritic_horizontal: -250.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_vertical: 500.0, ..CharStyle::default() },
|
||||
CharStyle { diacritic_horizontal: 12.5, diacritic_vertical: -1000.0, ..CharStyle::default() },
|
||||
] {
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved.get("diacriticHorizontal").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_horizontal);
|
||||
assert_eq!(saved.get("diacriticVertical").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.diacritic_vertical);
|
||||
assert_eq!(saved.get("diacriticHorizontal").is_some(), set.diacritic_horizontal != 0.0);
|
||||
assert_eq!(saved.get("diacriticVertical").is_some(), set.diacritic_vertical != 0.0);
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
|
||||
}
|
||||
let mut damaged = CharStyle { diacritic_horizontal: -4000.0, diacritic_vertical: 4000.0, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (-MAX_DIACRITIC_POSITION, MAX_DIACRITIC_POSITION));
|
||||
let mut damaged = CharStyle { diacritic_horizontal: f64::NAN, diacritic_vertical: f64::NEG_INFINITY, ..CharStyle::default() };
|
||||
damaged.keep_dimensions_in_range();
|
||||
assert_eq!((damaged.diacritic_horizontal, damaged.diacritic_vertical), (0.0, -MAX_DIACRITIC_POSITION));
|
||||
// A character style from a file is kept in range the same way.
|
||||
let mut d = crate::Document::new(100.0, 100.0);
|
||||
let attrs = serde_json::json!({"diacriticHorizontal": 5000, "diacriticVertical": -5000});
|
||||
d.char_styles.push(TextStyleDef { name: "Moved".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
|
||||
d.keep_type_values_in_range();
|
||||
let kept = |key: &str| d.char_styles[0].attrs[key].as_f64();
|
||||
assert_eq!((kept("diacriticHorizontal"), kept("diacriticVertical")), (Some(MAX_DIACRITIC_POSITION), Some(-MAX_DIACRITIC_POSITION)));
|
||||
}
|
||||
|
||||
/// Tsume is 0 by default and saved only when not 0; styles written before it read as 0, and a
|
||||
/// value out of range from a file, in a run or a character style, is kept from 0 to 100.
|
||||
#[test]
|
||||
|
||||
@@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"distort.transform",
|
||||
"Transform…",
|
||||
DT,
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale, a Drop Shadow's offset turns, reflects and scales, a pixel filter's lightDirection or strokeDirection turns and reflects to the nearest choice (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's channel angles turn and reflect with the art (0 to 360); so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
|
||||
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
|
||||
),
|
||||
g(
|
||||
|
||||
@@ -853,7 +853,11 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
{
|
||||
// The members' raster effects then follow the group's own Transform effects as well.
|
||||
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
|
||||
members_as_drawn(doc, &mut m);
|
||||
}
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
|
||||
+113
-2
@@ -29,6 +29,8 @@ mod sketch_ink;
|
||||
mod texture;
|
||||
mod video;
|
||||
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
@@ -332,6 +334,9 @@ pub struct PixelSpace {
|
||||
pub extent: f64,
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angle parameters with their defaults (degrees).
|
||||
const SCREEN_ANGLES: [(&str, f64); 4] = [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)];
|
||||
|
||||
/// Effect `id`'s parameters `p` (defaults merged in) as a [`PixelFx`]; `None` for other effects.
|
||||
pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
let quality = |levels: [(&str, u32); 3], default: u32| {
|
||||
@@ -565,8 +570,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
},
|
||||
"pixelate.colorHalftone" => PixelFx::ColorHalftone {
|
||||
max_radius: num(p, "maxRadius", 8.0).clamp(4.0, 127.0),
|
||||
angles: [("channel1", 108.0), ("channel2", 162.0), ("channel3", 90.0), ("channel4", 45.0)]
|
||||
.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
angles: SCREEN_ANGLES.map(|(k, d)| num(p, k, d).clamp(-360.0, 360.0)),
|
||||
},
|
||||
"pixelate.crystallize" => PixelFx::Crystallize { cell: num(p, "cellSize", 10.0).clamp(3.0, 300.0) },
|
||||
"pixelate.mezzotint" => PixelFx::Mezzotint { kind: Mezzotint::parse(text(p, "type", "fineDots")) },
|
||||
@@ -855,6 +859,113 @@ fn pick<T: Clone>(table: &[(&str, &str)], all: &[T], value: &str, default: T) ->
|
||||
table.iter().zip(all).find(|((_, v), _)| v.eq_ignore_ascii_case(value)).map_or(default, |(_, t)| t.clone())
|
||||
}
|
||||
|
||||
/// The shortest that a direction's unit vector may become under a Transform effect and still give
|
||||
/// a direction ([`turned_directions`]).
|
||||
const MIN_TURNED: f64 = 1e-9;
|
||||
|
||||
/// How close (radians) two directions' angles to a turned direction must be to count as equally
|
||||
/// near ([`nearest`]).
|
||||
const TIE: f64 = 1e-9;
|
||||
|
||||
/// The parameters of pixel filter `id` (params `p`, defaults not merged in) that set a direction
|
||||
/// on the page, as `a` turns them: `a` is the linear part of a Transform effect listed after the
|
||||
/// filter, which turns, reflects and scales what the filter paints. A light direction or stroke
|
||||
/// direction becomes the one nearest to where `a` takes it, the one clockwise of it when two are
|
||||
/// equally near ([`snapped`]); `later` is the map the filter still goes through when it is drawn,
|
||||
/// after `a`. Color Halftone's screen angles (degrees counterclockwise from the page's horizontal)
|
||||
/// turn with `a`, from 0 up to 360. A direction that `a` takes to no direction (a zero scale) stays
|
||||
/// as it is. Empty for filters with no such parameter.
|
||||
pub(crate) fn turned_directions(id: &str, p: &Value, a: Affine, later: Affine) -> Vec<(&'static str, Value)> {
|
||||
enum Kind {
|
||||
Light(&'static str),
|
||||
Stroke,
|
||||
Screens,
|
||||
}
|
||||
let kind = match id {
|
||||
"sketch.basRelief" => Kind::Light("bottom"),
|
||||
"artistic.underpainting" | "artistic.roughPastels" | "sketch.conteCrayon" | "sketch.plaster" | "texture.texturizer" => Kind::Light("top"),
|
||||
"brushStrokes.sprayedStrokes" | "sketch.graphicPen" => Kind::Stroke,
|
||||
"pixelate.colorHalftone" => Kind::Screens,
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
let p = crate::merged_params(id, p);
|
||||
match kind {
|
||||
Kind::Light(default) => {
|
||||
let light = Light::parse(text(&p, "lightDirection", default));
|
||||
snapped(&Light::ALL, Light::toward, light, a, later, false)
|
||||
.and_then(|t| name_of(&LIGHT_DIRECTIONS, &Light::ALL, t))
|
||||
.map(|name| vec![("lightDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
Kind::Stroke => {
|
||||
let direction = StrokeDirection::parse(text(&p, "strokeDirection", "rightDiagonal"));
|
||||
snapped(&StrokeDirection::ALL, StrokeDirection::along, direction, a, later, true)
|
||||
.and_then(|t| name_of(&STROKE_DIRECTIONS, &StrokeDirection::ALL, t))
|
||||
.map(|name| vec![("strokeDirection", Value::from(name))])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
// A screen at θ° runs along (cos θ, −sin θ) on the page (y down).
|
||||
Kind::Screens => SCREEN_ANGLES
|
||||
.iter()
|
||||
.filter_map(|&(key, default)| {
|
||||
let t = num(&p, key, default).clamp(-360.0, 360.0).to_radians();
|
||||
let v = mapped(a, Vec2::new(t.cos(), -t.sin()))?;
|
||||
let degrees = ((-v.y).atan2(v.x).to_degrees() * 1e6).round() / 1e6;
|
||||
Some((key, Value::from(degrees.rem_euclid(360.0) + 0.0)))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the linear part of `a` takes direction `v`; `None` when it takes it to no direction.
|
||||
fn mapped(a: Affine, v: Vec2) -> Option<Vec2> {
|
||||
let w = (a * v.to_point()) - (a * Point::ORIGIN);
|
||||
(w.is_finite() && w.hypot() > MIN_TURNED).then_some(w)
|
||||
}
|
||||
|
||||
/// The entry of `all` to store for `from` (directions `dir`) once `a` turns it: the one nearest to
|
||||
/// where `a` takes it ([`nearest`]). When the stored entry is still to be mapped by `later` and
|
||||
/// rounded again as it is drawn, it is the entry nearest to that among those that `later` takes to
|
||||
/// the entry nearest to where `later` after `a` takes `from`, so that the drawn direction is
|
||||
/// rounded once. `None` when `a` takes `from` to no direction.
|
||||
fn snapped<T: Copy + PartialEq>(all: &[T], dir: fn(T) -> Vec2, from: T, a: Affine, later: Affine, axis: bool) -> Option<T> {
|
||||
let v = mapped(a, dir(from))?;
|
||||
let turned = nearest(all, dir, v, axis)?;
|
||||
if later == Affine::IDENTITY {
|
||||
return Some(turned);
|
||||
}
|
||||
let Some(target) = mapped(later * a, dir(from)).and_then(|w| nearest(all, dir, w, axis)) else { return Some(turned) };
|
||||
let fits: Vec<T> = all.iter().copied().filter(|&t| mapped(later, dir(t)).and_then(|w| nearest(all, dir, w, axis)) == Some(target)).collect();
|
||||
nearest(&fits, dir, v, axis).or(Some(turned))
|
||||
}
|
||||
|
||||
/// The entry of `all` whose direction (`dir`, page axes with y down) is nearest to `v` by angle,
|
||||
/// a direction and its opposite counting as the same with `axis`. Of two equally near, the one
|
||||
/// clockwise of `v` on the page.
|
||||
fn nearest<T: Copy>(all: &[T], dir: impl Fn(T) -> Vec2, v: Vec2, axis: bool) -> Option<T> {
|
||||
let period = if axis { PI } else { TAU };
|
||||
let at = v.atan2();
|
||||
let mut best: Option<(T, f64)> = None;
|
||||
for &t in all {
|
||||
// How far clockwise of `v` the entry lies, within half a period either way.
|
||||
let d = (dir(t).atan2() - at).rem_euclid(period);
|
||||
let d = if d > period / 2.0 { d - period } else { d };
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((_, b)) => d.abs() < b.abs() - TIE || (d.abs() <= b.abs() + TIE && d > b),
|
||||
};
|
||||
if better {
|
||||
best = Some((t, d));
|
||||
}
|
||||
}
|
||||
best.map(|(t, _)| t)
|
||||
}
|
||||
|
||||
/// The value in `table` of entry `t` of `all` (the same order).
|
||||
fn name_of<T: PartialEq>(table: &[(&'static str, &'static str)], all: &[T], t: T) -> Option<&'static str> {
|
||||
table.iter().zip(all).find(|(_, u)| **u == t).map(|((_, v), _)| *v)
|
||||
}
|
||||
|
||||
/// `data` as `w` × `h` RGBA pixels, `None` when it isn't that size (or is empty).
|
||||
fn pixels(data: &mut [u8], w: usize, h: usize) -> Option<&mut [[u8; 4]]> {
|
||||
let (px, rest) = data.as_chunks_mut::<4>();
|
||||
|
||||
@@ -43,7 +43,7 @@ pub enum StrokeDirection {
|
||||
}
|
||||
|
||||
impl StrokeDirection {
|
||||
const ALL: [StrokeDirection; 4] =
|
||||
pub(super) const ALL: [StrokeDirection; 4] =
|
||||
[StrokeDirection::RightDiagonal, StrokeDirection::Horizontal, StrokeDirection::LeftDiagonal, StrokeDirection::Vertical];
|
||||
|
||||
/// The direction of `value` (a [`STROKE_DIRECTIONS`] value, any case); Right Diagonal
|
||||
@@ -53,7 +53,7 @@ impl StrokeDirection {
|
||||
}
|
||||
|
||||
/// The unit vector along the strokes (document axes, y down).
|
||||
fn along(self) -> Vec2 {
|
||||
pub(super) fn along(self) -> Vec2 {
|
||||
match self {
|
||||
StrokeDirection::RightDiagonal => RIGHT,
|
||||
StrokeDirection::Horizontal => Vec2::new(1.0, 0.0),
|
||||
|
||||
@@ -137,7 +137,7 @@ pub enum Light {
|
||||
}
|
||||
|
||||
impl Light {
|
||||
const ALL: [Light; 8] =
|
||||
pub(super) const ALL: [Light; 8] =
|
||||
[Light::Bottom, Light::BottomLeft, Light::Left, Light::TopLeft, Light::Top, Light::TopRight, Light::Right, Light::BottomRight];
|
||||
|
||||
/// The direction of `value` (a [`LIGHT_DIRECTIONS`] value, any case); Top otherwise.
|
||||
|
||||
@@ -452,7 +452,7 @@ pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
|
||||
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
|
||||
let list = out.get_or_insert_with(|| effects.to_vec());
|
||||
if let Some(e) = list.get_mut(i) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
out.map_or(Cow::Borrowed(effects), Cow::Owned)
|
||||
@@ -472,7 +472,7 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
|
||||
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
|
||||
let mut changed = false;
|
||||
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
|
||||
follow_transform(e, a);
|
||||
follow_transform(e, a, Affine::IDENTITY);
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
@@ -519,7 +519,7 @@ pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine)
|
||||
let det = b.determinant();
|
||||
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
|
||||
if c.is_finite() {
|
||||
follow_transform(e, c);
|
||||
follow_transform(e, c, b);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -666,11 +666,44 @@ pub(crate) fn follows(id: &str) -> bool {
|
||||
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The linear part of the Transform effects of the groups and layers whose members are being
|
||||
/// evaluated ([`LaterGroups`]), which those groups apply to the members' raster effects once
|
||||
/// the members are evaluated: the members' light and stroke directions are rounded for them as
|
||||
/// well ([`follow_transform`]).
|
||||
static LATER_GROUPS: std::cell::Cell<Affine> = const { std::cell::Cell::new(Affine::IDENTITY) };
|
||||
}
|
||||
|
||||
/// The Transform effects of a group or layer whose members are being evaluated before the group's
|
||||
/// own effects are applied to them, added to [`LATER_GROUPS`] until it is dropped.
|
||||
pub(crate) struct LaterGroups(Affine);
|
||||
|
||||
impl LaterGroups {
|
||||
/// Add the Transform effects of `owner`, a group's or layer's own effects ([`contents_step`]),
|
||||
/// to those the members will still go through.
|
||||
pub(crate) fn enter(owner: &[Effect]) -> Self {
|
||||
let was = LATER_GROUPS.with(|l| l.get());
|
||||
if let Some(step) = contents_step(owner) {
|
||||
LATER_GROUPS.with(|l| l.set(was * step));
|
||||
}
|
||||
LaterGroups(was)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LaterGroups {
|
||||
fn drop(&mut self) {
|
||||
LATER_GROUPS.with(|l| l.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
|
||||
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
|
||||
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
|
||||
/// `a`. Effects that [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
/// scale ([`crate::scale_effect`]), a Drop Shadow's offset turns, reflects and scales with `a`,
|
||||
/// and a pixel filter's light direction, stroke direction or screen angles turn and reflect with
|
||||
/// it ([`pixel::turned_directions`]; `later` is the map `e` still goes through when it is drawn,
|
||||
/// before the Transform effects of the groups around it in [`LATER_GROUPS`]). Effects that
|
||||
/// [`follows`] leaves out stay as they are.
|
||||
fn follow_transform(e: &mut Effect, a: Affine, later: Affine) {
|
||||
if !follows(&e.id) {
|
||||
return;
|
||||
}
|
||||
@@ -678,15 +711,22 @@ fn follow_transform(e: &mut Effect, a: Affine) {
|
||||
let p = merged_params(&e.id, &e.params);
|
||||
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
|
||||
});
|
||||
let turned = pixel::turned_directions(&e.id, &e.params, a, LATER_GROUPS.with(|l| l.get()) * later);
|
||||
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
|
||||
crate::scale_effect(e, k);
|
||||
}
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
let mut set = |key: &str, value: Value| {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
}
|
||||
e.params["x"] = json!(o.x);
|
||||
e.params["y"] = json!(o.y);
|
||||
e.params[key] = value;
|
||||
};
|
||||
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
|
||||
set("x", json!(o.x));
|
||||
set("y", json!(o.y));
|
||||
}
|
||||
for (key, value) in turned {
|
||||
set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -515,18 +515,62 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
|
||||
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
|
||||
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
|
||||
/// move with the type.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
|
||||
///
|
||||
/// When `xf` is not a similarity (it scales unevenly, shears or flattens), one weight can't give
|
||||
/// the stroke the thickness the canvas paints in each direction: `piece` keeps only the run's fill,
|
||||
/// and the returned path is the area the run's stroke paints around `piece` in text space
|
||||
/// ([`crate::stroke::outline_region`]: dashes, caps, joins and alignment), placed by `xf` and
|
||||
/// filled with the stroke's paint, to paint over `piece`. `None` under a similarity and for a run
|
||||
/// without a stroke.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) -> Option<Node> {
|
||||
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
|
||||
let mut ap = style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
let stroke = if is_similarity(xf) { None } else { filled_stroke(piece, &mut ap) };
|
||||
piece.appearance = ap.into();
|
||||
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
|
||||
piece.transform(xf, scaling);
|
||||
stroke.map(|mut s| {
|
||||
s.transform(xf, scaling);
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `xf` keep angles and scale every direction alike (a move, a rotation, a uniform scale or a
|
||||
/// reflection), without flattening?
|
||||
fn is_similarity(xf: Affine) -> bool {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let (x, y) = (a.hypot(b), c.hypot(d));
|
||||
let tol = 1e-9 * x.max(y);
|
||||
x.is_finite() && y.is_finite() && x > 0.0 && y > 0.0 && (x - y).abs() <= tol && (a * c + b * d).abs() <= tol * x.max(y)
|
||||
}
|
||||
|
||||
/// Takes the stroke out of `ap`, the appearance of `piece` (a path or compound path in text space),
|
||||
/// and returns the area it paints there as a path filled with its paint, opacity, blend mode,
|
||||
/// effects and overprint, with `piece`'s id. `None` when `ap` has no stroke or it paints nothing.
|
||||
fn filled_stroke(piece: &Node, ap: &mut Appearance) -> Option<Node> {
|
||||
let i = ap.items.iter().position(|i| matches!(i, AppearanceItem::Stroke(_)))?;
|
||||
let AppearanceItem::Stroke(st) = ap.items.remove(i) else { return None };
|
||||
let path = PathData::from_bezpath(&piece.stroke_path()?);
|
||||
let region = crate::stroke::outline_region(&path, FillRule::NonZero, &st);
|
||||
if region.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fill = vectorcraft_doc::FillLayer {
|
||||
opacity: st.opacity,
|
||||
blend: st.blend,
|
||||
effects: st.effects.clone(),
|
||||
overprint: st.overprint,
|
||||
..vectorcraft_doc::FillLayer::new(st.paint.stroke_as_fill())
|
||||
};
|
||||
Some(Node::path(piece.id, region, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
|
||||
}
|
||||
|
||||
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
|
||||
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
|
||||
/// outline with the object's items below the characters under them and the others over them, as
|
||||
/// the renderer paints them. Each run's path is placed by the type's transform, which also scales its stroke
|
||||
/// weights and dashes and transforms its pattern tiles; its unplaced gradients are first fixed to
|
||||
/// weights and dashes and transforms its pattern tiles (a transform that is not a similarity puts
|
||||
/// the run's stroke on a filled path over it, [`paint_type_piece`]); its unplaced gradients are first fixed to
|
||||
/// the layout's bounds in text space. The object's own unplaced gradients are fixed to the
|
||||
/// bounding box of those bounds in the document. The group is marked as type's outlines
|
||||
/// ([`vectorcraft_doc::NodeExtras::type_outlines`]).
|
||||
@@ -542,8 +586,9 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
continue;
|
||||
}
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
|
||||
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
let stroke = paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
children.push(Arc::new(piece));
|
||||
children.extend(stroke.map(Arc::new));
|
||||
}
|
||||
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
|
||||
let (below, above) = n.appearance.split_contents();
|
||||
|
||||
@@ -324,8 +324,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
reshape_members(n, before, &mut shapes);
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
return check_cast(id, p, &shapes);
|
||||
return check_solids(id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -342,38 +341,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = path.bounds().ok_or_else(anchors)?;
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
check_cast(id, p, &shapes)
|
||||
check_solids(id, p, &shapes)
|
||||
}
|
||||
|
||||
/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes`
|
||||
/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
if wireframe::wireframe_params(id, p) {
|
||||
return Ok(());
|
||||
}
|
||||
cast_shadow(id, p, shapes).map(|_| ())
|
||||
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
|
||||
/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn casts_shadow(id: &str, p: &Value) -> bool {
|
||||
!is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p)
|
||||
}
|
||||
|
||||
/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow?
|
||||
fn visible(item: &AppearanceItem, member: f32) -> bool {
|
||||
paint_of(item, member).1 > 0.0
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every
|
||||
/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill,
|
||||
/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid,
|
||||
/// which [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
|
||||
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
|
||||
/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids
|
||||
/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which
|
||||
/// [`check_solids`] builds once, about the bounds the effect draws it about.
|
||||
fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))))
|
||||
.try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
let cast = casts_shadow(id, p);
|
||||
let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity)));
|
||||
shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes`
|
||||
/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not
|
||||
/// counted.
|
||||
/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does
|
||||
/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as
|
||||
/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the
|
||||
/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its
|
||||
/// shadow Rotate builds no plane here.
|
||||
fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) };
|
||||
let Some(b) = union_bounds(shapes) else { return Ok(()) };
|
||||
let cast = casts_shadow(id, p);
|
||||
if is_plane(id) {
|
||||
if !cast {
|
||||
return Ok(());
|
||||
}
|
||||
let mut built = vec![];
|
||||
for s in shapes {
|
||||
for item in &s.items {
|
||||
if !visible(item, s.opacity) {
|
||||
built.push(None);
|
||||
continue;
|
||||
}
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1);
|
||||
}
|
||||
}
|
||||
return cast_built(id, p, shapes, built).map(|_| ());
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()))
|
||||
if !cast {
|
||||
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
|
||||
}
|
||||
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
|
||||
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
cast_built(id, p, shapes, built).map(|_| ())
|
||||
}
|
||||
|
||||
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
|
||||
@@ -733,7 +762,8 @@ thread_local! {
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
|
||||
/// ([`cast_shadow`]) count too.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -1435,7 +1465,7 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let cast = casts_shadow(&fx.id, &p);
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
@@ -1500,12 +1530,16 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
|
||||
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
@@ -1529,16 +1563,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
/// each shape, otherwise each part ([`solid_parts`]). No solid is built here: an entry with no faces
|
||||
/// (a stroke's solid left out of the art, past its own limits) casts nothing, as it draws nothing.
|
||||
/// Only `built` of another length than the solids is cast as [`cast_shadow`] casts it.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
@@ -1555,39 +1587,22 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
let Some(kept) = kept else { continue };
|
||||
cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.casts() && kept.is_none())) {
|
||||
let (parts, _) = solid_parts(shapes, b);
|
||||
if parts.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if !ink.casts() {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) {
|
||||
let ink = ink(item, *member);
|
||||
// A fully transparent solid, or a stroke's solid left out of the art, casts nothing.
|
||||
let Some(kept) = kept.filter(|_| ink.casts()) else { continue };
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
let faces = match caster.add_solid(kept) {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
|
||||
@@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result
|
||||
|
||||
/// The check builds each solid the effect draws once, about the bounds it draws it about: one for
|
||||
/// a fill and one for each stroke, on an object, on a group's members and on an appearance item,
|
||||
/// with the shadow on or off.
|
||||
/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds
|
||||
/// kept, so no solid is built again for it.
|
||||
#[test]
|
||||
fn the_check_builds_each_drawn_solid_once() {
|
||||
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
|
||||
@@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() {
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill");
|
||||
let shadow = json!({"shadow": true});
|
||||
assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on");
|
||||
let mut other = square_node();
|
||||
other.id = NodeId(2);
|
||||
let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]);
|
||||
assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on");
|
||||
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -313,6 +313,68 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast
|
||||
/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws
|
||||
/// nothing, and the fill's solid still casts.
|
||||
#[test]
|
||||
fn a_stroke_left_out_of_the_art_casts_no_shadow() {
|
||||
for id in [EXTRUDE, INFLATE] {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
|
||||
let p = crate::merged_params(id, &json!({"shadow": true}));
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let mut built: Vec<Option<SolidFaces>> =
|
||||
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
|
||||
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
|
||||
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
|
||||
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
|
||||
assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast");
|
||||
built[stroke] = None;
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap();
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow");
|
||||
assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing");
|
||||
assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the
|
||||
/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing.
|
||||
#[test]
|
||||
fn the_check_accepts_the_shadowed_objects_that_draw() {
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for params in shadow_settings(id) {
|
||||
for n in shadowed(id, ¶ms) {
|
||||
let mut drawn = 0;
|
||||
art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some()));
|
||||
assert!(drawn > 0, "{id} {params}");
|
||||
assert_eq!(validate_solid(&n, id, ¶ms), Ok(()), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let shadow = json!({"shadow": true});
|
||||
for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] {
|
||||
let n = stroked_square(1, 0.0, stroke);
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no
|
||||
/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off.
|
||||
#[test]
|
||||
fn the_check_casts_no_shadow_in_wireframe_mode() {
|
||||
let n = stroked_square(1, 0.0, 1.0);
|
||||
let wire = json!({"shadow": true, "render": {"mode": "wireframe"}});
|
||||
for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] {
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}");
|
||||
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
|
||||
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
|
||||
/// it from the faces the solids drawn kept.
|
||||
|
||||
@@ -11,6 +11,7 @@ mod rasterfollow;
|
||||
mod scale;
|
||||
mod solidcontext;
|
||||
mod transformfx;
|
||||
mod typestroke;
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
|
||||
@@ -7,7 +7,8 @@ use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use crate::geometry::{Budget, MAX_EFFECT_LINES, apply_geometry_carrying_within};
|
||||
use crate::{Carry, GeomContext, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
use crate::pixel::{Light, StrokeDirection};
|
||||
use crate::{Carry, GeomContext, PixelFx, RasterFx, apply_geometry_carrying, bake_document, expand_outlined, raster_effects};
|
||||
|
||||
fn fx(id: &str, params: Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
@@ -436,6 +437,230 @@ fn pixel_filter_sizes_scale_with_the_transform_after_them() {
|
||||
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
|
||||
}
|
||||
|
||||
/// The light direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_light(effects: &[Effect]) -> Option<Light> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(
|
||||
PixelFx::Underpainting { light, .. }
|
||||
| PixelFx::RoughPastels { light, .. }
|
||||
| PixelFx::ConteCrayon { light, .. }
|
||||
| PixelFx::BasRelief { light, .. }
|
||||
| PixelFx::Plaster { light, .. }
|
||||
| PixelFx::Texturizer { light, .. },
|
||||
) => Some(light),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The stroke direction of the first pixel filter `effects` draw, if it has one.
|
||||
fn drawn_strokes(effects: &[Effect]) -> Option<StrokeDirection> {
|
||||
raster_effects(effects).into_iter().find_map(|r| match r {
|
||||
RasterFx::Pixel(PixelFx::SprayedStrokes { direction, .. } | PixelFx::GraphicPen { direction, .. }) => Some(direction),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The screen angles of the first Color Halftone `effects` draw.
|
||||
fn drawn_screens(effects: &[Effect]) -> [f64; 4] {
|
||||
match raster_effects(effects).into_iter().next() {
|
||||
Some(RasterFx::Pixel(PixelFx::ColorHalftone { angles, .. })) => angles,
|
||||
other => panic!("expected a Color Halftone, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bas Relief lit from `light`, then a Transform effect with `params`: the light it draws with.
|
||||
fn relief_then(light: &str, params: Value) -> Option<Light> {
|
||||
drawn_light(&[fx("sketch.basRelief", json!({ "lightDirection": light })), transform(params)])
|
||||
}
|
||||
|
||||
/// A light direction before a Transform effect turns and reflects with the art (y down on the
|
||||
/// page), to the nearest of the eight directions, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn bas_relief_light_follows_rotation_and_reflection() {
|
||||
assert_eq!(relief_then("top", json!({"rotate": 90})), Some(Light::Left));
|
||||
assert_eq!(relief_then("top", json!({"reflectY": true})), Some(Light::Bottom));
|
||||
assert_eq!(relief_then("top", json!({"reflectX": true})), Some(Light::Top));
|
||||
assert_eq!(relief_then("left", json!({"reflectX": true})), Some(Light::Right));
|
||||
// 22.5° clockwise lies halfway between Top and Top Right; 22.5° counterclockwise halfway
|
||||
// between Top and Top Left.
|
||||
assert_eq!(relief_then("top", json!({"rotate": -22.5})), Some(Light::TopRight));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 22.5})), Some(Light::Top));
|
||||
assert_eq!(relief_then("top", json!({"rotate": 30})), Some(Light::TopLeft));
|
||||
// A turn of 90° counterclockwise, from each direction.
|
||||
for (from, to) in [
|
||||
("bottom", Light::Right),
|
||||
("bottomLeft", Light::BottomRight),
|
||||
("left", Light::Bottom),
|
||||
("topLeft", Light::BottomLeft),
|
||||
("top", Light::Left),
|
||||
("topRight", Light::TopLeft),
|
||||
("right", Light::Top),
|
||||
("bottomRight", Light::TopRight),
|
||||
] {
|
||||
assert_eq!(relief_then(from, json!({"rotate": 90})), Some(to), "{from}");
|
||||
}
|
||||
// Every filter with a light direction, and Bas Relief's default light (Bottom).
|
||||
for id in ["artistic.underpainting", "artistic.roughPastels", "sketch.conteCrayon", "sketch.basRelief", "sketch.plaster", "texture.texturizer"] {
|
||||
let effects = [fx(id, json!({"lightDirection": "top"})), transform(json!({"rotate": 90}))];
|
||||
assert_eq!(drawn_light(&effects), Some(Light::Left), "{id}");
|
||||
}
|
||||
assert_eq!(drawn_light(&[fx("sketch.basRelief", json!({})), transform(json!({"rotate": 90}))]), Some(Light::Right));
|
||||
// The Transform effects after the filter turn it together, with one rounding at the end.
|
||||
let twice = [fx("sketch.basRelief", json!({"lightDirection": "top"})), transform(json!({"rotate": -22.5})), transform(json!({"rotate": -22.5}))];
|
||||
assert_eq!(drawn_light(&twice), Some(Light::TopRight));
|
||||
}
|
||||
|
||||
/// A stroke direction before a Transform effect turns and reflects with the art, to the nearest
|
||||
/// of the four, a stroke and its reverse being the same, the clockwise one at a tie.
|
||||
#[test]
|
||||
fn stroke_axis_follows_transform() {
|
||||
let strokes = |id: &str, way: Option<&str>, params: Value| {
|
||||
let p = way.map_or(json!({}), |w| json!({ "strokeDirection": w }));
|
||||
drawn_strokes(&[fx(id, p), transform(params)])
|
||||
};
|
||||
let sprayed = "brushStrokes.sprayedStrokes";
|
||||
let pen = "sketch.graphicPen";
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 90})), Some(StrokeDirection::Vertical));
|
||||
assert_eq!(strokes(sprayed, Some("vertical"), json!({"rotate": 90})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("rightDiagonal"), json!({"reflectX": true})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(pen, Some("leftDiagonal"), json!({"reflectY": true})), Some(StrokeDirection::RightDiagonal));
|
||||
assert_eq!(strokes(pen, None, json!({"rotate": 90})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -22.5})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 22.5})), Some(StrokeDirection::Horizontal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": -44})), Some(StrokeDirection::LeftDiagonal));
|
||||
assert_eq!(strokes(sprayed, Some("horizontal"), json!({"rotate": 180})), Some(StrokeDirection::Horizontal));
|
||||
}
|
||||
|
||||
fn near4(a: [f64; 4], b: [f64; 4]) -> bool {
|
||||
a.iter().zip(b).all(|(p, q)| (p - q).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Color Halftone's screen angles before a Transform effect turn and reflect with the art.
|
||||
#[test]
|
||||
fn halftone_channels_follow_rotation_and_reflection() {
|
||||
let screens = |p: Value, transforms: &[Value]| {
|
||||
let mut effects = vec![fx("pixelate.colorHalftone", p)];
|
||||
effects.extend(transforms.iter().cloned().map(transform));
|
||||
drawn_screens(&effects)
|
||||
};
|
||||
let defaults = screens(json!({}), &[json!({"rotate": 90})]);
|
||||
assert!(near4(defaults, [198.0, 252.0, 180.0, 135.0]), "{defaults:?}");
|
||||
let reflected = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectX": true})]);
|
||||
assert!(near4(reflected, [135.0, 150.0, 180.0, 270.0]), "{reflected:?}");
|
||||
let flipped = screens(json!({"channel1": 45, "channel2": 30, "channel3": 0, "channel4": 270}), &[json!({"reflectY": true})]);
|
||||
assert!(near4(flipped, [315.0, 330.0, 0.0, 90.0]), "{flipped:?}");
|
||||
// One Transform effect reflects, then turns; two apply in the order they are listed.
|
||||
let p = json!({"channel1": 10.5, "channel2": -30, "channel3": 0, "channel4": 359.25});
|
||||
let one = screens(p.clone(), &[json!({"rotate": 30, "reflectX": true})]);
|
||||
assert!(near4(one, [199.5, 240.0, 210.0, 210.75]), "{one:?}");
|
||||
let two = screens(p, &[json!({"rotate": 30}), json!({"reflectX": true})]);
|
||||
assert!(near4(two, [139.5, 180.0, 150.0, 150.75]), "{two:?}");
|
||||
}
|
||||
|
||||
/// Only the visible Transform effects listed after a filter that move the art once turn its
|
||||
/// direction; a hidden filter turns too, and a zero scale leaves it as it is.
|
||||
#[test]
|
||||
fn only_earlier_visible_single_map_effects_follow() {
|
||||
let relief = fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
assert_eq!(drawn_light(&[transform(json!({"rotate": 90})), relief.clone()]), Some(Light::Top));
|
||||
for params in [
|
||||
json!({"rotate": 90, "objects": false}),
|
||||
json!({"rotate": 90, "copies": 1}),
|
||||
json!({"rotate": 90, "random": true}),
|
||||
json!({"scaleH": 0, "scaleV": 0}),
|
||||
] {
|
||||
assert_eq!(drawn_light(&[relief.clone(), transform(params.clone())]), Some(Light::Top), "{params}");
|
||||
}
|
||||
let mut hidden = transform(json!({"rotate": 90}));
|
||||
hidden.visible = false;
|
||||
assert_eq!(drawn_light(&[relief.clone(), hidden]), Some(Light::Top));
|
||||
let zero = [fx("pixelate.colorHalftone", json!({"channel1": 20})), transform(json!({"scaleH": 0, "scaleV": 0}))];
|
||||
assert!(near4(drawn_screens(&zero), [20.0, 162.0, 90.0, 45.0]), "{:?}", drawn_screens(&zero));
|
||||
// A hidden filter kept when the Transform effect is applied draws turned once it is shown.
|
||||
let mut off = relief;
|
||||
off.visible = false;
|
||||
let kept = crate::raster::without_geometry(&[off, transform(json!({"rotate": 90}))]);
|
||||
assert_eq!(kept.len(), 1);
|
||||
let mut shown = kept[0].clone();
|
||||
shown.visible = true;
|
||||
assert_eq!(drawn_light(&[shown]), Some(Light::Left));
|
||||
}
|
||||
|
||||
/// The light direction of every Bas Relief drawn on `n` and the nodes under it, from the object's
|
||||
/// effects and from each fill's and stroke's.
|
||||
fn lights_in(n: &Node) -> Vec<Light> {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |m| {
|
||||
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
|
||||
for list in lists {
|
||||
out.extend(drawn_light(list));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The canvas, a fill's own effects, a group's members and export turn the light the same way.
|
||||
#[test]
|
||||
fn nested_and_baked_directions_match_canvas() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let turn = || transform(json!({"rotate": 90}));
|
||||
// A fill's own Transform effect, and the object's Transform effect over its fill.
|
||||
let fill = fill_square(31, vec![relief(), turn()]);
|
||||
let item = fill.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(item.effects()), Some(Light::Left));
|
||||
let mut over = fill_square(32, vec![relief()]);
|
||||
over.appearance.effects = vec![turn()];
|
||||
let item = over.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&over.appearance.effects, item.effects())), Some(Light::Left));
|
||||
// A fill's own turn of 30° and the object's turn of 30° make 60°, rounded once: Top Left, not
|
||||
// Left (Top Left after the first turn, then Left after the second).
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let mut both = fill_square(37, vec![relief(), thirty()]);
|
||||
both.appearance.effects = vec![thirty()];
|
||||
let item = both.appearance.items.first().unwrap();
|
||||
assert_eq!(drawn_light(&crate::item_effects_in(&both.appearance.effects, item.effects())), Some(Light::TopLeft));
|
||||
// A group's Transform effect over a member's own filter and its fill's.
|
||||
let g = group(33, vec![square(34, vec![relief()]), fill_square(35, vec![relief()])], vec![turn()]);
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left; 2]);
|
||||
// Baked for export: the Transform effect is applied and the filter keeps the turned light.
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, square(36, vec![relief(), turn()])).unwrap();
|
||||
d.insert(Some(layer), 1, g).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
let b = baked.node(NodeId(36)).unwrap();
|
||||
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{:?}", b.appearance.effects);
|
||||
assert_eq!(drawn_light(&b.appearance.effects), Some(Light::Left));
|
||||
for id in [34, 35] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::Left], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A member's light under two nested groups that each turn 30° turns 60° in all, rounded once:
|
||||
/// Top Left, not Left (Top Left after the inner group's turn, then Left after the outer one's).
|
||||
#[test]
|
||||
fn nested_group_turns_round_the_light_once() {
|
||||
let relief = || fx("sketch.basRelief", json!({"lightDirection": "top"}));
|
||||
let thirty = || transform(json!({"rotate": 30}));
|
||||
let inner = group(41, vec![square(42, vec![relief()]), fill_square(43, vec![relief()])], vec![thirty()]);
|
||||
let outer = group(40, vec![inner], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &outer).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::TopLeft; 2]);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, outer).unwrap();
|
||||
let baked = bake_document(&d).unwrap();
|
||||
for id in [42, 43] {
|
||||
assert_eq!(lights_in(baked.node(NodeId(id)).unwrap()), vec![Light::TopLeft], "{id}");
|
||||
}
|
||||
// Three groups make 90°: Left, not Bottom Left.
|
||||
let three = group(44, vec![group(45, vec![group(46, vec![square(47, vec![relief()])], vec![thirty()])], vec![thirty()])], vec![thirty()]);
|
||||
let art = crate::evaluate_container(None, &three).unwrap();
|
||||
assert_eq!(lights_in(&art), vec![Light::Left]);
|
||||
}
|
||||
|
||||
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
|
||||
/// before the 3D effect, as it does without the 3D effect.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Character strokes of outlined type under the type's transform ([`paint_type_piece`]): a live
|
||||
//! stroke with a scaled weight under a similarity, otherwise the area the stroke paints in text
|
||||
//! space, placed by the transform and filled.
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Dash, LineJoin, Node, NodeId, StrokeAlign};
|
||||
use vectorcraft_geom::{Affine, FillRule, Rect, shapes};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const BOX: Rect = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
/// A black run with a red stroke of `width` and round joins.
|
||||
fn style(width: f64) -> CharStyle {
|
||||
CharStyle {
|
||||
fill: Paint::solid(Color::BLACK),
|
||||
stroke: Paint::solid(red()),
|
||||
stroke_width: width,
|
||||
stroke_join: LineJoin::Round,
|
||||
..CharStyle::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 x 10 square in text space standing in for a glyph.
|
||||
fn square() -> Node {
|
||||
Node::path(NodeId(7), shapes::rectangle(BOX), Appearance::default())
|
||||
}
|
||||
|
||||
fn area(n: &Node) -> f64 {
|
||||
vectorcraft_pathops::area(n.path_data().unwrap(), FillRule::NonZero).abs()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect) -> bool {
|
||||
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uneven_scale_fills_the_stroke_the_canvas_paints() {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::scale_non_uniform(3.0, 1.0)).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none(), "the piece keeps only its fill");
|
||||
assert_eq!(piece.appearance.fill_paint(), Paint::solid(Color::BLACK));
|
||||
assert_eq!(piece.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0));
|
||||
assert!(stroke.appearance.stroke().is_none());
|
||||
assert_eq!(stroke.appearance.fill_paint(), Paint::solid(red()));
|
||||
assert_eq!(stroke.id, NodeId(7));
|
||||
// 4 pt across in text space: 12 pt across the upright sides and 4 pt across the level ones.
|
||||
let b = stroke.geometric_bounds().unwrap();
|
||||
assert!(near(b, Rect::new(-6.0, -2.0, 36.0, 12.0)), "{b:?}");
|
||||
// The ring of a 10 pt square stroked 4 pt with round joins (180 + 4π outside, 36 inside), 3 times as wide.
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - 3.0 * ring).abs() < 0.5, "{}", area(&stroke));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_similarity_keeps_the_live_stroke_with_a_scaled_weight() {
|
||||
for (xf, weight) in [
|
||||
(Affine::translate((5.0, 5.0)), 4.0),
|
||||
(Affine::scale(2.0), 8.0),
|
||||
(Affine::rotate(0.5) * Affine::scale(2.0), 8.0),
|
||||
(Affine::scale_non_uniform(-2.0, 2.0), 8.0),
|
||||
] {
|
||||
let mut piece = square();
|
||||
assert!(paint_type_piece(&mut piece, &style(4.0), BOX, xf).is_none(), "{xf:?}");
|
||||
let st = piece.appearance.stroke().expect("a live stroke");
|
||||
assert!((st.width - weight).abs() < 1e-9, "{xf:?}: {}", st.width);
|
||||
assert_eq!(st.join, LineJoin::Round);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shears_and_flattening_transforms_fill_the_stroke() {
|
||||
// A shear keeps the area.
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, Affine::skew(0.5, 0.0)).expect("a filled stroke");
|
||||
let ring = 180.0 + 4.0 * std::f64::consts::PI - 36.0;
|
||||
assert!((area(&stroke) - ring).abs() < 0.5, "{}", area(&stroke));
|
||||
// Flattened to a line or a point: no division by the determinant, nothing non-finite.
|
||||
for xf in [Affine::scale_non_uniform(2.0, 0.0), Affine::scale(0.0)] {
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &style(4.0), BOX, xf).expect("a filled stroke");
|
||||
assert!(piece.appearance.stroke().is_none());
|
||||
if let Some(b) = stroke.geometric_bounds() {
|
||||
assert!([b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && b.height().abs() < 1e-9, "{xf:?}: {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_options_shape_the_filled_stroke_in_text_space() {
|
||||
let xf = Affine::scale_non_uniform(3.0, 1.0);
|
||||
let filled = |st: CharStyle| paint_type_piece(&mut square(), &st, BOX, xf);
|
||||
// No stroke, or no weight: nothing is filled.
|
||||
assert!(filled(style(0.0)).is_none());
|
||||
assert!(filled(CharStyle { stroke: Paint::None, ..style(4.0) }).is_none());
|
||||
// Inside and outside alignment are kept to their side of the square before it is scaled.
|
||||
let inside = filled(CharStyle { stroke_align: StrokeAlign::Inside, ..style(4.0) }).unwrap();
|
||||
assert!(near(inside.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 30.0, 10.0)));
|
||||
assert!((area(&inside) - 3.0 * (100.0 - 4.0)).abs() < 0.5, "{}", area(&inside));
|
||||
let outside = filled(CharStyle { stroke_align: StrokeAlign::Outside, ..style(4.0) }).unwrap();
|
||||
assert!(near(outside.geometric_bounds().unwrap(), Rect::new(-12.0, -4.0, 42.0, 14.0)), "{:?}", outside.geometric_bounds());
|
||||
// Dashes are laid out along the square in text space: half of each 10 pt is painted.
|
||||
let solid = area(&filled(style(1.0)).unwrap());
|
||||
let dash = Dash { pattern: vec![5.0, 5.0], ..Default::default() };
|
||||
let dashed = area(&filled(CharStyle { stroke_dash: Some(dash), ..style(1.0) }).unwrap());
|
||||
assert!(dashed < 0.7 * solid && dashed > 0.3 * solid, "{dashed} of {solid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_on_the_stroke_stays_where_the_stroke_had_it() {
|
||||
let stops = vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)];
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut piece = square();
|
||||
let stroke = paint_type_piece(&mut piece, &CharStyle { stroke: ramp, ..style(4.0) }, BOX, Affine::scale_non_uniform(3.0, 1.0)).unwrap();
|
||||
let Paint::Gradient(g) = stroke.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
// Fitted across the stroke's box in text space (the square grown by half the weight), then scaled.
|
||||
let geom = g.geom.expect("placed");
|
||||
assert!((geom.start.x + 6.0).abs() < 1e-6 && (geom.end.x - 36.0).abs() < 1e-6, "{geom:?}");
|
||||
}
|
||||
@@ -53,7 +53,7 @@ heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], op
|
||||
flate2 = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# The XML parts of Word documents placed as type (place/docx.rs).
|
||||
roxmltree = "0.21"
|
||||
craft-xml = { workspace = true }
|
||||
# The compound file that holds a Word 97-2003 document placed as type (place/doc.rs).
|
||||
cfb = "0.15"
|
||||
kurbo = { workspace = true }
|
||||
|
||||
@@ -98,6 +98,8 @@ pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
mod textedit;
|
||||
mod xmlattrs;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
pub mod textstyles;
|
||||
pub(crate) mod textwrap;
|
||||
|
||||
@@ -8,6 +8,7 @@ mod contour;
|
||||
mod cutting;
|
||||
mod document;
|
||||
mod image;
|
||||
mod packaging;
|
||||
mod pathtools;
|
||||
mod pen;
|
||||
mod select;
|
||||
@@ -15,6 +16,7 @@ mod shapes;
|
||||
mod typetools;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(cutting::specs());
|
||||
v.extend(document::specs());
|
||||
v.extend(image::specs());
|
||||
v.extend(packaging::specs());
|
||||
v.extend(pathtools::specs());
|
||||
v.extend(pen::specs());
|
||||
v.extend(select::specs());
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod roles;
|
||||
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::super::CommandSpec;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
roles::specs()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
|
||||
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
|
||||
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
|
||||
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
|
||||
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
|
||||
//! string, takes its default swatch, named after the role.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Document unknown key: the role table, `{role id: swatch name}`.
|
||||
pub(crate) const ROLES_KEY: &str = "packagingRoles";
|
||||
|
||||
const SET_ROLE: &str = "addon.packaging.setRole";
|
||||
const ROLES: &str = "addon.packaging.roles";
|
||||
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
|
||||
|
||||
/// What a fold line does when the blank is cut and folded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Role {
|
||||
/// Separates the material.
|
||||
Cut,
|
||||
/// A fold.
|
||||
Crease,
|
||||
/// A fold cut part way through the board.
|
||||
PartialCut,
|
||||
/// A fold along a line of cuts.
|
||||
Perforation,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
|
||||
|
||||
/// The role's id in params and in the role table.
|
||||
pub(crate) fn id(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "cut",
|
||||
Role::Crease => "crease",
|
||||
Role::PartialCut => "partialCut",
|
||||
Role::Perforation => "perforation",
|
||||
}
|
||||
}
|
||||
|
||||
/// The role's name, which is also its default swatch's name.
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Role::Cut => "Cut",
|
||||
Role::Crease => "Crease",
|
||||
Role::PartialCut => "Partial Cut",
|
||||
Role::Perforation => "Perforation",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_id(id: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| r.id() == id)
|
||||
}
|
||||
|
||||
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
|
||||
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
|
||||
fn color(self) -> Color {
|
||||
match self {
|
||||
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
|
||||
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
|
||||
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
|
||||
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatch each role is carried by, in [`Role::ALL`] order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct RoleTable([String; 4]);
|
||||
|
||||
impl RoleTable {
|
||||
/// The document's role table, with each missing or damaged entry at its default. When a damaged
|
||||
/// table names one swatch for two roles, the later role takes its default name instead, or
|
||||
/// "Crease 2" and so on when an earlier role has that.
|
||||
pub(crate) fn of(d: &Document) -> RoleTable {
|
||||
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
|
||||
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
|
||||
for r in Role::ALL {
|
||||
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
|
||||
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
|
||||
_ => {
|
||||
let base = r.name();
|
||||
std::iter::once(base.to_string())
|
||||
.chain((2..).map(|i| format!("{base} {i}")))
|
||||
.find(|n| !names.contains(n))
|
||||
.unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
};
|
||||
names.push(name);
|
||||
}
|
||||
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
|
||||
}
|
||||
|
||||
/// The swatch of `role`.
|
||||
pub(crate) fn swatch(&self, role: Role) -> &str {
|
||||
self.0.get(role.index()).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// The role swatch `name` carries.
|
||||
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
|
||||
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
|
||||
}
|
||||
|
||||
/// The role of object `n`: the role of the swatch its top stroke is painted with.
|
||||
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
|
||||
if !can_carry(n) {
|
||||
return None;
|
||||
}
|
||||
match &n.appearance.stroke()?.paint {
|
||||
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(&self) -> Value {
|
||||
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
|
||||
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
|
||||
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
|
||||
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
|
||||
/// two roles share a swatch.
|
||||
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
|
||||
let before = RoleTable::of(d);
|
||||
let mut table = before.clone();
|
||||
for r in Role::ALL {
|
||||
let name = table.swatch(r).to_string();
|
||||
let moved = if name == from && global {
|
||||
Some(to.to_string())
|
||||
} else if name == from || (name == to && from != to) {
|
||||
Some(free_role_name(d, &table, r))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
if table != before {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
|
||||
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
|
||||
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
|
||||
/// role keeps its name, which the next `setRole` makes a swatch for.
|
||||
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
|
||||
let mut table = RoleTable::of(d);
|
||||
if !linked || table.role_of_swatch(kept).is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = kept.to_string();
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
|
||||
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
|
||||
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
|
||||
/// always ends at a free one.
|
||||
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
|
||||
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
|
||||
let base = role.name();
|
||||
if free(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
|
||||
/// guide, or a compound path.
|
||||
fn can_carry(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
|
||||
NodeKind::Compound { .. } => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
|
||||
/// are on a locked artboard are left out and counted as skipped.
|
||||
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } => {
|
||||
for c in children {
|
||||
// A group's clipping path draws no stroke: it is skipped.
|
||||
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
|
||||
*skipped += 1;
|
||||
} else {
|
||||
walk(c, out, skipped);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => *skipped += 1,
|
||||
}
|
||||
}
|
||||
let (mut out, mut skipped) = (vec![], 0);
|
||||
// A path of a compound path is painted with the compound's appearance: the compound takes the
|
||||
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
|
||||
// group and its member are never both roots.
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
|
||||
walk(n, &mut out, &mut skipped);
|
||||
}
|
||||
if editable {
|
||||
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
|
||||
// layer or on a locked artboard, stays as it is.
|
||||
let ok = d.editable();
|
||||
let before = out.len();
|
||||
out.retain(|id| ok(*id));
|
||||
skipped += before - out.len();
|
||||
}
|
||||
(out, skipped)
|
||||
}
|
||||
|
||||
/// Every object of the document that can carry a role, through layers and groups.
|
||||
fn document_targets(d: &Document) -> Vec<NodeId> {
|
||||
fn walk(n: &Node, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
|
||||
_ if can_carry(n) => out.push(n.id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
d.layers.iter().for_each(|l| walk(l, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.packaging.setRole",
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
cmd!(
|
||||
query "addon.packaging.roles",
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
cmd!(
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"Role Swatches…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
|
||||
has_doc,
|
||||
set_role_swatch
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
|
||||
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
|
||||
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
|
||||
match Role::from_id(id) {
|
||||
Some(r) => Ok(Some(r)),
|
||||
None if none && id == "none" => Ok(None),
|
||||
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
|
||||
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why swatch `name` of `d` can't carry a role, if it can't.
|
||||
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
|
||||
if name == REGISTRATION || name == "[None]" {
|
||||
return Some(format!("`{name}` can't carry a role"));
|
||||
}
|
||||
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
|
||||
match &sw.paint {
|
||||
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
|
||||
Paint::Solid { .. } if sw.global => None,
|
||||
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
|
||||
_ => Some(format!("`{name}` isn't a color swatch")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
|
||||
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
|
||||
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
|
||||
/// free name, which the role table then gives the role.
|
||||
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
|
||||
let mut table = RoleTable::of(d);
|
||||
let current = table.swatch(role);
|
||||
let taken = match d.swatch(current) {
|
||||
Some(_) => unfit_swatch(d, current).is_some(),
|
||||
None => d.swatch_name_taken(current),
|
||||
};
|
||||
if taken {
|
||||
let free = free_role_name(d, &table, role);
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = free;
|
||||
}
|
||||
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
|
||||
}
|
||||
let name = table.swatch(role);
|
||||
if d.swatch(name).is_none() {
|
||||
let model = d.color_mode.model();
|
||||
let color = role.color();
|
||||
let color = if color.model() == model {
|
||||
color
|
||||
} else {
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
cms.convert(&color, model, cms.settings().intent)
|
||||
};
|
||||
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
|
||||
}
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
|
||||
}
|
||||
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
|
||||
}
|
||||
|
||||
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
|
||||
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
let had = table.role_of(n);
|
||||
let mut a = (*n.appearance).clone();
|
||||
match paint {
|
||||
Some(paint) => {
|
||||
a.set_stroke(paint.clone());
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
// A hidden stroke would carry the role without drawing or printing the line.
|
||||
st.visible = true;
|
||||
st.overprint = overprint;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if had.is_none() {
|
||||
return false;
|
||||
}
|
||||
if let Some(st) = a.stroke_mut() {
|
||||
if let Paint::Solid { color, .. } = st.paint {
|
||||
st.paint = Paint::solid(color);
|
||||
}
|
||||
st.overprint = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if a == *n.appearance {
|
||||
return false;
|
||||
}
|
||||
n.appearance = vectorcraft_doc::Shared::new(a);
|
||||
true
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
|
||||
let mut changed = 0;
|
||||
edit_counted(s, label, |d| {
|
||||
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
|
||||
let paint = role.map(|r| role_paint(d, r)).transpose()?;
|
||||
// A role swatch made again (its strokes may still name it) is a change of its own.
|
||||
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
|
||||
let table = RoleTable::of(d);
|
||||
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
|
||||
Ok(changed + usize::from(made))
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
.zip(counts)
|
||||
.map(|(r, count)| {
|
||||
let swatch = table.swatch(r);
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
|
||||
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(why) = unfit_swatch(d, name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, why));
|
||||
}
|
||||
let mut table = RoleTable::of(d);
|
||||
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
|
||||
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
|
||||
}
|
||||
if let Some(slot) = table.0.get_mut(role.index()) {
|
||||
*slot = name.to_string();
|
||||
}
|
||||
let value = table.to_value();
|
||||
let changed = RoleTable::of(d) != table;
|
||||
if changed {
|
||||
s.edit("Role Swatches", |d, _| {
|
||||
d.unknown.insert(ROLES_KEY.to_string(), value);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session(mode: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn set_role(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("addon.packaging.setRole", &p).unwrap()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
|
||||
s.execute(cmd, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// The `roles` query's counts, in role order.
|
||||
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
|
||||
let r = s.execute("addon.packaging.roles", &p).unwrap();
|
||||
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sw = d.swatch("Cut").unwrap();
|
||||
assert!(sw.global && sw.spot, "{sw:?}");
|
||||
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
|
||||
assert!(st.overprint, "role strokes overprint by default");
|
||||
// Again: nothing changes, and no undo step is recorded.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// Undo takes the swatch away with the role.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
|
||||
let mut s = session("rgb");
|
||||
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
|
||||
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
|
||||
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
|
||||
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
|
||||
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("strip", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
n.appearance.items.retain(AppearanceItem::is_fill);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(node(&s, a).appearance.stroke().is_none());
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.width, 1.0, "a 1 pt stroke");
|
||||
assert!(!st.overprint);
|
||||
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_takes_the_role_away_and_keeps_the_color() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let st = node(&s, a).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.paint, Paint::solid(shown));
|
||||
assert!(!st.overprint);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
|
||||
// Nothing left with a role: no undo step.
|
||||
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_roles_and_targets_are_refused() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
|
||||
// Text beside a path is skipped and counted.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
d.node_mut(c).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
|
||||
// Named directly, a locked or hidden path is left out too.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
|
||||
let before = steps(&s);
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
|
||||
let mut s = session("cmyk");
|
||||
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
|
||||
s.edit("lock", |d, _| {
|
||||
d.node_mut(b).unwrap().locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// A locked line keeps its role and is counted, whether its group is selected or not.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
|
||||
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
|
||||
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
|
||||
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
|
||||
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
|
||||
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
|
||||
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
|
||||
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
|
||||
// The next Make Cut Line makes the Cut role's swatch again.
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_swatch_can_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_counts_the_selection_or_the_whole_document() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
|
||||
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
|
||||
let rows = r["roles"].as_array().unwrap();
|
||||
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
|
||||
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_maps_a_role_to_another_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
// The old swatch's objects keep their color and lose the role.
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
|
||||
// The same mapping again changes nothing.
|
||||
let steps_now = steps(&s);
|
||||
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_role_swatch_keeps_its_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
// A swatch that carries no role leaves the table alone.
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
|
||||
// Undo puts the old name back in the table with the swatch.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
// No Crease swatch exists yet, so the name is free for the Cut swatch.
|
||||
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
|
||||
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
|
||||
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
|
||||
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
|
||||
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
|
||||
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
|
||||
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
|
||||
let before = steps(&s);
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
|
||||
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
|
||||
assert_eq!(steps(&s), before + 1, "as one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.edit("hide", |d, _| {
|
||||
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
|
||||
st.visible = false;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert!(node(&s, a).appearance.stroke().unwrap().visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
let before = steps(&s);
|
||||
for (swatch, says) in [
|
||||
("Nope", "no swatch"),
|
||||
("Ramp", "isn't a color swatch"),
|
||||
("Plain", "process color"),
|
||||
("Ink Tint", "tint swatch"),
|
||||
("[None]", "can't carry a role"),
|
||||
("[Registration]", "can't carry a role"),
|
||||
("Crease", "already carries the Crease role"),
|
||||
] {
|
||||
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
|
||||
assert!(e.contains(says), "{swatch}: {e}");
|
||||
}
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
|
||||
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_role_table_reads_as_the_defaults() {
|
||||
let mut s = session("cmyk");
|
||||
s.edit("damage", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
|
||||
s.edit("not an object", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!("Cut"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let a = rect(&mut s, 20.0);
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
|
||||
// One swatch named for two roles: the later role takes its own default.
|
||||
s.edit("duplicate", |d, _| {
|
||||
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
|
||||
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
|
||||
let b = rect(&mut s, 100.0);
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_open_keep_the_role_table_and_the_roles() {
|
||||
let mut s = session("cmyk");
|
||||
let a = rect(&mut s, 20.0);
|
||||
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// A document with one rectangle of each of Cut and Crease.
|
||||
fn two_roles() -> Session {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
|
||||
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
|
||||
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
|
||||
s
|
||||
}
|
||||
|
||||
fn export(s: &mut Session, format: &str) -> String {
|
||||
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
|
||||
let mut s = two_roles();
|
||||
let c = rect(&mut s, 180.0);
|
||||
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&s.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = String::from_utf8_lossy(&bytes);
|
||||
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
|
||||
assert!(pdf.contains("/Separation/Crease"));
|
||||
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
|
||||
assert!(pdf.contains("/OP true"), "the role strokes overprint");
|
||||
// Without overprint, nothing in the file overprints.
|
||||
let mut plain = session("cmyk");
|
||||
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
|
||||
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
|
||||
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
|
||||
let bytes = vectorcraft_pdf::export(
|
||||
&plain.doc().unwrap().doc,
|
||||
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
|
||||
assert!(!export(&mut s, "pdf").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
|
||||
let mut s = two_roles();
|
||||
let svg = export(&mut s, "svg");
|
||||
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
|
||||
let strokes = if strokes.is_empty() {
|
||||
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
|
||||
} else {
|
||||
strokes
|
||||
};
|
||||
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
|
||||
let dxf = export(&mut s, "dxf");
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The rectangles' white fills come out as true colors too.
|
||||
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
|
||||
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
|
||||
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
|
||||
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
|
||||
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_paths_carry_a_role() {
|
||||
let mut s = session("cmyk");
|
||||
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
|
||||
assert_eq!(r["ids"], json!([c.0]));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
|
||||
// A member named by id gives its compound the role.
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
}
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
|
||||
@@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
let through: Vec<NodeId> = match p.get("through") {
|
||||
None => vec![],
|
||||
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
|
||||
Some(v) => {
|
||||
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
|
||||
ids.iter()
|
||||
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
|
||||
.collect::<Result<_>>()?
|
||||
}
|
||||
};
|
||||
let (eid, count, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
@@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
LpScope::Connected => b::connected_edges(n, eid, &like),
|
||||
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
.collect(),
|
||||
|
||||
@@ -595,6 +595,8 @@ struct Relink {
|
||||
styles: BTreeMap<u32, u32>,
|
||||
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
|
||||
colors: BTreeMap<String, Color>,
|
||||
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
|
||||
keep_styles: bool,
|
||||
}
|
||||
|
||||
impl Relink {
|
||||
@@ -674,7 +676,9 @@ impl Relink {
|
||||
/// Relink a node tree (the mirror of [`node_refs`]).
|
||||
fn node(&self, n: &mut Node) {
|
||||
self.appearance(&mut n.appearance);
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
if !self.keep_styles {
|
||||
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
self.node(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
@@ -1109,6 +1113,30 @@ impl Clipboard {
|
||||
self.import_used(d, &self.used(), choices, same_doc)
|
||||
}
|
||||
|
||||
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
|
||||
/// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste
|
||||
/// without Formatting sets its pie legend labels' contrast from the wedge colors before it
|
||||
/// pastes). Nothing changes for the document the objects came from (`same_doc`).
|
||||
pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) {
|
||||
if same_doc {
|
||||
return;
|
||||
}
|
||||
let used = self.used();
|
||||
let colors: BTreeMap<String, Color> = self
|
||||
.conflicts(d, &used)
|
||||
.into_iter()
|
||||
.filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge)
|
||||
.filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c)))
|
||||
.collect();
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
let relink = Relink { colors, keep_styles: true, ..Default::default() };
|
||||
for n in &mut self.nodes {
|
||||
relink.node(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
|
||||
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
|
||||
/// compared and relinked with their names here, and each loop of definitions that use each
|
||||
|
||||
@@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
|
||||
*p0 = end;
|
||||
if pts.len() < 2 {
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already.
|
||||
// No stroke to add: the brush alone changes, when it is not the path's already, and the
|
||||
// path is selected or deselected as a longer continuation leaves it.
|
||||
if let Some(name) = brush_name
|
||||
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
|
||||
{
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
s.edit("Paintbrush", |d, sel| {
|
||||
set_brush(d, target, name);
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -367,7 +367,8 @@ fn edit_effects(
|
||||
|
||||
/// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and
|
||||
/// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share
|
||||
/// is left out of it, and a target sharing none of them is left out.
|
||||
/// is left out of it, and a target sharing none of them is left out. A position no target has is
|
||||
/// an error with `none`, and nothing changes.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects_at(
|
||||
s: &mut Session,
|
||||
@@ -396,7 +397,12 @@ fn edit_effects_at(
|
||||
// Each target's list and the positions in it, in the order the targets first come up.
|
||||
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
|
||||
for &index in indices {
|
||||
for (id, at, i) in effect_targets(s, p, item, index, cmd)? {
|
||||
let found = effect_targets(s, p, item, index, cmd)?;
|
||||
// An aligned effect of a design's art that no other object has is refused, as it is given alone.
|
||||
if found.is_empty() {
|
||||
return Err(EngineError::Other(none.into()));
|
||||
}
|
||||
for (id, at, i) in found {
|
||||
match targets.iter_mut().find(|t| t.0 == id && t.1 == at) {
|
||||
Some(t) => t.2.push(i),
|
||||
None => targets.push((id, at, vec![i])),
|
||||
|
||||
@@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
|
||||
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
|
||||
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
|
||||
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
|
||||
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the
|
||||
/// path filled with its run's stroke under a transform that is not a similarity, has one
|
||||
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
|
||||
/// the document as it is and stops at the first such path.
|
||||
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
|
||||
let gradient =
|
||||
|st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_)));
|
||||
if !t.runs.iter().any(|r| gradient(&r.style)) {
|
||||
return false;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let first = t.first_style();
|
||||
let expands = |run: usize, outline: &BezPath| {
|
||||
let style = t.runs.get(run).map_or(&first, |r| &r.style);
|
||||
if !matches!(style.fill, Paint::Gradient(_)) {
|
||||
if !gradient(style) {
|
||||
return false;
|
||||
}
|
||||
let path = PathData::from_bezpath(outline);
|
||||
@@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
return false;
|
||||
}
|
||||
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
|
||||
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
|
||||
gradient_expands(d, &piece)
|
||||
let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
|
||||
gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s))
|
||||
};
|
||||
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
|
||||
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|
||||
|
||||
@@ -894,12 +894,19 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
return Some(format!("an image of {w} × {h} pixels is too large to draw"));
|
||||
}
|
||||
let d = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?;
|
||||
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let format = reader.format()?;
|
||||
let d = reader.into_decoder().ok()?;
|
||||
let (w, h) = d.dimensions();
|
||||
// The allowance also counts the pixels as RGBA: an image of fewer than 4 bytes a pixel (gray,
|
||||
// gray with alpha, RGB) takes more than the decoder counts (#1717).
|
||||
let rgba_over = u64::from(w) * u64::from(h) > MAX_RASTER_ALLOC / 4;
|
||||
(rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
let samples_over = d.total_bytes() > MAX_RASTER_ALLOC;
|
||||
// The renderer can stream a non-interlaced PNG a row at a time when those buffers fit. Its
|
||||
// full decoded byte count can exceed the allowance even though drawing it at native size is
|
||||
// safe; use the renderer's decision for that case instead of warning from total_bytes alone.
|
||||
let png_streams_at_size = samples_over && format == image::ImageFormat::Png && vectorcraft_render::reduced_size(bytes) == Some((w, h));
|
||||
(rgba_over || (samples_over && !png_streams_at_size)).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
}
|
||||
|
||||
/// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -174,23 +174,48 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
/// blocks whose signature is `8BIM` are given.
|
||||
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
|
||||
let mut r = Reader::new(resources);
|
||||
std::iter::from_fn(move || {
|
||||
if r.rest().is_empty() {
|
||||
return None;
|
||||
std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() })
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
}
|
||||
|
||||
/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is
|
||||
/// none before the blocks end or before a block that is cut short ahead of it. An error when
|
||||
/// that block itself is cut short.
|
||||
pub(super) fn resource(resources: &[u8], id: u16) -> Result<Option<&[u8]>, String> {
|
||||
let mut r = Reader::new(resources);
|
||||
while !r.rest().is_empty() {
|
||||
match block(&mut r) {
|
||||
Ok((true, i, _, data)) if i == id => return Ok(Some(data)),
|
||||
Ok(_) => {}
|
||||
Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()),
|
||||
Err(_) => return Ok(None),
|
||||
}
|
||||
let ours = r.take(4).ok()? == b"8BIM";
|
||||
let id = r.u16().ok()?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its
|
||||
/// Pascal string) and its data.
|
||||
type Block<'a> = (bool, u16, &'a [u8], &'a [u8]);
|
||||
|
||||
/// The image resource block that `r` starts with. When it is cut short, the error gives whether
|
||||
/// its signature is `8BIM` and its id, when those were read.
|
||||
fn block<'a>(r: &mut Reader<'a>) -> Result<Block<'a>, Option<(bool, u16)>> {
|
||||
let ours = r.take(4).map_err(|_| None)? == b"8BIM";
|
||||
let id = r.u16().map_err(|_| None)?;
|
||||
let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> {
|
||||
// A Pascal string padded to an even size, length byte included.
|
||||
let len = usize::from(r.u8().ok()?);
|
||||
let name = r.take(len).ok()?;
|
||||
r.take((len + 1) % 2).ok()?;
|
||||
let size = usize::try_from(r.u32().ok()?).ok()?;
|
||||
let data = r.take(size).ok()?;
|
||||
r.take(size % 2).ok()?;
|
||||
Some((ours, id, name, data))
|
||||
})
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
let len = usize::from(r.u8()?);
|
||||
let name = r.take(len)?;
|
||||
r.take((len + 1) % 2)?;
|
||||
let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?;
|
||||
let data = r.take(size)?;
|
||||
r.take(size % 2)?;
|
||||
Ok((name, data))
|
||||
};
|
||||
let (name, data) = rest().map_err(|_| Some((ours, id)))?;
|
||||
Ok((ours, id, name, data))
|
||||
}
|
||||
|
||||
/// The resource naming the document's clipping path.
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
use vectorcraft_doc::{SliceKind, SliceOptions};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::psdread::{Reader, TRUNCATED, header, resources};
|
||||
use super::psdread::{Reader, TRUNCATED, header, resource};
|
||||
|
||||
/// The image resource that holds the slices.
|
||||
const SLICES: u16 = 1050;
|
||||
@@ -51,12 +51,12 @@ struct Stored {
|
||||
}
|
||||
|
||||
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
|
||||
/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB
|
||||
/// file, or its slices can't be read.
|
||||
/// before the image resources end, or before a block that is cut short ahead of it). An error when
|
||||
/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read.
|
||||
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r)?;
|
||||
let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) };
|
||||
let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) };
|
||||
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
|
||||
}
|
||||
|
||||
|
||||
@@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() {
|
||||
let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}}));
|
||||
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
|
||||
}
|
||||
|
||||
/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset,
|
||||
/// while `null` keeps the preset's value; an unknown value is a bad parameter.
|
||||
#[test]
|
||||
fn profiles_default_unsets_a_presets_profiles_setting() {
|
||||
use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion};
|
||||
let mut settings = PdfSettings::default();
|
||||
settings.output.profiles = Some(ProfileInclusion::None);
|
||||
let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }];
|
||||
let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved);
|
||||
assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None);
|
||||
assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None));
|
||||
assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All));
|
||||
let bad = resolve(json!({"profiles": "sometimes"}));
|
||||
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
|
||||
}
|
||||
|
||||
@@ -371,6 +371,29 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
|
||||
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slices_resource_cut_short_warns_and_the_file_still_opens() {
|
||||
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
|
||||
// Image resource `id`, the last of the image resources, declares 10 bytes more than they hold.
|
||||
let cut = |layers: bool, id: u16, data: &[u8]| {
|
||||
let mut f = with_resource(&psd(layers), id, data);
|
||||
let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat();
|
||||
let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8;
|
||||
f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes());
|
||||
f
|
||||
};
|
||||
for layers in [true, false] {
|
||||
let (s, r) = open(&cut(layers, 1050, &good), json!({}));
|
||||
let w = warnings(&r);
|
||||
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}");
|
||||
assert!(slices(&s).is_empty());
|
||||
assert!(s.doc().unwrap().doc.art_bounds().is_some());
|
||||
// Another resource cut short says nothing about slices.
|
||||
let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({}));
|
||||
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
|
||||
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
|
||||
|
||||
@@ -1109,6 +1109,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() {
|
||||
assert!(rows(&s, mark).effects.is_empty());
|
||||
}
|
||||
|
||||
/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an
|
||||
/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone.
|
||||
#[test]
|
||||
fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() {
|
||||
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
|
||||
let (mut s, _, art, mark) = aligned_design_art();
|
||||
// The art has a shadow and a roughen, the mark the shadow only.
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap();
|
||||
s.edit("Effects", |d, _| {
|
||||
let effects = d.node(mark).unwrap().appearance.effects.clone();
|
||||
d.node_mut(art).unwrap().appearance.effects = effects;
|
||||
d.node_mut(mark).unwrap().appearance.effects.pop();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for cmd in ["effect.remove", "effect.duplicate"] {
|
||||
assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}");
|
||||
let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err();
|
||||
assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}");
|
||||
assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
|
||||
}
|
||||
// With the roughen on the mark too, both of its effects are removed.
|
||||
s.edit("Roughen", |d, _| {
|
||||
let roughen = d.node(art).unwrap().appearance.effects[1].clone();
|
||||
d.node_mut(mark).unwrap().appearance.effects.push(roughen);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap();
|
||||
assert!(rows(&s, mark).effects.is_empty());
|
||||
}
|
||||
|
||||
/// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art:
|
||||
/// Expand Appearance does not put the art back beside the image.
|
||||
#[test]
|
||||
|
||||
@@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let paint = if span {
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it.
|
||||
let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect();
|
||||
placed_across(&s.doc()?.doc, &spanned, paint, p, fill)
|
||||
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
|
||||
// object's box is that of the row it edits.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut spanned = Vec::with_capacity(ids.len());
|
||||
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
|
||||
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
|
||||
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
|
||||
}
|
||||
placed_across(d, &spanned, paint, p, fill)
|
||||
} else {
|
||||
paint
|
||||
};
|
||||
@@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its
|
||||
/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in
|
||||
/// document coordinates, so the ramp runs on across them (#2127).
|
||||
fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint {
|
||||
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the
|
||||
/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle
|
||||
/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on
|
||||
/// across them (#2127).
|
||||
fn placed_across(d: &Document, ids: &[(NodeId, Option<usize>)], paint: Paint, p: &Value, fill: bool) -> Paint {
|
||||
let union = ids
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds()))
|
||||
.filter_map(|(id, index)| Some((d.node(*id)?, *index)))
|
||||
.filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds()))
|
||||
.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
|
||||
.reduce(|a, b| a.union(b));
|
||||
let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint };
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -38,7 +38,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use roxmltree::Node;
|
||||
use craft_xml::{Canonical, Doctype, El, Limits, Names, Options};
|
||||
use vectorcraft_doc::text::Kashida;
|
||||
use vectorcraft_doc::{CharPosition, CharStyle, Justify, ParaDirection, ParaStyle, ScriptMetrics, TextRun};
|
||||
|
||||
@@ -88,6 +88,7 @@ const MAX_RUNS: usize = 100_000;
|
||||
|
||||
/// WordprocessingML's namespaces: Transitional, then Strict.
|
||||
const W: [&str; 2] = ["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"];
|
||||
const DOCX_NS: Canonical<'static> = Canonical::new(&[("w", W[0]), ("w", W[1])]);
|
||||
|
||||
/// Is the file `name` with `bytes` a Word document: a ZIP archive named `.docx`, or one that holds
|
||||
/// `word/document.xml`?
|
||||
@@ -104,7 +105,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
let main = relationship(&zip, "", "officeDocument", cmd)?.unwrap_or_else(|| "word/document.xml".into());
|
||||
let Some(xml) = part(&zip, &main, cmd)? else { return Err(bad(cmd, "not a Word document: its package has no main document part")) };
|
||||
let doc = parse(&xml, &main, cmd)?;
|
||||
if local(doc.root_element()) != Some("document") {
|
||||
if local(&doc) != Some("document") {
|
||||
return Err(bad(cmd, "not a Word document: its main part is not a WordprocessingML document"));
|
||||
}
|
||||
let folder = main.rfind('/').and_then(|i| main.get(..=i)).unwrap_or_default();
|
||||
@@ -117,7 +118,7 @@ pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
if let Some(xml) = part(&zip, &styles, cmd)? {
|
||||
r.styles(&parse(&xml, &styles, cmd)?);
|
||||
}
|
||||
if let Some(body) = doc.root_element().children().find(|n| local(*n) == Some("body")) {
|
||||
if let Some(body) = child(&doc, "body") {
|
||||
r.block(body, 0);
|
||||
}
|
||||
r.finish(cmd)
|
||||
@@ -158,57 +159,21 @@ fn part(zip: &Archive, name: &str, cmd: &str) -> Result<Option<String>> {
|
||||
}
|
||||
|
||||
/// The XML of the part `name`.
|
||||
fn parse<'a>(xml: &'a str, name: &str, cmd: &str) -> Result<roxmltree::Document<'a>> {
|
||||
// roxmltree parses nested elements recursively.
|
||||
if nesting(xml) > MAX_NESTING {
|
||||
return Err(bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")));
|
||||
fn parse(xml: &str, name: &str, cmd: &str) -> Result<El> {
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&DOCX_NS),
|
||||
doctype: Doctype::Reject,
|
||||
limits: Limits { max_depth: MAX_NESTING, max_nodes: MAX_NODES as usize, ..Limits::DEFAULT },
|
||||
..Options::default()
|
||||
}
|
||||
let opts = roxmltree::ParsingOptions { nodes_limit: MAX_NODES, ..roxmltree::ParsingOptions::default() };
|
||||
roxmltree::Document::parse_with_options(xml, opts).map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))
|
||||
}
|
||||
|
||||
/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments,
|
||||
/// CDATA sections, processing instructions, declarations and quoted attribute values.
|
||||
pub(crate) fn nesting(xml: &str) -> usize {
|
||||
let b = xml.as_bytes();
|
||||
let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize);
|
||||
// The index just past the first `end` at or after `from` (the end of the text if none).
|
||||
let past = |from: usize, end: &[u8]| {
|
||||
b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len())
|
||||
};
|
||||
while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) {
|
||||
let start = i + at;
|
||||
let rest = b.get(start..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = past(start + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = past(start + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = past(start + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(usize::from(rest.starts_with(b"</")));
|
||||
i = past(start + 2, b">");
|
||||
} else {
|
||||
// A start tag: up to its `>` outside quotes; `/>` closes it at once.
|
||||
let mut j = start + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match (quote, c) {
|
||||
(None, b'"' | b'\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, b'>') => break,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.saturating_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
most = most.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
most
|
||||
.strict();
|
||||
let doc = opts.parse(xml.as_bytes()).map_err(|e| match e {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")),
|
||||
_ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits)
|
||||
.map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?;
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// The part that the first relationship of part `source` (`""`: the package) whose type ends in
|
||||
@@ -220,11 +185,10 @@ fn relationship(zip: &Archive, source: &str, kind: &str, cmd: &str) -> Result<Op
|
||||
let Some(xml) = part(zip, &rels, cmd)? else { return Ok(None) };
|
||||
let doc = parse(&xml, &rels, cmd)?;
|
||||
let target = doc
|
||||
.root_element()
|
||||
.children()
|
||||
.filter(|n| n.tag_name().name() == "Relationship" && n.attribute("TargetMode") != Some("External"))
|
||||
.find(|n| n.attribute("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attribute("Target"));
|
||||
.elements()
|
||||
.filter(|n| n.local() == "Relationship" && n.attr("TargetMode") != Some("External"))
|
||||
.find(|n| n.attr("Type").is_some_and(|t| t.rsplit('/').next() == Some(kind)))
|
||||
.and_then(|n| n.attr("Target"));
|
||||
Ok(target.map(|t| resolve(folder, t)))
|
||||
}
|
||||
|
||||
@@ -248,22 +212,22 @@ fn resolve(folder: &str, target: &str) -> String {
|
||||
}
|
||||
|
||||
/// `n`'s local name when it is a WordprocessingML element.
|
||||
fn local<'a>(n: Node<'a, '_>) -> Option<&'a str> {
|
||||
(n.is_element() && n.tag_name().namespace().is_some_and(|ns| W.contains(&ns))).then(|| n.tag_name().name())
|
||||
fn local(n: &El) -> Option<&str> {
|
||||
n.name.strip_prefix("w:")
|
||||
}
|
||||
|
||||
/// `n`'s first WordprocessingML child element named `name`.
|
||||
fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
|
||||
n.children().find(|c| local(*c) == Some(name))
|
||||
fn child<'a>(n: &'a El, name: &str) -> Option<&'a El> {
|
||||
n.elements().find(|c| local(c) == Some(name))
|
||||
}
|
||||
|
||||
/// `n`'s WordprocessingML attribute `name`.
|
||||
fn attr<'a>(n: Node<'a, '_>, name: &str) -> Option<&'a str> {
|
||||
n.attributes().find(|a| a.name() == name && a.namespace().is_some_and(|ns| W.contains(&ns))).map(|a| a.value())
|
||||
fn attr<'a>(n: &'a El, name: &str) -> Option<&'a str> {
|
||||
n.attrs.iter().find_map(|(k, v)| k.strip_prefix("w:").filter(|&l| l == name).map(|_| v.as_str()))
|
||||
}
|
||||
|
||||
/// An on/off property (ST_OnOff): on unless `w:val` is `false`, `0` or `off`.
|
||||
fn on(n: Node) -> bool {
|
||||
fn on(n: &El) -> bool {
|
||||
!matches!(attr(n, "val"), Some("false" | "0" | "off"))
|
||||
}
|
||||
|
||||
@@ -280,12 +244,12 @@ fn measure(v: &str, per_pt: f64) -> Option<f64> {
|
||||
}
|
||||
|
||||
/// Twentieths of a point.
|
||||
fn twips(n: Node, name: &str) -> Option<f64> {
|
||||
fn twips(n: &El, name: &str) -> Option<f64> {
|
||||
attr(n, name).and_then(|v| measure(v, 20.0))
|
||||
}
|
||||
|
||||
/// Half points.
|
||||
fn half_points(n: Node) -> Option<f64> {
|
||||
fn half_points(n: &El) -> Option<f64> {
|
||||
attr(n, "val").and_then(|v| measure(v, 2.0))
|
||||
}
|
||||
|
||||
@@ -462,21 +426,21 @@ struct Reader {
|
||||
|
||||
impl Reader {
|
||||
/// The major and minor fonts of a theme part's font scheme.
|
||||
fn theme_fonts(&mut self, doc: &roxmltree::Document) {
|
||||
fn theme_fonts(&mut self, doc: &El) {
|
||||
for (slot, scheme) in self.theme.iter_mut().zip(["majorFont", "minorFont"]) {
|
||||
*slot = doc
|
||||
.descendants()
|
||||
.find(|n| n.tag_name().name() == scheme)
|
||||
.and_then(|n| n.children().find(|c| c.tag_name().name() == "latin"))
|
||||
.and_then(|n| n.attribute("typeface"))
|
||||
*slot = std::iter::once(doc)
|
||||
.chain(doc.descendants())
|
||||
.find(|n| n.local() == scheme)
|
||||
.and_then(|n| n.elements().find(|c| c.local() == "latin"))
|
||||
.and_then(|n| n.attr("typeface"))
|
||||
.map(font_name)
|
||||
.filter(|f| !f.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// The document defaults and the styles of the styles part.
|
||||
fn styles(&mut self, doc: &roxmltree::Document) {
|
||||
for n in doc.root_element().children() {
|
||||
fn styles(&mut self, doc: &El) {
|
||||
for n in doc.elements() {
|
||||
match local(n) {
|
||||
Some("docDefaults") => {
|
||||
let props = |outer: &str, inner: &str| child(n, outer).and_then(|d| child(d, inner));
|
||||
@@ -526,7 +490,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The number of the font a `w:rFonts` element names.
|
||||
fn font(&mut self, n: Node) -> Option<usize> {
|
||||
fn font(&mut self, n: &El) -> Option<usize> {
|
||||
let theme = |v: &str| self.theme.get(usize::from(v.starts_with("minor"))).and_then(Option::as_deref);
|
||||
let name = attr(n, "asciiTheme")
|
||||
.and_then(theme)
|
||||
@@ -549,9 +513,9 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The run properties of a `w:rPr` element.
|
||||
fn run_props(&mut self, rpr: Node) -> RunProps {
|
||||
fn run_props(&mut self, rpr: &El) -> RunProps {
|
||||
let mut p = RunProps::default();
|
||||
for n in rpr.children() {
|
||||
for n in rpr.elements() {
|
||||
match local(n) {
|
||||
Some("rFonts") => p.font = self.font(n),
|
||||
Some("b") => p.bold = Some(on(n)),
|
||||
@@ -594,11 +558,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The paragraphs, tables and containers of them that are `n`'s children.
|
||||
fn block(&mut self, n: Node, depth: usize) {
|
||||
fn block(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
if self.full {
|
||||
return;
|
||||
}
|
||||
@@ -617,7 +581,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A table: each row a paragraph, its cells separated by tabs.
|
||||
fn table(&mut self, tbl: Node, depth: usize) {
|
||||
fn table(&mut self, tbl: &El, depth: usize) {
|
||||
for row in items(tbl, "tr", depth) {
|
||||
for cell in items(row, "tc", depth) {
|
||||
self.flush();
|
||||
@@ -638,7 +602,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A paragraph.
|
||||
fn paragraph(&mut self, p: Node, depth: usize) {
|
||||
fn paragraph(&mut self, p: &El, depth: usize) {
|
||||
self.flush();
|
||||
let ppr = child(p, "pPr");
|
||||
let style = ppr
|
||||
@@ -675,11 +639,11 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// The runs of a paragraph, and the containers of runs in it.
|
||||
fn inline(&mut self, n: Node, depth: usize) {
|
||||
fn inline(&mut self, n: &El, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some("r") => self.run(c),
|
||||
Some("hyperlink" | "ins" | "moveTo" | "smartTag" | "customXml" | "fldSimple" | "dir" | "bdo") => self.inline(c, depth + 1),
|
||||
@@ -694,7 +658,7 @@ impl Reader {
|
||||
}
|
||||
|
||||
/// A run.
|
||||
fn run(&mut self, r: Node) {
|
||||
fn run(&mut self, r: &El) {
|
||||
let rpr = child(r, "rPr");
|
||||
let mut chars = self.base;
|
||||
let style = rpr
|
||||
@@ -709,11 +673,10 @@ impl Reader {
|
||||
let props = self.run_props(n);
|
||||
chars.apply(&props, false);
|
||||
}
|
||||
for c in r.children() {
|
||||
for c in r.elements() {
|
||||
match local(c) {
|
||||
Some("t") => {
|
||||
// Comments and processing instructions may split the text.
|
||||
for ch in c.children().filter(|n| n.is_text()).filter_map(|n| n.text()).flat_map(str::chars) {
|
||||
for ch in c.text().chars() {
|
||||
self.put(ch, chars);
|
||||
}
|
||||
}
|
||||
@@ -907,9 +870,9 @@ fn font_name(name: &str) -> String {
|
||||
}
|
||||
|
||||
/// The paragraph properties of a `w:pPr` element.
|
||||
fn para_props(ppr: Node) -> ParaProps {
|
||||
fn para_props(ppr: &El) -> ParaProps {
|
||||
let mut p = ParaProps::default();
|
||||
for n in ppr.children() {
|
||||
for n in ppr.elements() {
|
||||
match local(n) {
|
||||
Some("jc") => {
|
||||
p.align = match attr(n, "val") {
|
||||
@@ -945,12 +908,12 @@ fn para_props(ppr: Node) -> ParaProps {
|
||||
}
|
||||
|
||||
/// `n`'s children named `name`, and those inside content controls and custom XML among them.
|
||||
fn items<'a, 'i>(n: Node<'a, 'i>, name: &str, depth: usize) -> Vec<Node<'a, 'i>> {
|
||||
fn items<'a>(n: &'a El, name: &str, depth: usize) -> Vec<&'a El> {
|
||||
let mut out = vec![];
|
||||
if depth > MAX_DEPTH {
|
||||
return out;
|
||||
}
|
||||
for c in n.children() {
|
||||
for c in n.elements() {
|
||||
match local(c) {
|
||||
Some(l) if l == name => out.push(c),
|
||||
Some("sdt") => {
|
||||
@@ -979,15 +942,6 @@ mod tests {
|
||||
assert_eq!(measure("wide", 20.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_counts_elements_outside_markup_that_is_not_an_element() {
|
||||
assert_eq!(nesting(r#"<?xml version="1.0"?><a><b x="1>2" y='</c>'><c/></b><!-- <d><e> --><![CDATA[<f><g>]]></a>"#), 2);
|
||||
assert_eq!(nesting("<a><b><c>"), 3, "unclosed elements count");
|
||||
assert_eq!(nesting("</a></b><a>"), 1);
|
||||
assert_eq!(nesting("<a x=\"unterminated"), 1);
|
||||
assert_eq!(nesting(""), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_resolve_against_their_folder() {
|
||||
assert_eq!(resolve("", "word/document.xml"), "word/document.xml");
|
||||
|
||||
@@ -40,6 +40,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.image.colorMask",
|
||||
"addon.image.removeBackground",
|
||||
"addon.image.removeColorMask",
|
||||
"addon.packaging.roles",
|
||||
"addon.packaging.setRole",
|
||||
"addon.packaging.setRoleSwatch",
|
||||
"addon.pathtools.addPoints",
|
||||
"addon.pathtools.close",
|
||||
"addon.pathtools.corner",
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
has_doc,
|
||||
swatch_edit
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Merge Swatches",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step → {name, merged: [deleted names], relinked}",
|
||||
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}",
|
||||
has_doc,
|
||||
swatch_merge
|
||||
),
|
||||
@@ -937,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t));
|
||||
// A fold line role carried by the swatch follows its new name, as the strokes do.
|
||||
super::addons::role_swatch_edited(d, &name, &to, global);
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
@@ -1139,6 +1141,8 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
take_swatches(d, merged, |_| true);
|
||||
map_all_paints(d, &mut unplate);
|
||||
let relinked = map_swatch_links(d, &mut relink);
|
||||
// The lines of a merged role swatch link to the kept swatch, which takes that role.
|
||||
super::addons::role_swatches_merged(d, merged, keep, link.is_some());
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok(relinked)
|
||||
})?;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
("akiLeft", json!(v.aki_left)),
|
||||
("akiRight", json!(v.aki_right)),
|
||||
("tsume", json!(v.tsume)),
|
||||
("diacriticHorizontal", json!(v.diacritic_horizontal)),
|
||||
("diacriticVertical", json!(v.diacritic_vertical)),
|
||||
("standardVerticalRoman", json!(v.standard_vertical_roman)),
|
||||
("noBreak", json!(v.no_break)),
|
||||
("digits", json!(v.digits)),
|
||||
@@ -584,6 +586,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
if changed(key) && !(lo..=hi).contains(&st.tsume) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
|
||||
let lo = -hi;
|
||||
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
|
||||
if changed(key) && !(lo..=hi).contains(&value) {
|
||||
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
|
||||
}
|
||||
}
|
||||
let lines = vectorcraft_doc::text::WARICHU_LINES;
|
||||
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
|
||||
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
@@ -1081,12 +1090,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 22] = [
|
||||
const RANGED: [&str; 24] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
@@ -1095,6 +1104,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
"akiLeft",
|
||||
"akiRight",
|
||||
"tsume",
|
||||
"diacriticHorizontal",
|
||||
"diacriticVertical",
|
||||
"tcyUpDown",
|
||||
"tcyLeftRight",
|
||||
"warichuLines",
|
||||
|
||||
@@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
json!({"akiRight": 1000.1}),
|
||||
json!({"tsume": -0.1}),
|
||||
json!({"tsume": 100.1}),
|
||||
json!({"diacriticHorizontal": -1000.1}),
|
||||
json!({"diacriticVertical": 1000.1}),
|
||||
] {
|
||||
let key = attrs.as_object().unwrap().keys().next().unwrap();
|
||||
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
|
||||
@@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
|
||||
"baseline_shift": -1296.0,
|
||||
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
|
||||
"akiLeft": 0.0, "akiRight": 1000.0,
|
||||
"tsume": 100.0
|
||||
"tsume": 100.0,
|
||||
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Outlines",
|
||||
["Type"],
|
||||
Some("Cmd+Shift+O"),
|
||||
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
|
||||
"{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
|
||||
has_selection,
|
||||
create_outlines
|
||||
),
|
||||
@@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as
|
||||
/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced
|
||||
/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's
|
||||
/// transform); `None` when the piece has no path.
|
||||
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> {
|
||||
/// transform), followed by a path (or compound path) filled with the run's stroke when the type's
|
||||
/// transform is not a similarity; empty when the piece has no path.
|
||||
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec<Node> {
|
||||
let path = PathData::from_bezpath(outline);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
return vec![];
|
||||
}
|
||||
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
|
||||
let mut node = shape_node(d, path, None);
|
||||
vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
|
||||
Some(node)
|
||||
let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
|
||||
let mut out = vec![node];
|
||||
if let Some(s) = stroke
|
||||
&& let Some(path) = s.path_data()
|
||||
{
|
||||
let mut filled = shape_node(d, path.clone(), None);
|
||||
filled.appearance = s.appearance.clone();
|
||||
out.push(filled);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
children.push(Arc::new(d.reid(&art)));
|
||||
break 'glyph;
|
||||
}
|
||||
if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) {
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new));
|
||||
}
|
||||
run_end.insert(g.run, children.len());
|
||||
}
|
||||
@@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// nothing there either).
|
||||
let mut ruby: Vec<(usize, Arc<Node>)> = vec![];
|
||||
for g in &lay.ruby {
|
||||
let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue };
|
||||
// After the glyphs of its run and of the runs before it.
|
||||
let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0);
|
||||
ruby.push((at, Arc::new(node)));
|
||||
ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node))));
|
||||
}
|
||||
ruby.sort_by_key(|(at, _)| *at);
|
||||
let mut ruby = ruby.into_iter().peekable();
|
||||
@@ -711,9 +717,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// Underline and strikethrough bars become paths of their run's paint too (#847).
|
||||
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
|
||||
all.extend(bar.iter());
|
||||
if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) {
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new));
|
||||
}
|
||||
// The object's own fills and strokes (not its characters') paint the whole outline:
|
||||
// those below the Characters row under the characters, the others over them, with
|
||||
|
||||
@@ -1921,6 +1921,66 @@ fn tsume_is_a_character_attribute() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options):
|
||||
/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both
|
||||
/// commands set them in one undo step, setting one leaves the other, a call that gives the values
|
||||
/// the text already has records none, and a value that is not a number or lies outside -1000 to
|
||||
/// 1000 is refused, naming the key, before anything changes; the native file and a character style
|
||||
/// captured from the characters carry them.
|
||||
#[test]
|
||||
fn diacritic_positions_are_character_attributes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "بَب"})).unwrap()["id"].as_u64().unwrap();
|
||||
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::<Vec<_>>();
|
||||
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
|
||||
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap();
|
||||
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
|
||||
let mark = "بَ".len();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap();
|
||||
assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]);
|
||||
let saved = serde_json::to_value(&runs(&s)[1].style).unwrap();
|
||||
assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect();
|
||||
assert_eq!(reopened, moved(&s));
|
||||
let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style);
|
||||
assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
|
||||
|
||||
let before = moved(&s);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, p, want) in [
|
||||
("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"),
|
||||
("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"),
|
||||
("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"),
|
||||
(
|
||||
"text.setRangeStyle",
|
||||
json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}),
|
||||
"`diacriticHorizontal` must be from -1000 to 1000",
|
||||
),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!(moved(&s), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
|
||||
}
|
||||
|
||||
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
|
||||
/// attribute, off by default and saved only when on. Documents written before it read as off; a
|
||||
/// character style captured from the characters carries it.
|
||||
|
||||
@@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
|
||||
|
||||
fn paste_plain(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let saved = s.clipboard.nodes.clone();
|
||||
// Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take
|
||||
// the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error.
|
||||
if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) {
|
||||
let same_doc = s.clipboard.source_doc == Some(st.uid);
|
||||
let d = std::sync::Arc::clone(&st.doc);
|
||||
s.clipboard.show_merged_colors(&d, &choices, same_doc);
|
||||
}
|
||||
for n in &mut s.clipboard.nodes {
|
||||
strip_formatting(n);
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ fn library_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
|
||||
/// up to [`MAX_LIBRARY_ENTITIES`] entity declarations, each with a name of at most [`MAX_NAME`]
|
||||
/// bytes and a quoted value that holds no `<`, `&` or `%`. Anything else in it is refused, and so is
|
||||
/// a text that the replacements make longer than [`MAX_LIBRARY_BYTES`]. The XML parser then refuses
|
||||
/// any other document type declaration, so [`nesting`](super::place::docx::nesting) counts the
|
||||
/// elements the parser reads.
|
||||
/// any other document type declaration, so its depth and node limits count the elements it
|
||||
/// reads.
|
||||
fn without_doctype(xml: &str, cmd: &str) -> Result<String> {
|
||||
let b = xml.as_bytes();
|
||||
let past = |from: usize, end: &str| xml.get(from..).and_then(|rest| rest.find(end)).map(|at| from + at + end.len());
|
||||
@@ -240,22 +240,25 @@ impl Library {
|
||||
/// type declaration defines are read as [`without_doctype`] says.
|
||||
fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
let xml = without_doctype(xml, cmd)?;
|
||||
// roxmltree parses nested elements recursively.
|
||||
if crate::cmd::place::docx::nesting(&xml) > MAX_LIBRARY_NESTING {
|
||||
return Err(bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")));
|
||||
let opts = craft_xml::Options {
|
||||
names: craft_xml::Names::AsWritten,
|
||||
limits: craft_xml::Limits { max_depth: MAX_LIBRARY_NESTING, max_nodes: MAX_LIBRARY_NODES as usize, ..craft_xml::Limits::DEFAULT },
|
||||
..craft_xml::Options::default()
|
||||
}
|
||||
let opts = roxmltree::ParsingOptions { nodes_limit: MAX_LIBRARY_NODES, ..roxmltree::ParsingOptions::default() };
|
||||
let doc =
|
||||
roxmltree::Document::parse_with_options(&xml, opts).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
|
||||
let is = |n: &roxmltree::Node, name: &str| n.is_element() && n.tag_name().name() == name;
|
||||
let Some(root) = doc.descendants().find(|n| is(n, "variableSets")) else {
|
||||
.strict();
|
||||
let doc = opts.parse(xml.as_bytes()).map_err(|e| match e {
|
||||
craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")),
|
||||
_ => bad(cmd, format!("the variable library is not well-formed XML: {e}")),
|
||||
})?;
|
||||
crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?;
|
||||
let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else {
|
||||
return Err(bad(cmd, "the file holds no `variableSets` element"));
|
||||
};
|
||||
let sets: Vec<roxmltree::Node> = root.children().filter(|n| is(n, "variableSet")).collect();
|
||||
let sets: Vec<&craft_xml::El> = root.children(craft_xml::Local("variableSet")).collect();
|
||||
let (mut variables, mut kinds, mut refs) = (Vec::new(), BTreeMap::new(), Vec::new());
|
||||
for var in sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "variables")).flat_map(|v| v.children()).filter(|n| is(n, "variable")) {
|
||||
let name = named(var.attribute("varName"), "varName", cmd)?;
|
||||
let trait_name = var.attribute("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>());
|
||||
for var in sets.iter().flat_map(|s| s.children(craft_xml::Local("variables"))).flat_map(|v| v.children(craft_xml::Local("variable"))) {
|
||||
let name = named(var.attr("varName"), "varName", cmd)?;
|
||||
let trait_name = var.attr("trait").map(|t| t.chars().take(MAX_NAME).collect::<String>());
|
||||
let kind = trait_kind(trait_name.as_deref());
|
||||
if kinds.insert(name.clone(), kind).is_some() {
|
||||
return Err(bad(cmd, format!("variable `{name}` is declared twice")));
|
||||
@@ -265,7 +268,7 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
}
|
||||
if kind == VariableKind::Text {
|
||||
// `docRef="id('…')"` names the element of the variable's bound object.
|
||||
let element = var.attribute("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
let element = var.attr("docRef").and_then(|r| r.trim().strip_prefix("id('")?.strip_suffix("')")).filter(|e| !e.is_empty());
|
||||
if let Some(element) = element {
|
||||
refs.push((name.clone(), element.to_string()));
|
||||
}
|
||||
@@ -276,10 +279,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
return Err(bad(cmd, "the variable library declares no variables"));
|
||||
}
|
||||
let (mut datasets, mut seen) = (Vec::new(), BTreeSet::new());
|
||||
for row in
|
||||
sets.iter().flat_map(|s| s.children()).filter(|n| is(n, "sampleDataSets")).flat_map(|d| d.children()).filter(|n| is(n, "sampleDataSet"))
|
||||
{
|
||||
let name = named(row.attribute("dataSetName"), "dataSetName", cmd)?;
|
||||
for row in sets.iter().flat_map(|s| s.children(craft_xml::Local("sampleDataSets"))).flat_map(|d| d.children(craft_xml::Local("sampleDataSet"))) {
|
||||
let name = named(row.attr("dataSetName"), "dataSetName", cmd)?;
|
||||
if !seen.insert(name.clone()) {
|
||||
return Err(bad(cmd, format!("data set `{name}` is declared twice")));
|
||||
}
|
||||
@@ -287,8 +288,8 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
return Err(bad(cmd, format!("the variable library declares more than {MAX_LIBRARY_DATASETS} data sets")));
|
||||
}
|
||||
let (mut values, mut held) = (BTreeMap::new(), BTreeSet::new());
|
||||
for el in row.children().filter(roxmltree::Node::is_element) {
|
||||
let var = el.tag_name().name();
|
||||
for el in row.elements() {
|
||||
let var = el.local();
|
||||
let Some(kind) = kinds.get(var) else {
|
||||
return Err(bad(cmd, format!("data set `{name}` holds a value for `{var}`, which the library doesn't declare")));
|
||||
};
|
||||
@@ -315,12 +316,12 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result<Library> {
|
||||
/// white space round them, and an element holding only white space gives none. A variable of
|
||||
/// unknown kind takes no value, so what its element holds is passed over. `set` names the data set
|
||||
/// in the errors.
|
||||
fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.tag_name().name()));
|
||||
let text = || if elements(el).next().is_some() { None } else { Some(deep_text(el)) };
|
||||
fn library_value(el: &craft_xml::El, kind: VariableKind, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let refused = |what: &str| bad(cmd, format!("data set `{set}` holds a value for `{}` that isn't {what}", el.local()));
|
||||
let text = || if el.elements().next().is_some() { None } else { Some(el.deep_text()) };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
let paras: Vec<String> = elements(el).filter(|n| n.tag_name().name() == "p").map(deep_text).collect();
|
||||
let paras: Vec<String> = el.children(craft_xml::Local("p")).map(craft_xml::El::deep_text).collect();
|
||||
Ok((!paras.is_empty()).then(|| DataValue::Text(paras.join("\n"))))
|
||||
}
|
||||
VariableKind::Visibility => {
|
||||
@@ -346,16 +347,6 @@ fn library_value(el: roxmltree::Node, kind: VariableKind, set: &str, cmd: &str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The elements among `n`'s children.
|
||||
fn elements<'a, 'i>(n: roxmltree::Node<'a, 'i>) -> impl Iterator<Item = roxmltree::Node<'a, 'i>> {
|
||||
n.children().filter(roxmltree::Node::is_element)
|
||||
}
|
||||
|
||||
/// The text of every text node inside `n`, in order.
|
||||
fn deep_text(n: roxmltree::Node) -> String {
|
||||
n.descendants().filter(roxmltree::Node::is_text).filter_map(|t| t.text()).collect()
|
||||
}
|
||||
|
||||
/// The absolute path a library's image value `text` names: a `file:` URL's path (`file:///…`,
|
||||
/// `file://localhost/…` or `file:/…`), its `%XX` escapes decoded (a URL with a host names a share,
|
||||
/// `//host/…`), or `text` itself. `None` unless that is an absolute path: one starting with `/` or
|
||||
@@ -428,29 +419,28 @@ fn library_file(path: &str) -> String {
|
||||
/// series, or when `el` holds only white space, there is no value. Anything else in `el`, more than
|
||||
/// [`MAX_GRAPH_CATEGORIES`] rows or [`MAX_GRAPH_SERIES`] series (what a graph holds), and CSV longer
|
||||
/// than graph values hold, are refused.
|
||||
fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let var = el.tag_name().name();
|
||||
fn graph_value(el: &craft_xml::El, set: &str, cmd: &str) -> Result<Option<DataValue>> {
|
||||
let var = el.local();
|
||||
let refused = || bad(cmd, format!("data set `{set}` holds a value for `{var}` that isn't a graph's `data` element"));
|
||||
let named = |name: &'static str| move |n: &roxmltree::Node| n.tag_name().name() == name;
|
||||
let mut children = elements(el);
|
||||
let named = |name: &'static str| craft_xml::Local(name);
|
||||
let mut children = el.elements();
|
||||
let data = match (children.next(), children.next()) {
|
||||
(None, _) if deep_text(el).trim_matches(XML_SPACE).is_empty() => return Ok(None),
|
||||
(Some(data), None) if data.tag_name().name() == "data" => data,
|
||||
(None, _) if el.deep_text().trim_matches(XML_SPACE).is_empty() => return Ok(None),
|
||||
(Some(data), None) if data.local() == "data" => data,
|
||||
_ => return Err(refused()),
|
||||
};
|
||||
// Labels keep their white space; numbers are read without it.
|
||||
let series: Vec<String> =
|
||||
elements(data).find(named("propertyRow")).map(|r| elements(r).filter(named("value")).skip(1).map(deep_text).collect()).unwrap_or_default();
|
||||
let rows: Vec<roxmltree::Node> =
|
||||
elements(data).filter(named("values")).flat_map(elements).filter(named("row")).take(MAX_GRAPH_CATEGORIES + 1).collect();
|
||||
data.child(named("propertyRow")).map(|r| r.children(named("value")).skip(1).map(craft_xml::El::deep_text).collect()).unwrap_or_default();
|
||||
let rows: Vec<&craft_xml::El> = data.children(named("values")).flat_map(|v| v.children(named("row"))).take(MAX_GRAPH_CATEGORIES + 1).collect();
|
||||
if rows.is_empty() && series.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let too_many = || bad(cmd, format!("data set `{set}` holds a graph value for `{var}` with {}", graph_limits()));
|
||||
// A row's values after its name.
|
||||
let wide = |row: &roxmltree::Node| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let _name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
let wide = |row: &&craft_xml::El| {
|
||||
let mut values = row.children(named("value")).peekable();
|
||||
let _name = values.next_if(|v| v.attr("key") == Some("name"));
|
||||
values.count() > MAX_GRAPH_SERIES
|
||||
};
|
||||
if rows.len() > MAX_GRAPH_CATEGORIES || series.len() > MAX_GRAPH_SERIES || rows.iter().any(wide) {
|
||||
@@ -462,12 +452,12 @@ fn graph_value(el: roxmltree::Node, set: &str, cmd: &str) -> Result<Option<DataV
|
||||
let read: Vec<(Option<String>, Vec<Option<f64>>)> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut values = elements(*row).filter(named("value")).peekable();
|
||||
let name = values.next_if(|v| v.attribute("key") == Some("name"));
|
||||
labelled |= name.is_some_and(|v| v.attribute("type") == Some("string") || !deep_text(v).is_empty());
|
||||
let name = name.map(deep_text);
|
||||
let number = |v: roxmltree::Node| deep_text(v).trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite());
|
||||
let numbers = values.map(|v| if v.attribute("type") == Some("string") { None } else { number(v) });
|
||||
let mut values = row.children(named("value")).peekable();
|
||||
let name = values.next_if(|v| v.attr("key") == Some("name"));
|
||||
labelled |= name.is_some_and(|v| v.attr("type") == Some("string") || !v.deep_text().is_empty());
|
||||
let name = name.map(craft_xml::El::deep_text);
|
||||
let number = |v: &craft_xml::El| v.deep_text().trim_matches(XML_SPACE).parse::<f64>().ok().filter(|n| n.is_finite());
|
||||
let numbers = values.map(|v| if v.attr("type") == Some("string") { None } else { number(v) });
|
||||
(name, numbers.collect())
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode.
|
||||
//!
|
||||
//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the
|
||||
//! shared strict reader and remove this second event pass when that dependency is updated.
|
||||
|
||||
/// Check names before canonical/local-name rewriting can collapse distinct attributes.
|
||||
/// The event reader and namespace scope use the same caller-supplied resource caps.
|
||||
pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict();
|
||||
let mut events = opts.events(xml);
|
||||
let mut bindings: Vec<(String, String)> = Vec::new();
|
||||
let mut scopes = Vec::new();
|
||||
while let Some(event) = events.next().map_err(|e| e.to_string())? {
|
||||
match event {
|
||||
craft_xml::Event::Start { attrs, .. } => {
|
||||
scopes.push(bindings.len());
|
||||
let mut raw = BTreeSet::new();
|
||||
for (key, value) in &attrs {
|
||||
if !raw.insert(key.as_str()) {
|
||||
return Err(format!("duplicate attribute `{key}`"));
|
||||
}
|
||||
if let Some(prefix) = key.strip_prefix("xmlns:") {
|
||||
if bindings.len() >= limits.max_attrs {
|
||||
return Err("too many in-scope namespace declarations".into());
|
||||
}
|
||||
bindings.push((prefix.to_string(), value.clone()));
|
||||
}
|
||||
}
|
||||
let mut expanded = BTreeSet::new();
|
||||
for (key, _) in &attrs {
|
||||
if key == "xmlns" || key.starts_with("xmlns:") {
|
||||
continue;
|
||||
}
|
||||
// Default namespaces do not apply to attributes. Preserve undeclared
|
||||
// prefixes for standalone SVG library fragments, as the importer did.
|
||||
let name = match key.split_once(':') {
|
||||
Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local),
|
||||
Some((prefix, local)) => {
|
||||
bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local))
|
||||
}
|
||||
None => ("", key.as_str()),
|
||||
};
|
||||
if !expanded.insert(name) {
|
||||
return Err(format!("duplicate expanded attribute `{key}`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
|
||||
}
|
||||
|
||||
/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and
|
||||
/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the
|
||||
/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is
|
||||
/// changes neither the selection nor the undo history.
|
||||
#[test]
|
||||
fn brush_freehand_continued_by_one_point_follows_keep_selected() {
|
||||
let mut s = session();
|
||||
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
|
||||
let p = NodeId(r["id"].as_u64().unwrap());
|
||||
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
let extend = json!({"id": p.0, "end": "end"});
|
||||
|
||||
select(&mut s, &[p, a]);
|
||||
let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false});
|
||||
assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0));
|
||||
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
|
||||
assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush");
|
||||
assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection");
|
||||
|
||||
select(&mut s, &[a]);
|
||||
let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"});
|
||||
s.execute("brush.freehand", &on).unwrap();
|
||||
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
|
||||
assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected");
|
||||
|
||||
select(&mut s, &[a]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("brush.freehand", &on).unwrap();
|
||||
assert_eq!(selected(&s), [a], "the same brush again: the selection stays");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
|
||||
}
|
||||
|
||||
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
|
||||
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
|
||||
/// document, the selection and the undo history stay as they were. Without a brush the path is
|
||||
|
||||
@@ -3908,6 +3908,266 @@ fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
|
||||
}
|
||||
|
||||
/// A triple-click whose first click is released across an edge, in the face it then clicks twice,
|
||||
/// matches that face's fill from before the first click: the release painted it too.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
|
||||
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
|
||||
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
|
||||
assert_eq!([a, b].map(|f| fill_of(&s, f)), [green.clone(), green.clone()], "the release across x = 50 fills both faces");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
|
||||
}
|
||||
|
||||
/// A triple-click whose third press lands in another face and is released in the face its first
|
||||
/// two clicks painted still matches that face's fill from before the first click.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
|
||||
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
|
||||
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::TripleClick, 55.0, 25.0), v).unwrap();
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
|
||||
}
|
||||
|
||||
/// A triple-click whose first click makes the Live Paint group and is released across an edge, in
|
||||
/// the face it then clicks twice, matches the fill that face was made with.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill() {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = [0.0, 50.0, 200.0, 300.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
for (id, c) in ids.iter().zip([red, red, blue, red]) {
|
||||
set_fill(&mut s, *id, c);
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
|
||||
let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
|
||||
assert_eq!(faces[..2].iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone()], "the release fills both faces");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone(), Paint::solid(blue), green]);
|
||||
}
|
||||
|
||||
/// When the first click makes the Live Paint group and is released in a face covered by a source
|
||||
/// path with no fill in front of a filled one, the face was made with the filled source's fill, as
|
||||
/// Make gives it, so the triple-click there matches that fill and not none.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill() {
|
||||
let mut s = session();
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let (a, b, d) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
|
||||
for id in [a, b, d] {
|
||||
set_fill(&mut s, id, red);
|
||||
}
|
||||
let (c, e) = (rect(&mut s, 60.0, 10.0, 30.0, 30.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
|
||||
s.edit("t", |doc, _| {
|
||||
for id in [c, e] {
|
||||
doc.node_mut(id).unwrap().appearance.set_fill(Paint::None);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, d.0, c.0, e.0]})).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 25.0), v).unwrap();
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
|
||||
let faces = faces_at(&s, g, &[(75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
|
||||
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the face under the unfilled path");
|
||||
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [Paint::solid(red), Paint::None], "Make gave the far faces red and none");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 75.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [green, Paint::None], "the triple-click matches the red the face was made with");
|
||||
}
|
||||
|
||||
/// A triple-click whose first click adds paths to a selected Live Paint group and is released in a
|
||||
/// face of that group matches the face's fill, not the edge around it.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0]);
|
||||
let [a] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 51.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone())]);
|
||||
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
|
||||
set_fill(&mut s, next, Color::rgb(0.0, 0.0, 1.0));
|
||||
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click merged the paths");
|
||||
let faces = faces_at(&s, g, &[(25.0, 25.0), (225.0, 25.0)]);
|
||||
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the group's face");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the face had");
|
||||
}
|
||||
|
||||
/// When the first click merges two selected Live Paint groups, a face of the group in front takes
|
||||
/// its source path's fill, so a triple-click there after a release across an edge matches that fill
|
||||
/// and not the paint the face had before the merge.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill() {
|
||||
let mut s = session();
|
||||
let back = live_squares(&mut s, &[0.0]);
|
||||
let source = rect(&mut s, 100.0, 0.0, 50.0, 50.0);
|
||||
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
|
||||
let front = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [f] = faces_at(&s, front, &[(125.0, 25.0)])[..] else { panic!("one face") };
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
paint_parts(&mut s, &[], &Paint::None, &[(f, blue.clone())]);
|
||||
let (next, far) = (rect(&mut s, 150.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
|
||||
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
|
||||
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
|
||||
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [m] = faces_at(&s, merged, &[(125.0, 25.0)])[..] else { panic!("one face") };
|
||||
assert_eq!(fill_of(&s, m), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "Merge gives the front group's face its source's fill");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 155.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 145.0, 25.0), v).unwrap();
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(125.0, 25.0)).expect("the click merged the groups");
|
||||
let faces = faces_at(&s, g, &[(125.0, 25.0), (325.0, 25.0)]);
|
||||
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the front group's face");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 145.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the merge gave the face");
|
||||
}
|
||||
|
||||
/// When the first click merges paths into a selected Live Paint group whose face has an unplaced
|
||||
/// gradient, Merge fixes the gradient to the face's fit, so a triple-click there after a release
|
||||
/// across an edge matches the fixed gradient: a far face whose source has that same fixed gradient
|
||||
/// takes the bucket's paint.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0]);
|
||||
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
|
||||
paint_parts(&mut s, &[], &Paint::None, &[(f, gradient.clone())]);
|
||||
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
|
||||
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [g.0, next.0]})).unwrap();
|
||||
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [m] = faces_at(&s, merged, &[(25.0, 25.0)])[..] else { panic!("one face") };
|
||||
let fixed = fill_of(&s, m);
|
||||
assert_ne!(fixed, gradient, "Merge fixes the face's gradient to its fit");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(far).unwrap().appearance.set_fill(fixed.clone());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
|
||||
let [far_face] = faces_at(&s, g, &[(225.0, 25.0)])[..] else { panic!("the far face") };
|
||||
assert_eq!(fill_of(&s, far_face), fixed, "the far face keeps its source's fixed gradient");
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
|
||||
}
|
||||
assert_eq!(fill_of(&s, far_face), green, "the far face had the fixed gradient the merge gave the face");
|
||||
}
|
||||
|
||||
/// When the first click merges a line that splits a painted face of the selected Live Paint group,
|
||||
/// Merge keeps the face's paint in one part only and the other part takes its source path's fill;
|
||||
/// a triple-click in that other part after a release across an edge matches the source's fill.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill() {
|
||||
let mut s = session();
|
||||
let source = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
|
||||
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
|
||||
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
|
||||
paint_parts(&mut s, &[], &Paint::None, &[(f, Paint::solid(Color::rgb(0.0, 0.0, 1.0)))]);
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 40, "y1": -10, "x2": 40, "y2": 60})).unwrap()["id"].as_u64().unwrap());
|
||||
let next = rect(&mut s, 50.0, 0.0, 50.0, 50.0);
|
||||
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
|
||||
let (red_far, blue_far) = (rect(&mut s, 200.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
|
||||
set_fill(&mut s, red_far, Color::rgb(1.0, 0.0, 0.0));
|
||||
set_fill(&mut s, blue_far, Color::rgb(0.0, 0.0, 1.0));
|
||||
let ids = json!({"ids": [g.0, line.0, next.0, red_far.0, blue_far.0]});
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let parts = faces_at(&s, merged, &[(20.0, 25.0), (45.0, 25.0)]);
|
||||
assert_eq!(
|
||||
parts.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(),
|
||||
[Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0))],
|
||||
"Merge keeps the paint in the part that holds the face's inside point"
|
||||
);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("select.set", &ids).unwrap();
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
|
||||
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
|
||||
}
|
||||
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
|
||||
let far = faces_at(&s, g, &[(225.0, 25.0), (325.0, 25.0)]);
|
||||
assert_eq!(far.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(), [green, Paint::solid(Color::rgb(0.0, 0.0, 1.0))]);
|
||||
}
|
||||
|
||||
/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
|
||||
/// fill the face was made with.
|
||||
#[test]
|
||||
@@ -3978,6 +4238,116 @@ fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges(
|
||||
assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
|
||||
}
|
||||
|
||||
/// A double-click whose two clicks land on two joined edges paints every edge joined to them that
|
||||
/// had their stroke: the edge the first click painted still joins the others.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
|
||||
// A square with a line across its middle, cut at x = 30 and x = 70 by two lines from the top: the
|
||||
// middle line's three edges join end to end.
|
||||
let mut s = session();
|
||||
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
|
||||
for anchors in [
|
||||
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
|
||||
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
|
||||
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
|
||||
] {
|
||||
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
|
||||
paint_parts(&mut s, &all, &red, &[]);
|
||||
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
|
||||
assert_eq!(middle.len(), 3, "the middle line's three edges");
|
||||
paint_parts(&mut s, &middle, &black, &[]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.stroke = green.clone();
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
for (kind, x) in
|
||||
[(PointerKind::Down, 50.0), (PointerKind::Up, 50.0), (PointerKind::Down, 85.0), (PointerKind::Up, 85.0), (PointerKind::DoubleClick, 85.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
|
||||
}
|
||||
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
|
||||
// `through` takes edge ids, with scope "connected" only.
|
||||
for p in [
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
|
||||
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
|
||||
json!({"group": g.0, "point": [15, 50], "through": []}),
|
||||
] {
|
||||
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A double-click whose second press lands on the next joined edge and is released back on the
|
||||
/// edge the first click painted (at the end of the line) matches that edge's stroke paint from
|
||||
/// before the first click, and the edge the second press painted still joins the edge past it.
|
||||
#[test]
|
||||
fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges() {
|
||||
let mut s = session();
|
||||
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
|
||||
for anchors in [
|
||||
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
|
||||
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
|
||||
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
|
||||
] {
|
||||
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
|
||||
paint_parts(&mut s, &all, &red, &[]);
|
||||
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
|
||||
assert_eq!(middle.len(), 3, "the middle line's three edges");
|
||||
paint_parts(&mut s, &middle, &black, &[]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.stroke = green.clone();
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
for (kind, x) in
|
||||
[(PointerKind::Down, 15.0), (PointerKind::Up, 15.0), (PointerKind::Down, 50.0), (PointerKind::Up, 15.0), (PointerKind::DoubleClick, 15.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
|
||||
}
|
||||
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
|
||||
}
|
||||
|
||||
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
|
||||
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
|
||||
#[test]
|
||||
fn live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
|
||||
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
|
||||
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
|
||||
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.fill = green.clone();
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
for (kind, m) in [
|
||||
(PointerKind::Down, Mods::default()),
|
||||
(PointerKind::Up, Mods::default()),
|
||||
(PointerKind::Down, cmd),
|
||||
(PointerKind::Up, cmd),
|
||||
(PointerKind::Down, Mods::default()),
|
||||
(PointerKind::Up, Mods::default()),
|
||||
(PointerKind::TripleClick, Mods::default()),
|
||||
] {
|
||||
s.pointer(&PointerEvent::new(kind, 25.0, 25.0).with_mods(m), v).unwrap();
|
||||
}
|
||||
assert_eq!(s.tool_id(), "livePaintBucket");
|
||||
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
|
||||
}
|
||||
|
||||
/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
|
||||
/// that compares none, and a scope with a drag's points are refused; nothing changes.
|
||||
#[test]
|
||||
|
||||
@@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() {
|
||||
assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}");
|
||||
}
|
||||
|
||||
/// The bounds of type `t`'s glyph outlines in text space.
|
||||
fn glyph_bounds(t: &TextObject) -> kurbo::Rect {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let mut all = kurbo::BezPath::new();
|
||||
for g in &lay.glyphs {
|
||||
all.extend(g.outline.iter());
|
||||
}
|
||||
kurbo::Shape::bounding_box(&all)
|
||||
}
|
||||
|
||||
/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in
|
||||
/// text space and then scales them, so the outlined stroke is filled art three times as thick
|
||||
/// across upright stems as across level bars, not a live stroke of one mean weight.
|
||||
#[test]
|
||||
fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() {
|
||||
let mut s = session();
|
||||
let id = stroked_text(&mut s);
|
||||
run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"}));
|
||||
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100}));
|
||||
let t = text(&s, id);
|
||||
let [a, b, c, d, ..] = t.xf.as_coeffs();
|
||||
assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf);
|
||||
let w = t.runs[0].style.stroke_width;
|
||||
let gb = glyph_bounds(&t);
|
||||
run(&mut s, "select.set", json!({ "ids": [id.0] }));
|
||||
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let group = doc.node(NodeId(g)).unwrap();
|
||||
let mut strokes: Option<kurbo::Rect> = None;
|
||||
for c in group.children().unwrap() {
|
||||
assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left");
|
||||
if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) {
|
||||
let cb = c.geometric_bounds().unwrap();
|
||||
strokes = Some(strokes.map_or(cb, |s| s.union(cb)));
|
||||
}
|
||||
}
|
||||
// Round joins and caps reach half the weight past the glyphs in text space, then scale.
|
||||
let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0));
|
||||
let got = strokes.expect("filled character strokes");
|
||||
assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}");
|
||||
assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}");
|
||||
}
|
||||
|
||||
/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight
|
||||
/// and dashes scaled with them.
|
||||
#[test]
|
||||
fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() {
|
||||
let mut s = session();
|
||||
let id = stroked_text(&mut s);
|
||||
run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]}));
|
||||
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200}));
|
||||
run(&mut s, "object.rotate", json!({"angle": 30}));
|
||||
let t = text(&s, id);
|
||||
let k = t.xf.determinant().abs().sqrt();
|
||||
assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf);
|
||||
let st = t.runs[0].style.clone();
|
||||
let dash = st.stroke_dash.as_ref().unwrap().pattern.clone();
|
||||
let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len();
|
||||
run(&mut s, "select.set", json!({ "ids": [id.0] }));
|
||||
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec();
|
||||
assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes");
|
||||
for p in &pieces {
|
||||
let ps = p.appearance.stroke().expect("a live stroke");
|
||||
assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k);
|
||||
let got = &ps.dash.as_ref().unwrap().pattern;
|
||||
assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's
|
||||
/// own stroke attributes have none, on paths as on type).
|
||||
#[test]
|
||||
|
||||
@@ -1034,6 +1034,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() {
|
||||
assert_eq!(pasted, labels(&s, p), "copied as {before:?}");
|
||||
}
|
||||
|
||||
/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without
|
||||
/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the
|
||||
/// copied light color and black labels.
|
||||
#[test]
|
||||
fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() {
|
||||
let csv = ",North,South\nP,1,1";
|
||||
fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
|
||||
let mut out = vec![];
|
||||
node(s, id).walk(&mut |n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& ["North", "South"].contains(&t.plain_text().as_str())
|
||||
{
|
||||
out.push((t.plain_text(), t.first_style().fill.clone()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))];
|
||||
for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] {
|
||||
let mut s = session();
|
||||
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
|
||||
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap();
|
||||
let mut wedges = vec![];
|
||||
node(&s, g).walk(&mut |m| {
|
||||
if let NodeKind::Path { .. } = m.kind {
|
||||
wedges.push(m.id.0);
|
||||
}
|
||||
});
|
||||
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap();
|
||||
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
|
||||
assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels");
|
||||
copy(&mut s, &[g]);
|
||||
new_doc(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
|
||||
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0];
|
||||
let pasted = labels(&s, p);
|
||||
assert_eq!(pasted, both(expected), "{conflict}");
|
||||
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
|
||||
assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them");
|
||||
}
|
||||
}
|
||||
|
||||
/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when
|
||||
/// pasted without formatting, and its color shows the document's swatch.
|
||||
#[test]
|
||||
fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() {
|
||||
let mut s = session();
|
||||
let r = swatched_rect(&mut s, "Ink", "#ffffff");
|
||||
sel(&mut s, &[r]);
|
||||
s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap();
|
||||
copy(&mut s, &[r]);
|
||||
new_doc(&mut s);
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
|
||||
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
|
||||
assert_eq!(v["merged"], 1);
|
||||
let p = ids_of(&v)[0];
|
||||
let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone());
|
||||
assert_eq!(style.as_deref(), Some("Sun"));
|
||||
assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0));
|
||||
}
|
||||
|
||||
/// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label
|
||||
/// takes the contrast of the wedge it is in.
|
||||
#[test]
|
||||
|
||||
@@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() {
|
||||
assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lower_stroke_row_spans_the_box_that_row_paints() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0);
|
||||
// [Fill, Stroke 40 pt, Stroke 1 pt] on both.
|
||||
s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap();
|
||||
for aligned in [false, true] {
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"}))
|
||||
.unwrap();
|
||||
for id in [a, b] {
|
||||
let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else {
|
||||
panic!("expected a gradient on stroke row 1")
|
||||
};
|
||||
// The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt.
|
||||
let geom = g.geom.expect("placed in document coordinates");
|
||||
assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_art_default_stays_unplaced() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -717,6 +717,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() {
|
||||
assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient");
|
||||
}
|
||||
|
||||
/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that
|
||||
/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art.
|
||||
#[test]
|
||||
fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() {
|
||||
let mut s = session();
|
||||
let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setStroke",
|
||||
json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100],
|
||||
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}),
|
||||
);
|
||||
run(&mut s, "stroke.set", json!({"weight": 4}));
|
||||
let info = run(&mut s, "object.expand.info", json!({}));
|
||||
assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill");
|
||||
run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100}));
|
||||
let info = run(&mut s, "object.expand.info", json!({}));
|
||||
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true)));
|
||||
run(&mut s, "object.expand", json!({}));
|
||||
assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art");
|
||||
}
|
||||
|
||||
/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art
|
||||
/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are
|
||||
/// written with 0.002 pt runs (over a 0.2 pt vector).
|
||||
|
||||
@@ -468,6 +468,15 @@ fn malformed_docx_fails_cleanly() {
|
||||
assert!(e.contains("not a WordprocessingML document"), "{e}");
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", b"<w:document><w:body>")])).unwrap_err();
|
||||
assert!(e.contains("not well-formed XML"), "{e}");
|
||||
for xml in [
|
||||
format!(r#"<w:document xmlns:w="{W_NS}"><w:body><w:p><w:r><w:t>partial text</w:t></w:r></w:p>"#),
|
||||
document("<w:p><w:r><w:t>A&missing;B</w:t></w:r></w:p>"),
|
||||
document("<w:p><w:r><w:t xml:space=\"preserve\" xml:space=\"default\">text</w:t></w:r></w:p>"),
|
||||
document("<w:p xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\"><w:r><w:t>text</w:t></w:r></w:p>"),
|
||||
] {
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", xml.as_bytes())])).unwrap_err();
|
||||
assert!(e.contains("not well-formed XML"), "{e}");
|
||||
}
|
||||
let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document("<w:p/>").as_bytes())])).unwrap_err();
|
||||
assert!(e.contains("no text to place"), "{e}");
|
||||
// A file whose headers understate what it unpacks to, and one whose headers say it is too large.
|
||||
|
||||
@@ -2665,6 +2665,11 @@ fn malformed_variable_libraries_are_refused() {
|
||||
let long_graph = format!("<Shown><data><values>{}</values></data></Shown>", row.repeat(2_000));
|
||||
let cases = [
|
||||
("not well-formed XML", "<variableSets><variableSet>".to_string()),
|
||||
("not well-formed XML", ok.replace("<p>x</p>", "<p>A&missing;B</p>")),
|
||||
("not well-formed XML", ok.replace("</variableSets>", "")),
|
||||
("not well-formed XML", ok.replace("varName=\"Name\"", "varName=\"Name\" varName=\"Other\"")),
|
||||
("not well-formed XML", ok.replace("<variable ", "<variable xmlns:a=\"urn:test\" xmlns:b=\"urn:test\" a:id=\"1\" b:id=\"2\" ")),
|
||||
("missing `varName`", ok.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Name\"")),
|
||||
("no `variableSets` element", "<svg><variables/></svg>".to_string()),
|
||||
("declares no variables", "<variableSets><variableSet><variables/></variableSet></variableSets>".to_string()),
|
||||
("is declared twice", library(&[("Name", "textcontent"), ("Name", "textcontent")], &[])),
|
||||
@@ -3545,6 +3550,17 @@ fn variable_sort_orders_the_list_by_each_column() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_library_attributes_keep_their_namespace() {
|
||||
let mut s = session();
|
||||
let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["x"])])])
|
||||
.replace("varName=\"Name\"", "xmlns:m=\"urn:metadata\" m:varName=\"Other\" varName=\"Name\"");
|
||||
let loaded = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap();
|
||||
assert_eq!(loaded["variables"], json!(["Name"]));
|
||||
let sets = s.execute("dataset.list", &json!({})).unwrap();
|
||||
assert_eq!(sets["datasets"][0]["values"], json!({"Name": {"text": "x"}}));
|
||||
}
|
||||
|
||||
/// The sort is panel state: it is not an undo step and does not count as a change to save, and
|
||||
/// setting the order the list already has does not redraw anything. A bad `by` or `descending`
|
||||
/// is an error that leaves the order as it was.
|
||||
|
||||
@@ -255,6 +255,9 @@ impl Session {
|
||||
}
|
||||
// The Selection and Group Selection tools act on the instance whole.
|
||||
self.select_whole_instance(id);
|
||||
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
|
||||
// double-click or triple-click compares.
|
||||
self.tool.press_elsewhere();
|
||||
let lent = self.make_tool(id);
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
@@ -1086,6 +1089,12 @@ impl Session {
|
||||
self.with_tool_cx(view, |t, cx| t.hover_ended(cx));
|
||||
}
|
||||
|
||||
/// A press on the canvas went to the view tools and not to the active tool
|
||||
/// ([`vectorcraft_tools::Tool::press_elsewhere`]).
|
||||
pub fn tool_press_elsewhere(&mut self) {
|
||||
self.tool.press_elsewhere();
|
||||
}
|
||||
|
||||
/// Whether the active tool's hover depends on what lies under a still pointer
|
||||
/// ([`vectorcraft_tools::Tool::wants_rehover`]).
|
||||
pub fn tool_wants_rehover(&self) -> bool {
|
||||
|
||||
@@ -993,6 +993,13 @@ fn structured_junk() {
|
||||
("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})),
|
||||
("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})),
|
||||
("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})),
|
||||
// Packaging Tools add-on.
|
||||
("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})),
|
||||
("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})),
|
||||
("addon.packaging.setRole", json!({"role": "none", "overprint": null})),
|
||||
("addon.packaging.roles", json!({"ids": [-1, 1e300]})),
|
||||
("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})),
|
||||
("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})),
|
||||
// Smart Pen add-on.
|
||||
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
|
||||
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),
|
||||
|
||||
@@ -167,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on",
|
||||
),
|
||||
(
|
||||
"ui.checkSpelling",
|
||||
"Check Spelling…",
|
||||
"Cmd+I",
|
||||
"{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options",
|
||||
),
|
||||
("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:<id>, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"),
|
||||
("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"),
|
||||
("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"),
|
||||
|
||||
@@ -33,8 +33,8 @@ smallvec = "1"
|
||||
siphasher = "1"
|
||||
weezl = "0.2"
|
||||
serde = { workspace = true }
|
||||
# The XMP packet that File Info is read from (file_info.rs); the version usvg already uses.
|
||||
roxmltree = "0.21"
|
||||
# The XMP packet that File Info is read from (file_info.rs).
|
||||
craft-xml = { workspace = true }
|
||||
# PDF security (encrypt.rs): pure Rust, MIT OR Apache-2.0, builds for wasm.
|
||||
aes = "0.8"
|
||||
md-5 = { version = "0.10", default-features = false }
|
||||
|
||||
@@ -3,6 +3,8 @@ use super::{Arc, BlendMode, Color, Exporter, Image, Node, NodeKind, Paint, Rect,
|
||||
use krilla::color::device_n::{Colorant, DeviceNSpace, Process};
|
||||
use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace};
|
||||
|
||||
use crate::images::SourceProfiles;
|
||||
|
||||
/// The byte count of a repeated color channel, within [`vectorcraft_doc::MAX_RASTER_ALLOC`].
|
||||
fn tinted_color_len(samples: usize, pixels: usize) -> Option<usize> {
|
||||
let bytes = samples.checked_mul(pixels)?;
|
||||
@@ -138,7 +140,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
let doc = self.doc;
|
||||
let out = self.out.clone();
|
||||
let profiles = !out.standard.cmyk_only();
|
||||
let profiles = out.source_profiles();
|
||||
let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit });
|
||||
let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| {
|
||||
let cmyk_image = blob.is_cmyk();
|
||||
@@ -147,7 +149,7 @@ impl Exporter<'_> {
|
||||
}
|
||||
let r = if cmyk_image {
|
||||
let icc = out.cmyk_image_icc(blob);
|
||||
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref())
|
||||
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, out.cmyk_tag(icc.as_deref()))
|
||||
} else {
|
||||
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles, to_srgb)
|
||||
};
|
||||
@@ -197,7 +199,8 @@ impl Exporter<'_> {
|
||||
let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| {
|
||||
let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?;
|
||||
let icc = self.out.cmyk_image_icc(blob);
|
||||
let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), icc.as_deref());
|
||||
let tag = self.out.cmyk_tag(icc.as_deref());
|
||||
let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag);
|
||||
if let (Some(w), Some(_)) = (r.warning, &r.image) {
|
||||
self.warn(w);
|
||||
}
|
||||
@@ -320,13 +323,15 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged),
|
||||
/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in
|
||||
/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an
|
||||
/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB
|
||||
/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of
|
||||
/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of
|
||||
/// 16 bits a sample is written at 8 bits ([`png_8_bit`]).
|
||||
pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> {
|
||||
/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` keeps it (not in
|
||||
/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). When `profiles`
|
||||
/// doesn't keep it, an image that carries a gray or RGB profile is written without it, and so is
|
||||
/// one whose gray or RGB profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data
|
||||
/// unchanged, an image of another format decoded. With [`SourceProfiles::Remove`], an image that
|
||||
/// carries any profile is written without it, a JPEG without its `ICC_PROFILE` segments (decoded
|
||||
/// when those can't be taken out). Without `sixteen_bit` (a file before PDF 1.5), a PNG or another
|
||||
/// image of 16 bits a sample is written at 8 bits ([`png_8_bit`]).
|
||||
pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option<Image> {
|
||||
// The header's size first: the writer's decoders allocate what it declares, and the encoded
|
||||
// bytes of an image that is far larger than any the app reads may be a few kilobytes.
|
||||
let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions();
|
||||
@@ -334,16 +339,25 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee
|
||||
return None;
|
||||
}
|
||||
let bytes = blob.bytes.as_ref().clone();
|
||||
// The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the
|
||||
// profile is malformed, such a JPEG is written without its profile, and an image of another
|
||||
// The PDF writer keeps a gray or RGB image's ICC profile: unless `profiles` keeps it, or when
|
||||
// the profile is malformed, such a JPEG is written without its profile, and an image of another
|
||||
// format is decoded and written without it. The color space is read from the header's bytes
|
||||
// 16..20 even in a profile cut short, as the PDF writer reads it.
|
||||
let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) {
|
||||
Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)),
|
||||
// 16..20 even in a profile cut short, as the PDF writer reads it. With `Remove`, a JPEG's
|
||||
// `ICC_PROFILE` segments are taken out also when they don't make up a profile the decoder reads.
|
||||
let remove = profiles == SourceProfiles::Remove;
|
||||
let jpeg = matches!(blob.mime.as_str(), "image/jpeg" | "image/jpg");
|
||||
let unkept = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) {
|
||||
_ if remove => true,
|
||||
Some(space @ (b"GRAY" | b"RGB ")) => {
|
||||
profiles != SourceProfiles::Keep || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s))
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
let strip = (remove && jpeg) || unkept;
|
||||
let direct = match blob.mime.as_str() {
|
||||
"image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(),
|
||||
"image/jpeg" | "image/jpg" if strip => {
|
||||
crate::images::jpeg_data(&bytes, remove).and_then(|data| Image::from_jpeg_with_icc(data.into(), None, interpolate).ok())
|
||||
}
|
||||
_ if strip => None,
|
||||
"image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()),
|
||||
"image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(),
|
||||
@@ -371,7 +385,7 @@ mod tests {
|
||||
let crc =
|
||||
!png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }));
|
||||
png[29..33].copy_from_slice(&crc.to_be_bytes());
|
||||
assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none());
|
||||
assert!(super::embed(&ImageBlob::png(png), false, true, super::SourceProfiles::Keep).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -326,7 +326,7 @@ impl Exporter<'_> {
|
||||
let img = match self.images.get(&cache) {
|
||||
Some(img) => img.clone(),
|
||||
None => {
|
||||
let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only());
|
||||
let img = embed(&image.blob, self.interpolate, self.sixteen_bit, self.out.source_profiles());
|
||||
self.images.insert(cache, img.clone());
|
||||
img
|
||||
}
|
||||
|
||||
+39
-86
@@ -5,7 +5,7 @@
|
||||
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::object::{DateTime, Dict, Stream};
|
||||
use roxmltree::Node;
|
||||
use craft_xml::{Canonical, Doctype, El, Limits, Names, Options};
|
||||
|
||||
use crate::import_scan::text_string;
|
||||
|
||||
@@ -15,12 +15,13 @@ const MAX_XMP: usize = 8 << 20;
|
||||
const MAX_NESTING: usize = 256;
|
||||
|
||||
const RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
|
||||
const XML: &str = "http://www.w3.org/XML/1998/namespace";
|
||||
pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/";
|
||||
const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use
|
||||
pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use
|
||||
const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use
|
||||
|
||||
const XMP_NAMESPACES: Canonical<'static> = Canonical::new(&[("rdf", RDF), ("dc", DC), ("xmp", XMP), ("xmpRights", XMP_RIGHTS), ("pdf", PDF)]);
|
||||
|
||||
/// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct FileInfo {
|
||||
@@ -73,39 +74,39 @@ fn packet(pdf: &Pdf) -> Option<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// The File Info fields of an XMP packet; `None` when it isn't XML in UTF-8 or UTF-16, or when its
|
||||
/// elements nest more than [`MAX_NESTING`] deep.
|
||||
/// [`xmp`] of `packet`; `None` when it isn't XML in UTF-8 or UTF-16, or when its elements nest
|
||||
/// more than [`MAX_NESTING`] deep.
|
||||
fn xmp(packet: &[u8]) -> Option<FileInfo> {
|
||||
let text = xml_text(packet)?;
|
||||
// roxmltree parses nested elements recursively.
|
||||
if nesting(&text) > MAX_NESTING {
|
||||
return None;
|
||||
let opts = Options {
|
||||
names: Names::Canonical(&XMP_NAMESPACES),
|
||||
doctype: Doctype::Reject,
|
||||
limits: Limits { max_depth: MAX_NESTING, ..Limits::DEFAULT },
|
||||
..Options::default()
|
||||
}
|
||||
let xml = roxmltree::Document::parse(&text).ok()?;
|
||||
.strict();
|
||||
let root = opts.parse(text.as_bytes()).ok()?;
|
||||
// The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value.
|
||||
let descriptions: Vec<Node<'_, '_>> = xml
|
||||
.descendants()
|
||||
.filter(|n| n.has_tag_name((RDF, "RDF")))
|
||||
.flat_map(|rdf| rdf.children())
|
||||
.filter(|n| n.has_tag_name((RDF, "Description")))
|
||||
.collect();
|
||||
let get = |ns: &str, name: &str| property(&descriptions, ns, name);
|
||||
let first = |ns: &str, name: &str| get(ns, name).into_iter().next();
|
||||
let creators = get(DC, "creator");
|
||||
let subjects = get(DC, "subject");
|
||||
let descriptions: Vec<&El> =
|
||||
std::iter::once(&root).chain(root.descendants()).filter(|n| n.is("rdf:RDF")).flat_map(|rdf| rdf.children("rdf:Description")).collect();
|
||||
let get = |name: &str| property(&descriptions, name);
|
||||
let first = |name: &str| get(name).into_iter().next();
|
||||
let creators = get("dc:creator");
|
||||
let subjects = get("dc:subject");
|
||||
Some(FileInfo {
|
||||
title: first(DC, "title"),
|
||||
title: first("dc:title"),
|
||||
author: (!creators.is_empty()).then(|| creators.join(", ")),
|
||||
description: first(DC, "description"),
|
||||
keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) },
|
||||
copyright_notice: first(DC, "rights"),
|
||||
copyright_url: first(XMP_RIGHTS, "WebStatement"),
|
||||
copyrighted: first(XMP_RIGHTS, "Marked").and_then(|m| match m.to_ascii_lowercase().as_str() {
|
||||
description: first("dc:description"),
|
||||
keywords: if subjects.is_empty() { first("pdf:Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) },
|
||||
copyright_notice: first("dc:rights"),
|
||||
copyright_url: first("xmpRights:WebStatement"),
|
||||
copyrighted: first("xmpRights:Marked").and_then(|m| match m.to_ascii_lowercase().as_str() {
|
||||
"true" => Some(true),
|
||||
"false" => Some(false),
|
||||
_ => None,
|
||||
}),
|
||||
created: first(XMP, "CreateDate").and_then(|d| xmp_date(&d)),
|
||||
modified: first(XMP, "ModifyDate").and_then(|d| xmp_date(&d)),
|
||||
created: first("xmp:CreateDate").and_then(|d| xmp_date(&d)),
|
||||
modified: first("xmp:ModifyDate").and_then(|d| xmp_date(&d)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -123,58 +124,14 @@ fn xml_text(b: &[u8]) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How deep the elements of `xml` nest: start tags less end tags, at most, outside comments,
|
||||
/// CDATA sections, processing instructions, declarations and quoted attribute values.
|
||||
fn nesting(xml: &str) -> usize {
|
||||
let b = xml.as_bytes();
|
||||
let (mut depth, mut most, mut i) = (0usize, 0usize, 0usize);
|
||||
// The index just past the first `end` at or after `from` (the end of the text if none).
|
||||
let past = |from: usize, end: &[u8]| {
|
||||
b.get(from..).and_then(|rest| rest.windows(end.len()).position(|w| w == end)).map_or(b.len(), |at| from + at + end.len())
|
||||
};
|
||||
while let Some(at) = b.get(i..).and_then(|rest| rest.iter().position(|&c| c == b'<')) {
|
||||
let start = i + at;
|
||||
let rest = b.get(start..).unwrap_or_default();
|
||||
if rest.starts_with(b"<!--") {
|
||||
i = past(start + 4, b"-->");
|
||||
} else if rest.starts_with(b"<![CDATA[") {
|
||||
i = past(start + 9, b"]]>");
|
||||
} else if rest.starts_with(b"<?") {
|
||||
i = past(start + 2, b"?>");
|
||||
} else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
|
||||
depth = depth.saturating_sub(usize::from(rest.starts_with(b"</")));
|
||||
i = past(start + 2, b">");
|
||||
} else {
|
||||
// A start tag: up to its `>` outside quotes; `/>` closes it at once.
|
||||
let mut j = start + 1;
|
||||
let mut quote = None;
|
||||
while let Some(&c) = b.get(j) {
|
||||
match (quote, c) {
|
||||
(None, b'"' | b'\'') => quote = Some(c),
|
||||
(Some(q), _) if c == q => quote = None,
|
||||
(None, b'>') => break,
|
||||
_ => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j.saturating_sub(1)) != Some(&b'/') {
|
||||
depth += 1;
|
||||
most = most.max(depth);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
most
|
||||
}
|
||||
|
||||
/// The values of property `ns` `name` on the first of `descriptions` that gives it: an attribute
|
||||
/// The values of property `name` on the first of `descriptions` that gives it: an attribute
|
||||
/// of the `rdf:Description`, or a property element's items ([`items`]), blank ones left out.
|
||||
fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String> {
|
||||
fn property(descriptions: &[&El], name: &str) -> Vec<String> {
|
||||
for d in descriptions {
|
||||
if let Some(v) = d.attribute((ns, name)).map(str::trim).filter(|v| !v.is_empty()) {
|
||||
if let Some(v) = d.attr(name).map(str::trim).filter(|v| !v.is_empty()) {
|
||||
return vec![v.to_string()];
|
||||
}
|
||||
let found = d.children().filter(|c| c.has_tag_name((ns, name))).map(items).find(|v| !v.is_empty());
|
||||
let found = d.children(name).map(items).find(|v| !v.is_empty());
|
||||
if let Some(v) = found {
|
||||
return v;
|
||||
}
|
||||
@@ -185,14 +142,10 @@ fn property(descriptions: &[Node<'_, '_>], ns: &str, name: &str) -> Vec<String>
|
||||
/// The items of property element `p`: the `rdf:li` of its `rdf:Seq`, `rdf:Bag` or `rdf:Alt` (the
|
||||
/// `x-default` language item first), else its own value ([`value_of`]); trimmed, blank ones left
|
||||
/// out.
|
||||
fn items(p: Node<'_, '_>) -> Vec<String> {
|
||||
let array = p.children().find(|c| ["Seq", "Bag", "Alt"].into_iter().any(|t| c.has_tag_name((RDF, t))));
|
||||
fn items(p: &El) -> Vec<String> {
|
||||
let array = p.elements().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt"));
|
||||
let mut values: Vec<(bool, String)> = match array {
|
||||
Some(a) => a
|
||||
.children()
|
||||
.filter(|c| c.has_tag_name((RDF, "li")))
|
||||
.map(|li| (li.attribute((XML, "lang")).is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li)))
|
||||
.collect(),
|
||||
Some(a) => a.children("rdf:li").map(|li| (li.attr("xml:lang").is_some_and(|l| l.eq_ignore_ascii_case("x-default")), value_of(li))).collect(),
|
||||
None => vec![(false, value_of(p))],
|
||||
};
|
||||
// A stable sort: the `x-default` item first, the others in their order.
|
||||
@@ -203,19 +156,19 @@ fn items(p: Node<'_, '_>) -> Vec<String> {
|
||||
/// The value of element `n`: the URI of its `rdf:resource` attribute (how RDF writes a URI value);
|
||||
/// for a qualified value, its `rdf:value` (an attribute or an element, on `n` or on an
|
||||
/// `rdf:Description` inside it), without the qualifiers; else the text inside it.
|
||||
fn value_of(mut n: Node<'_, '_>) -> String {
|
||||
fn value_of(mut n: &El) -> String {
|
||||
// Each step goes to an element inside `n`, so the loop ends.
|
||||
loop {
|
||||
if let Some(uri) = n.attribute((RDF, "resource")) {
|
||||
if let Some(uri) = n.attr("rdf:resource") {
|
||||
return uri.to_string();
|
||||
}
|
||||
let holder = n.children().find(|c| c.has_tag_name((RDF, "Description"))).unwrap_or(n);
|
||||
if let Some(v) = holder.attribute((RDF, "value")) {
|
||||
let holder = n.child("rdf:Description").unwrap_or(n);
|
||||
if let Some(v) = holder.attr("rdf:value") {
|
||||
return v.to_string();
|
||||
}
|
||||
match holder.children().find(|c| c.has_tag_name((RDF, "value"))) {
|
||||
match holder.child("rdf:value") {
|
||||
Some(v) => n = v,
|
||||
None => return n.descendants().filter(|d| d.is_text()).filter_map(|d| d.text()).collect(),
|
||||
None => return n.deep_text(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+71
-19
@@ -20,6 +20,9 @@
|
||||
//! inverted samples, which the PDF writer's Decode array undoes. A CMYK image whose numbers are
|
||||
//! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or
|
||||
//! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included.
|
||||
//! With Don't Include Profiles set ([`SourceProfiles::Remove`], [`CmykTag::Removed`]), a JPEG
|
||||
//! embedded as it is loses its `ICC_PROFILE` segments, its other segments and compressed samples
|
||||
//! unchanged.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
@@ -152,10 +155,10 @@ pub(crate) fn from_decoded(img: DynamicImage, icc: Option<Vec<u8>>, interpolate:
|
||||
}
|
||||
|
||||
/// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when
|
||||
/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as
|
||||
/// [`from_decoded`] writes it. `None` when it can't be decoded.
|
||||
pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option<Image> {
|
||||
from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit)
|
||||
/// `profiles` keeps it ([`SourceProfiles::Keep`]), as [`from_decoded`] writes it. `None` when it
|
||||
/// can't be decoded.
|
||||
pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: SourceProfiles) -> Option<Image> {
|
||||
from_decoded(decoded(bytes)?, (profiles == SourceProfiles::Keep).then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit)
|
||||
}
|
||||
|
||||
/// Are all of the RGBA pixels `rgba` grey?
|
||||
@@ -330,6 +333,47 @@ pub(crate) struct ToSrgb {
|
||||
pub sixteen_bit: bool,
|
||||
}
|
||||
|
||||
/// What happens to the ICC profile a gray or RGB image carries
|
||||
/// ([`crate::output::ColorOut::source_profiles`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SourceProfiles {
|
||||
/// The image keeps a well-formed gray or RGB profile ([`valid_icc`]).
|
||||
Keep,
|
||||
/// The image is untagged; a JPEG embedded as it is keeps its data unchanged (PDF/X-1a).
|
||||
Untag,
|
||||
/// The image is untagged and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its
|
||||
/// other segments and compressed samples unchanged (Don't Include Profiles).
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// The CMYK profile [`recode_cmyk`] tags a CMYK image that keeps its numbers with.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CmykTag<'a> {
|
||||
/// This profile ([`cmyk_icc`]).
|
||||
Profile(&'a [u8]),
|
||||
/// None; a JPEG embedded as it is keeps its data unchanged.
|
||||
Untagged,
|
||||
/// None, and a JPEG embedded as it is loses its `ICC_PROFILE` segments, its other segments
|
||||
/// and compressed samples unchanged (Don't Include Profiles).
|
||||
Removed,
|
||||
}
|
||||
|
||||
impl<'a> CmykTag<'a> {
|
||||
/// The profile the image is tagged with.
|
||||
fn icc(self) -> Option<&'a [u8]> {
|
||||
match self {
|
||||
Self::Profile(icc) => Some(icc),
|
||||
Self::Untagged | Self::Removed => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JPEG `bytes` as they are embedded: without their `ICC_PROFILE` segments with `remove`
|
||||
/// ([`vectorcraft_doc::cmyk::jpeg_without_icc`]). `None` when those can't be taken out.
|
||||
pub(crate) fn jpeg_data(bytes: &[u8], remove: bool) -> Option<Vec<u8>> {
|
||||
if remove { vectorcraft_doc::cmyk::jpeg_without_icc(bytes) } else { Some(bytes.to_vec()) }
|
||||
}
|
||||
|
||||
/// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of
|
||||
/// colour space `space` (`GRAY` or `RGB `, [`valid_icc`]): `None` without one, `Some(None)` when
|
||||
/// the CMS can't read it.
|
||||
@@ -474,8 +518,7 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic
|
||||
/// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask:
|
||||
/// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours
|
||||
/// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile
|
||||
/// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces);
|
||||
/// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB
|
||||
/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB
|
||||
/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as
|
||||
/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be
|
||||
/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB.
|
||||
@@ -485,7 +528,7 @@ pub(crate) fn recode(
|
||||
c: &CompressionSettings,
|
||||
interpolate: bool,
|
||||
convert: Option<&Pixels>,
|
||||
profiles: bool,
|
||||
profiles: SourceProfiles,
|
||||
to_srgb: Option<ToSrgb>,
|
||||
) -> Recoded {
|
||||
let keep = Recoded { image: None, warning: None, note: None };
|
||||
@@ -553,9 +596,14 @@ pub(crate) fn recode(
|
||||
// Written as it is only when nothing converts it further.
|
||||
let as_is = kept(&rule, dims, size, jpeg) && convert.is_none();
|
||||
// A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB
|
||||
// profile): its JPEG data, without the profile.
|
||||
if !changed && as_is && jpeg {
|
||||
let image = Image::from_jpeg_with_icc(bytes.to_vec().into(), None, interpolate).ok();
|
||||
// profile): its JPEG data, without the profile (and, with `Remove`, without its
|
||||
// segments: encoded again when those can't be taken out).
|
||||
if !changed
|
||||
&& as_is
|
||||
&& jpeg
|
||||
&& let Some(data) = jpeg_data(bytes, profiles == SourceProfiles::Remove)
|
||||
{
|
||||
let image = Image::from_jpeg_with_icc(data.into(), None, interpolate).ok();
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
}
|
||||
// Not resampled and lossless: written at its own depth.
|
||||
@@ -573,7 +621,8 @@ pub(crate) fn recode(
|
||||
// Pixels that keep their colours keep the profile they are in; converted ones are in the
|
||||
// destination's.
|
||||
let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" };
|
||||
let icc = (profiles && convert.is_none() && source.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want));
|
||||
let keeps = profiles == SourceProfiles::Keep && convert.is_none() && source.is_none();
|
||||
let icc = keeps.then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want));
|
||||
let rgb_icc = icc.is_some() && kind == Kind::Color;
|
||||
let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8();
|
||||
if kind == Kind::Mono {
|
||||
@@ -630,8 +679,8 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c
|
||||
/// is when its numbers are (`convert` is `None`); otherwise its ink amounts are resampled,
|
||||
/// converted by `convert` and compressed again. With `alpha` (one sample a pixel, see
|
||||
/// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its
|
||||
/// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc`
|
||||
/// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it.
|
||||
/// inks can't be read. When its numbers are kept, the image is tagged as `tag` says, and is
|
||||
/// untagged without a profile; converted pixels are never tagged with it.
|
||||
pub(crate) fn recode_cmyk(
|
||||
blob: &ImageBlob,
|
||||
size: (f64, f64),
|
||||
@@ -639,18 +688,21 @@ pub(crate) fn recode_cmyk(
|
||||
interpolate: bool,
|
||||
convert: Option<&CmykPixels>,
|
||||
alpha: Option<Vec<u8>>,
|
||||
icc: Option<&[u8]>,
|
||||
tag: CmykTag<'_>,
|
||||
) -> Recoded {
|
||||
let rule = rule(c, Kind::Color);
|
||||
let jpeg = jpeg_components(&blob.bytes).is_some();
|
||||
let icc = icc.filter(|_| convert.is_none());
|
||||
let icc = tag.icc().filter(|_| convert.is_none());
|
||||
if jpeg && convert.is_none() && alpha.is_none() {
|
||||
let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok());
|
||||
if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) {
|
||||
// The JPEG data as it is, tagged with `icc` rather than with its own segments; one
|
||||
// larger than [`MAX_EMBED_PIXELS`] is not written.
|
||||
// The JPEG data as it is (without its `ICC_PROFILE` segments with `CmykTag::Removed`: its
|
||||
// inks are encoded again when those can't be taken out), tagged with `icc` rather than
|
||||
// with its own segments; one larger than [`MAX_EMBED_PIXELS`] is not written.
|
||||
if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true))
|
||||
&& let Some(data) = jpeg_data(&blob.bytes, tag == CmykTag::Removed)
|
||||
{
|
||||
let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS)
|
||||
.then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok())
|
||||
.then(|| Image::from_jpeg_with_icc(data.into(), icc.map(|i| i.to_vec().into()), interpolate).ok())
|
||||
.flatten();
|
||||
return Recoded { image, warning: rule.instead, note: None };
|
||||
}
|
||||
|
||||
@@ -361,8 +361,9 @@ impl<'p> Builder<'p> {
|
||||
Some(MaskSpec::Mask(m)) => (opacity, Some(m.clone())),
|
||||
None => (opacity, None),
|
||||
};
|
||||
// Isolation only shows with blending inside; knockout with several objects.
|
||||
let isolate = isolate && Node::children_blend(&children, &mut |c| c.blends_through());
|
||||
// Isolation only shows with blending or overprinting inside; knockout with several
|
||||
// objects.
|
||||
let isolate = isolate && (Node::children_blend(&children, &mut |c| c.blends_through()) || children_overprint(&children));
|
||||
let knockout = knockout && children.len() > 1;
|
||||
let plain = opacity >= 0.999 && blend == BlendMode::Normal && mask.is_none() && !isolate && !knockout;
|
||||
if children.is_empty() {
|
||||
@@ -1183,3 +1184,16 @@ fn visual_glyph_text(text: String) -> String {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
order.iter().filter_map(|&i| chars.get(i)).collect()
|
||||
}
|
||||
|
||||
/// Whether a visible fill or stroke among `children` overprints, characters' too, directly or
|
||||
/// through children that don't isolate. In an isolated group an overprinting object is drawn on
|
||||
/// the group's empty backdrop, so it covers the inks of the art below the group that it does not
|
||||
/// paint; without isolation it leaves them.
|
||||
fn children_overprint(children: &[Arc<Node>]) -> bool {
|
||||
children.iter().any(|c| {
|
||||
c.visible
|
||||
&& (c.appearance.items.iter().any(|i| i.visible() && i.overprint())
|
||||
|| matches!(&c.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|
||||
|| (!c.isolate && c.children().is_some_and(|ch| children_overprint(ch))))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -24,7 +24,11 @@
|
||||
//! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a
|
||||
//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with
|
||||
//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3
|
||||
//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]).
|
||||
//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When
|
||||
//! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the
|
||||
//! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own
|
||||
//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4
|
||||
//! ([`ColorOut::source_profiles`]).
|
||||
//! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent
|
||||
//! of the catalog with the condition, identifier and registry; Trapped goes in the document
|
||||
//! information (`/False` when an output intent is written untrapped). PDF/A files carry their
|
||||
@@ -70,6 +74,9 @@ pub(crate) struct ColorOut {
|
||||
/// CMYK images that keep their numbers are tagged with the CMYK profile they carry
|
||||
/// ([`Self::cmyk_image_icc`]).
|
||||
image_icc: bool,
|
||||
/// Don't Include Profiles was set, in a file that doesn't tag every color: no image keeps its
|
||||
/// own ICC profile, a JPEG's `ICC_PROFILE` segments included ([`Self::source_profiles`]).
|
||||
no_profiles: bool,
|
||||
/// The CMYK profile that tags CMYK colours.
|
||||
cmyk_profile: String,
|
||||
/// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB
|
||||
@@ -117,6 +124,7 @@ impl Default for ColorOut {
|
||||
dest: None,
|
||||
tagged: false,
|
||||
image_icc: false,
|
||||
no_profiles: false,
|
||||
cmyk_profile,
|
||||
srgb_note: None,
|
||||
pixels: OnceLock::new(),
|
||||
@@ -246,9 +254,11 @@ impl ColorOut {
|
||||
}
|
||||
out.dest = Some(Dest { srgb: name == cms::SRGB, cms, model, keep, destination });
|
||||
}
|
||||
out.tagged = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4)
|
||||
let profiles = set.output.profiles.unwrap_or_default();
|
||||
let tags_all = matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4);
|
||||
out.tagged = tags_all
|
||||
|| (!set.standard.cmyk_only()
|
||||
&& match set.output.profiles {
|
||||
&& match profiles {
|
||||
ProfileInclusion::None => false,
|
||||
ProfileInclusion::All | ProfileInclusion::Destination => true,
|
||||
ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(),
|
||||
@@ -256,11 +266,14 @@ impl ColorOut {
|
||||
// Source profiles: with `all` and `taggedSource`, and in the files that tag every colour
|
||||
// unless only the destination profile is asked for; never in PDF/X-1a.
|
||||
out.image_icc = !set.standard.cmyk_only()
|
||||
&& match set.output.profiles {
|
||||
&& match profiles {
|
||||
ProfileInclusion::All | ProfileInclusion::TaggedSource => true,
|
||||
ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4),
|
||||
ProfileInclusion::None => tags_all,
|
||||
ProfileInclusion::Destination => false,
|
||||
};
|
||||
// A set Don't Include Profiles leaves out every image's own profile, outside the files
|
||||
// that tag every color.
|
||||
out.no_profiles = set.output.profiles == Some(ProfileInclusion::None) && !tags_all;
|
||||
let rgb = match &out.dest {
|
||||
Some(d) if d.model == Model::Rgb => (d.srgb, d.cms.settings().rgb.clone()),
|
||||
_ => (source.rgb_is_srgb(), st.rgb.clone()),
|
||||
@@ -367,6 +380,33 @@ impl ColorOut {
|
||||
crate::images::cmyk_icc(blob)
|
||||
}
|
||||
|
||||
/// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile
|
||||
/// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE`
|
||||
/// segments when Don't Include Profiles was set.
|
||||
pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> {
|
||||
use crate::images::CmykTag;
|
||||
match icc {
|
||||
Some(icc) => CmykTag::Profile(icc),
|
||||
None if self.no_profiles => CmykTag::Removed,
|
||||
None => CmykTag::Untagged,
|
||||
}
|
||||
}
|
||||
|
||||
/// What happens to the ICC profile a gray or RGB image carries ([`crate::images::recode`]):
|
||||
/// left out with its JPEG segments when Don't Include Profiles was set (not in PDF/A, PDF/X-3
|
||||
/// and PDF/X-4), left out of the color space in PDF/X-1a, which allows no ICC-based color
|
||||
/// spaces, and kept otherwise, also when the Profiles setting isn't set.
|
||||
pub(crate) fn source_profiles(&self) -> crate::images::SourceProfiles {
|
||||
use crate::images::SourceProfiles;
|
||||
if self.no_profiles {
|
||||
SourceProfiles::Remove
|
||||
} else if self.standard.cmyk_only() {
|
||||
SourceProfiles::Untag
|
||||
} else {
|
||||
SourceProfiles::Keep
|
||||
}
|
||||
}
|
||||
|
||||
/// How CMYK images' ink amounts are converted; `None` when they keep their numbers (no
|
||||
/// conversion, or to a CMYK destination that keeps them).
|
||||
pub(crate) fn cmyk_pixels(&self) -> Option<&CmykPixels> {
|
||||
|
||||
@@ -387,7 +387,12 @@ pub struct OutputSettings {
|
||||
/// Destination profile name (empty: the document's profile; [`DOCUMENT_CMYK`]: the CMYK
|
||||
/// profile in effect, whatever the document's colour mode).
|
||||
pub destination: String,
|
||||
pub profiles: ProfileInclusion,
|
||||
/// The Profile Inclusion setting; `None` (left out, `null` or `"default"`) when it isn't set:
|
||||
/// colors are then written as with [`ProfileInclusion::None`], while gray and RGB images keep
|
||||
/// the ICC profiles they carry. A set [`ProfileInclusion::None`] also leaves those out (see
|
||||
/// [`crate::output`]).
|
||||
#[serde(deserialize_with = "unset_or_choice")]
|
||||
pub profiles: Option<ProfileInclusion>,
|
||||
/// PDF/X output intent profile name.
|
||||
pub output_intent: String,
|
||||
pub output_condition: String,
|
||||
@@ -397,6 +402,19 @@ pub struct OutputSettings {
|
||||
pub trapped: bool,
|
||||
}
|
||||
|
||||
/// The JSON id of a setting that isn't set ([`OutputSettings::profiles`]), as `null` is.
|
||||
pub const UNSET_CHOICE: &str = "default";
|
||||
|
||||
/// A choice that may be left unset: `null` and [`UNSET_CHOICE`] are `None`, a choice's id is that
|
||||
/// choice.
|
||||
fn unset_or_choice<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
|
||||
match Option::<String>::deserialize(d)? {
|
||||
None => Ok(None),
|
||||
Some(id) if id == UNSET_CHOICE => Ok(None),
|
||||
Some(id) => T::deserialize(serde::de::value::StringDeserializer::<D::Error>::new(id)).map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Advanced section.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
|
||||
@@ -195,7 +195,8 @@ fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates()
|
||||
|
||||
/// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group
|
||||
/// without `/I true`, so it overprints the art below the group, and its graphics state still
|
||||
/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`.
|
||||
/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`, reads back isolated
|
||||
/// and is written with `/I true` again.
|
||||
#[test]
|
||||
fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() {
|
||||
for isolate in [false, true] {
|
||||
@@ -219,6 +220,42 @@ fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_
|
||||
});
|
||||
assert_eq!(overprints, [false, false, false, true], "isolate {isolate}");
|
||||
assert_eq!(knockout_groups(&back), [3], "isolate {isolate}");
|
||||
let mut found = vec![];
|
||||
back.walk(|n| {
|
||||
if n.knockout == vectorcraft_doc::Knockout::On {
|
||||
found.push(n.isolate);
|
||||
}
|
||||
});
|
||||
assert_eq!(found, [isolate], "isolate {isolate}");
|
||||
assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An isolated group with nothing blending inside but an overprinting fill reads back as an
|
||||
/// isolated group and is written with `/I true` again; a group that does not isolate reads back
|
||||
/// as its objects.
|
||||
#[test]
|
||||
fn an_isolated_group_with_an_overprinting_object_reads_back_isolated() {
|
||||
for isolate in [false, true] {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
add(&mut d, rect(Rect::new(0.0, 0.0, 200.0, 200.0), (0.9, 0.8, 0.2)));
|
||||
let mut top = rect(Rect::new(60.0, 60.0, 160.0, 160.0), (0.0, 0.0, 1.0));
|
||||
top.appearance.fill_mut().unwrap().overprint = true;
|
||||
let mut below = rect(Rect::new(20.0, 20.0, 120.0, 120.0), (1.0, 0.0, 0.0));
|
||||
(below.id, top.id) = (d.alloc_id(), d.alloc_id());
|
||||
let mut g = Node::group(NodeId(0), vec![std::sync::Arc::new(below), std::sync::Arc::new(top)]);
|
||||
g.isolate = isolate;
|
||||
add(&mut d, g);
|
||||
assert_eq!(text(&d).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}");
|
||||
let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}"));
|
||||
let mut groups = vec![];
|
||||
back.walk(|n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) {
|
||||
groups.push(n.isolate);
|
||||
}
|
||||
});
|
||||
assert_eq!(groups, if isolate { vec![true] } else { vec![] }, "isolate {isolate}");
|
||||
assert_eq!(text(&back).matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -573,6 +573,35 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() {
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask");
|
||||
}
|
||||
|
||||
/// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own
|
||||
/// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is
|
||||
/// written without a profile too. Left unset, the JPEG data stays as it is.
|
||||
#[test]
|
||||
fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() {
|
||||
let ink = [0u8, 102, 255, 0];
|
||||
let icc = cmyk_profile(|_| {});
|
||||
let jpg = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &icc);
|
||||
let d = image_doc(ImageBlob::new("image/jpeg", jpg.clone()), 64, 64);
|
||||
let export = |s: serde_json::Value| {
|
||||
let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}"));
|
||||
let w: Vec<Written> = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect();
|
||||
assert_eq!(w.len(), 1, "{s}: {w:?}");
|
||||
(w.into_iter().next().unwrap(), out.bytes)
|
||||
};
|
||||
let segment = |data: &[u8]| data.windows(12).any(|w| w == b"ICC_PROFILE\0");
|
||||
let (w, _) = export(json!({}));
|
||||
assert!(w.data == jpg && segment(&w.data), "unset: the JPEG data unchanged");
|
||||
let s = json!({"output": {"profiles": "none"}});
|
||||
let (w, bytes) = export(s.clone());
|
||||
assert_eq!((w.space.as_str(), w.filter.as_deref()), ("DeviceCMYK", Some("DCTDecode")), "{s}");
|
||||
assert!(!segment(&w.data) && w.data.len() < jpg.len(), "{s}: no ICC_PROFILE segment is left");
|
||||
assert!(w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: the other segments and the scan unchanged");
|
||||
assert_eq!(blobs(&import(&bytes).unwrap())[0].cmyk().unwrap().data, ImageBlob::new("image/jpeg", jpg.clone()).cmyk().unwrap().data);
|
||||
let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}});
|
||||
let (w, _) = export(s.clone());
|
||||
assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}");
|
||||
}
|
||||
|
||||
/// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out
|
||||
/// with a warning, as other images that large are.
|
||||
#[test]
|
||||
|
||||
@@ -266,7 +266,7 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() {
|
||||
assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None);
|
||||
assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all");
|
||||
let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap();
|
||||
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true, None);
|
||||
let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, crate::images::SourceProfiles::Keep, None);
|
||||
assert!(r.image.is_none(), "kept as it is");
|
||||
}
|
||||
|
||||
@@ -425,6 +425,80 @@ fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Don't Include Profiles set, a gray or RGB image is written without the ICC profile it
|
||||
/// carries: a PNG, JPEG or TIFF embedded as it is, resampled or compressed with JPEG, with alpha and
|
||||
/// at 16 bits. A JPEG kept as it is loses its `ICC_PROFILE` segments, its compressed samples
|
||||
/// unchanged. Left unset, or `null`, the setting keeps the profiles. PDF/X-4 files keep them
|
||||
/// whatever the setting says.
|
||||
#[test]
|
||||
fn a_set_dont_include_profiles_removes_image_profiles() {
|
||||
let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300));
|
||||
let mut clear = colour().to_rgba8();
|
||||
clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0]));
|
||||
let deep = DynamicImage::ImageRgb16(colour().to_rgb16());
|
||||
let export = |d: &Document, settings: Value| {
|
||||
let mut settings: PdfSettings = serde_json::from_value(settings).unwrap();
|
||||
settings.compression.compress_text = false;
|
||||
export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap()
|
||||
};
|
||||
let resampled =
|
||||
json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}, "gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}});
|
||||
let jpeg = json!({"color": {"compression": "jpeg"}, "gray": {"compression": "jpeg"}});
|
||||
let cases = [
|
||||
("RGB PNG", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", json!({}), "DeviceRGB"),
|
||||
("gray PNG", tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png", json!({}), "DeviceGray"),
|
||||
("RGB JPEG", tagged(&colour(), &rgb, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceRGB"),
|
||||
("gray JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", json!({}), "DeviceGray"),
|
||||
("RGB TIFF", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"),
|
||||
("gray TIFF", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceGray"),
|
||||
("RGBA TIFF", tagged(&clear.into(), &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"),
|
||||
("16-bit TIFF", tagged(&deep, &rgb, ImageFormat::Tiff), "image/tiff", json!({}), "DeviceRGB"),
|
||||
("RGB PNG, resampled", tagged(&colour(), &rgb, ImageFormat::Png), "image/png", resampled.clone(), "DeviceRGB"),
|
||||
("gray JPEG, resampled", tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg", resampled, "DeviceGray"),
|
||||
("RGB TIFF as JPEG", tagged(&colour(), &rgb, ImageFormat::Tiff), "image/tiff", jpeg.clone(), "DeviceRGB"),
|
||||
("gray TIFF as JPEG", tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff", jpeg, "DeviceGray"),
|
||||
];
|
||||
for (what, bytes, mime, compression, device) in cases {
|
||||
let d = doc(bytes.clone(), mime);
|
||||
// Left unset, or null, the image keeps its profile.
|
||||
for profiles in [json!({}), json!({"profiles": null})] {
|
||||
let r = export(&d, json!({"compression": compression.clone(), "output": profiles}));
|
||||
let spaces = image_spaces(&r.bytes);
|
||||
assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.is_some(), "{what}, {profiles}: {spaces:?}");
|
||||
}
|
||||
let none = export(&d, json!({"compression": compression.clone(), "output": {"profiles": "none"}}));
|
||||
assert!(none.warnings.is_empty(), "{what}: {:?}", none.warnings);
|
||||
let spaces = image_spaces(&none.bytes);
|
||||
assert!(spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none(), "{what}: {spaces:?}");
|
||||
let data = image_data(&none.bytes);
|
||||
assert!(data.iter().all(|d| !d.windows(12).any(|w| w == b"ICC_PROFILE\0")), "{what}: no ICC_PROFILE segment is left");
|
||||
if mime == "image/jpeg" && compression == json!({}) {
|
||||
// The JPEG data without its profile segments: the image decoder reads the same pixels
|
||||
// from it, and no profile.
|
||||
assert!(data.len() == 1 && data[0].len() < bytes.len(), "{what}: the JPEG data kept");
|
||||
let decode = |b: &[u8]| image::load_from_memory_with_format(b, ImageFormat::Jpeg).unwrap();
|
||||
assert!(decode(&data[0]) == decode(&bytes), "{what}: the same pixels");
|
||||
assert!(crate::images::source_icc(&data[0]).is_none() && crate::images::source_icc(&bytes).is_some(), "{what}");
|
||||
}
|
||||
// PDF/X-4 tags every colour: the image keeps its profile.
|
||||
let x4 = export(&d, json!({"standard": "pdfX4", "compatibility": "1.6", "compression": compression, "output": {"profiles": "none"}}));
|
||||
let spaces = image_spaces(&x4.bytes);
|
||||
assert!(spaces.len() == 1 && spaces[0].space == "ICCBased", "{what}, PDF/X-4: {spaces:?}");
|
||||
}
|
||||
// A JPEG whose `ICC_PROFILE` segments don't make up a profile (the first of two, the second
|
||||
// missing) loses them too.
|
||||
let plain = encoded(colour(), ImageFormat::Jpeg);
|
||||
let mut part = vec![0xFF, 0xD8, 0xFF, 0xE2, 0, 30];
|
||||
part.extend_from_slice(b"ICC_PROFILE\0");
|
||||
part.extend_from_slice(&[1, 2]);
|
||||
part.extend_from_slice(&rgb[..14]);
|
||||
part.extend_from_slice(&plain[2..]);
|
||||
assert!(crate::images::source_icc(&part).is_none(), "the decoder reads no profile");
|
||||
let none = export(&doc(part, "image/jpeg"), json!({"output": {"profiles": "none"}}));
|
||||
let data = image_data(&none.bytes);
|
||||
assert!(data == [plain], "an unreadable profile: the JPEG data without its segments");
|
||||
}
|
||||
|
||||
/// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based
|
||||
/// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as
|
||||
/// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels
|
||||
@@ -778,9 +852,10 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() {
|
||||
let c: CompressionSettings = serde_json::from_value(json!({})).unwrap();
|
||||
let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true });
|
||||
for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] {
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out);
|
||||
let keep = crate::images::SourceProfiles::Keep;
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, srgb_out);
|
||||
assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning);
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, None);
|
||||
let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, None);
|
||||
assert!(r.image.is_none() && r.warning.is_none(), "{what}, no conversion: {:?}", r.warning);
|
||||
// Too large to embed as it is too: the export leaves it out, and says only that.
|
||||
let mut settings: PdfSettings = serde_json::from_value(to_srgb(json!({}))).unwrap();
|
||||
|
||||
@@ -41,6 +41,24 @@ fn json_is_camel_case_and_partial_objects_keep_defaults() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Profiles setting is unset when left out, `null` or `"default"` (written as `null`), and set
|
||||
/// by a choice's id; another value is refused.
|
||||
#[test]
|
||||
fn the_profiles_setting_can_be_left_unset() {
|
||||
assert_eq!(serde_json::to_value(PdfSettings::default()).unwrap()["output"]["profiles"], serde_json::Value::Null);
|
||||
for unset in [json!({}), json!({"profiles": null}), json!({"profiles": "default"})] {
|
||||
assert_eq!(settings(json!({"output": unset.clone()})).output.profiles, None, "{unset}");
|
||||
}
|
||||
for (id, want) in [("none", ProfileInclusion::None), ("all", ProfileInclusion::All), ("taggedSource", ProfileInclusion::TaggedSource)] {
|
||||
let s = settings(json!({"output": {"profiles": id}}));
|
||||
assert_eq!(s.output.profiles, Some(want), "{id}");
|
||||
assert_eq!(serde_json::from_value::<PdfSettings>(serde_json::to_value(&s).unwrap()).unwrap(), s, "{id} round-trips");
|
||||
}
|
||||
for bad in [json!("Default"), json!("never"), json!(1)] {
|
||||
assert!(serde_json::from_value::<PdfSettings>(json!({"output": {"profiles": bad.clone()}})).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passwords_are_never_serialized() {
|
||||
let s = settings(json!({"security": {"openPassword": "secret", "permissionsPassword": "owner"}}));
|
||||
|
||||
@@ -19,13 +19,12 @@ vello_cpu = { workspace = true }
|
||||
# Filter types (Gaussian blur, drop shadow) are not re-exported by vello_cpu 0.2.
|
||||
vello_common = { version = "0.2", default-features = false }
|
||||
image = { workspace = true }
|
||||
craft-image-codecs = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
jpeg-encoder = { workspace = true }
|
||||
gif = { workspace = true }
|
||||
# TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader).
|
||||
weezl = "0.2"
|
||||
# PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader).
|
||||
png = "0.18"
|
||||
log = { workspace = true }
|
||||
# Combining marks inside a lam-alef cluster (MIT OR Apache-2.0; already used by vectorcraft-text).
|
||||
unicode-general-category = "1"
|
||||
@@ -47,8 +46,7 @@ vectorcraft-plugins = { workspace = true }
|
||||
wat = { workspace = true }
|
||||
# Decoders the export tests read their files back with.
|
||||
image = { workspace = true, features = ["tga"] }
|
||||
tiff = "0.11"
|
||||
# Reads the PSD exports back (MIT OR Apache-2.0).
|
||||
psd = "0.3"
|
||||
craft-tiff = { workspace = true }
|
||||
craft-psd = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -86,8 +86,10 @@ fn gray_and_bilevel_images_store_gray() {
|
||||
assert_eq!(gray(&file), levels);
|
||||
let (mime, file) = img.to_bilevel(150.0).unwrap();
|
||||
assert_eq!(mime, "image/tiff");
|
||||
let mut d = ::tiff::decoder::Decoder::new(std::io::Cursor::new(&file)).unwrap();
|
||||
assert_eq!(d.colortype().unwrap(), ::tiff::ColorType::Gray(1));
|
||||
let tiff = craft_tiff::Tiff::parse(&file).unwrap();
|
||||
let ifd = &tiff.ifds[0];
|
||||
assert_eq!(ifd.u16(craft_tiff::tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(ifd.value(craft_tiff::tags::BITS_PER_SAMPLE).unwrap().to_u64_vec(), vec![1]);
|
||||
let bw: Vec<u8> = [0u8, 0, 255, 255, 255, 0].iter().flat_map(|&g| [g, 255]).collect();
|
||||
assert_eq!(gray(&file), bw, "from 128 up is white");
|
||||
// Half-covered white over the light grey; a clear pixel is white.
|
||||
|
||||
@@ -144,9 +144,18 @@ fn unpack(mut src: &[u8], out: &mut Vec<u8>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The composite as a reader sees it.
|
||||
/// The stored composite: RGB stays white-matted, with its original alpha.
|
||||
fn merged(f: &[u8]) -> Vec<u8> {
|
||||
::psd::Psd::from_bytes(f).expect("a PSD a reader takes").rgba()
|
||||
let psd = craft_psd::PsdFile::from_bytes(f).expect("a PSD a reader takes");
|
||||
if psd.header.color_mode != craft_psd::ColorMode::Rgb {
|
||||
return psd.composite_rgba8().expect("composite").data;
|
||||
}
|
||||
assert_eq!(psd.header.depth, 8);
|
||||
let samples = psd.decode_merged().expect("stored composite planes");
|
||||
let count = psd.header.width as usize * psd.header.height as usize;
|
||||
(0..count)
|
||||
.flat_map(|i| [samples[i], samples[count + i], samples[2 * count + i], if psd.merged_has_alpha() { samples[3 * count + i] } else { 255 }])
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pixel(px: &[u8], width: usize, x: usize, y: usize) -> [u8; 4] {
|
||||
@@ -168,11 +177,12 @@ fn layers_are_the_top_level_layers_and_the_merged_image_is_the_render() {
|
||||
assert_eq!(p.records[1].rect, [0, 0, 50, 60], "the blue square and the corner");
|
||||
|
||||
// A reader decodes it: the layers, in place, and the merged image.
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.width(), psd.height(), psd.layers().len()), (100, 60, 2));
|
||||
let red = psd.layer_by_name("Layer 1").unwrap().rgba();
|
||||
assert_eq!(pixel(&red, 100, 20, 20), [255, 0, 0, 255]);
|
||||
assert_eq!(pixel(&red, 100, 50, 45)[3], 0, "the blue square isn't on Layer 1");
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.header.width, psd.header.height, psd.layers().len()), (100, 60, 2));
|
||||
let layer = psd.iter_layers().find(|l| l.name() == "Layer 1").unwrap();
|
||||
assert_eq!(layer.record.rect, craft_psd::layer::Rect { top: 10, left: 10, bottom: 40, right: 40 });
|
||||
let red = layer.rgba8().unwrap().data;
|
||||
assert_eq!(pixel(&red, 30, 10, 10), [255, 0, 0, 255]);
|
||||
|
||||
// The merged image is the flat render: colours on white where transparent, alpha apart.
|
||||
let img = Renderer::new().render_region_with(&doc, doc.artboards[0].rect, 1.0, &opts(PsdOptions::default()).render_options(RasterFormat::Psd));
|
||||
@@ -200,7 +210,7 @@ fn flat_writes_the_merged_image_alone_on_white() {
|
||||
assert_eq!(o.encode(&img, RasterFormat::Psd).unwrap(), file);
|
||||
let file = export(&doc, &RasterExportOptions { ppi: 150.0, ..o });
|
||||
assert_eq!(u32_at(parse(&file).resources, 12), 150 << 16);
|
||||
assert_eq!(::psd::Psd::from_bytes(&file).unwrap().width(), 208);
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().header.width, 208);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -230,8 +240,11 @@ fn maximum_editability_writes_groups_and_an_object_per_layer() {
|
||||
assert_eq!((p.records[4].opacity, p.records[4].blend, p.records[4].rect), (128, *b"mul ", [20, 30, 50, 60]));
|
||||
assert_eq!((p.records[8].blend, p.records[8].opacity), (*b"pass", 255));
|
||||
assert_eq!(p.records[6].rect, [0, 0, 6, 6]);
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert_eq!((psd.layers().len(), psd.groups().len()), (3, 3));
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
let content_layers = psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::Other)).count();
|
||||
let groups =
|
||||
psd.layers().iter().filter(|l| matches!(l.section_type(), craft_psd::SectionType::OpenFolder | craft_psd::SectionType::ClosedFolder)).count();
|
||||
assert_eq!((content_layers, groups), (3, 3));
|
||||
assert_eq!(merged(&file), merged(&export(&doc, &opts(PsdOptions::default()))), "the same merged image");
|
||||
|
||||
// Hidden layers: written hidden, drawn as if visible, instead of left out.
|
||||
@@ -300,8 +313,8 @@ fn a_background_colour_is_the_bottom_layer() {
|
||||
let p = parse(&file);
|
||||
assert_eq!((p.channels, p.count), (3, 3), "opaque: no merged alpha");
|
||||
assert_eq!((p.records[0].name.as_str(), p.records[0].rect), ("Background", [0, 0, 60, 100]));
|
||||
let psd = ::psd::Psd::from_bytes(&file).unwrap();
|
||||
assert!(psd.layer_by_name("Background").unwrap().rgba().chunks(4).all(|p| p == [0, 0, 255, 255]));
|
||||
let psd = craft_psd::PsdFile::from_bytes(&file).unwrap();
|
||||
assert!(psd.iter_layers().find(|l| l.name() == "Background").unwrap().rgba8().unwrap().data.chunks(4).all(|p| p == [0, 0, 255, 255]));
|
||||
assert_eq!(pixel(&merged(&file), 100, 5, 50), [0, 0, 255, 255]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
//! TIFF export: byte order, LZW, colour models and samples, resolution, profile, strips.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use tiff::decoder::{Decoder, DecodingResult};
|
||||
use tiff::tags::Tag;
|
||||
use craft_tiff::Tiff;
|
||||
use craft_tiff::tags;
|
||||
|
||||
use super::jpeg::ColorModel;
|
||||
use super::tiff::{self as t, ByteOrder, Compression, Image, Layout, Photometric, TiffOptions};
|
||||
|
||||
fn decoder(file: &[u8]) -> Decoder<Cursor<&[u8]>> {
|
||||
Decoder::new(Cursor::new(file)).expect("a TIFF")
|
||||
fn ifd0(file: &[u8]) -> craft_tiff::Ifd {
|
||||
Tiff::parse(file).expect("a TIFF").ifds.into_iter().next().expect("IFD0")
|
||||
}
|
||||
|
||||
fn tag_u16_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option<Vec<u16>> {
|
||||
ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u16).collect())
|
||||
}
|
||||
|
||||
fn tag_u32_vec(ifd: &craft_tiff::Ifd, tag: u16) -> Option<Vec<u32>> {
|
||||
ifd.value(tag).map(|v| v.to_u64_vec().into_iter().map(|x| x as u32).collect())
|
||||
}
|
||||
|
||||
fn pixels(file: &[u8]) -> Vec<u8> {
|
||||
match decoder(file).read_image().expect("decodes") {
|
||||
DecodingResult::U8(v) => v,
|
||||
_ => panic!("8-bit samples"),
|
||||
}
|
||||
craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, file).expect("decodes").into_data()
|
||||
}
|
||||
|
||||
/// Straight RGBA: flat areas (as art is) with a transparent corner when `clear`.
|
||||
@@ -46,7 +49,7 @@ fn byte_order_writes_an_ii_or_mm_header() {
|
||||
assert_eq!(&file[..4], magic);
|
||||
let rgb: Vec<u8> = px.chunks(4).flat_map(|p| &p[..3]).copied().collect();
|
||||
assert_eq!(pixels(&file), rgb, "{order:?}");
|
||||
assert_eq!(decoder(&file).get_tag_ascii_string(Tag::Software).unwrap(), "VectorCraft");
|
||||
assert_eq!(ifd0(&file).string(tags::SOFTWARE).as_deref(), Some("VectorCraft"));
|
||||
}
|
||||
for (s, o) in [("little", ByteOrder::Little), ("MM", ByteOrder::Big), ("mac", ByteOrder::Big), ("ii", ByteOrder::Little), ("big", ByteOrder::Big)]
|
||||
{
|
||||
@@ -61,44 +64,51 @@ fn lzw_is_smaller_and_decodes_the_same() {
|
||||
let plain = t::encode_samples(&px, 120, 90, 72.0, &TiffOptions { lzw: false, ..opts(ColorModel::Rgb) }).unwrap();
|
||||
let lzw = t::encode_samples(&px, 120, 90, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert!(lzw.len() * 4 < plain.len(), "{} vs {}", lzw.len(), plain.len());
|
||||
assert_eq!(decoder(&lzw).get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 5);
|
||||
assert_eq!(decoder(&plain).get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 1);
|
||||
assert_eq!(ifd0(&lzw).u16(tags::COMPRESSION), Some(5));
|
||||
assert_eq!(ifd0(&plain).u16(tags::COMPRESSION), Some(1));
|
||||
assert_eq!(pixels(&lzw), px, "transparency kept as an alpha channel");
|
||||
assert_eq!(pixels(&plain), px);
|
||||
// The image crate reads it too.
|
||||
let img = image::load_from_memory_with_format(&lzw, image::ImageFormat::Tiff).unwrap().to_rgba8();
|
||||
assert_eq!(img.into_raw(), px);
|
||||
let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &lzw).unwrap();
|
||||
assert_eq!(img.data(), px);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_models_write_their_samples() {
|
||||
let px = art(9, 6, true);
|
||||
let rgba = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert_eq!(decoder(&rgba).colortype().unwrap(), tiff::ColorType::RGBA(8));
|
||||
assert_eq!(decoder(&rgba).get_tag_u16_vec(Tag::ExtraSamples).unwrap(), [2], "unassociated alpha");
|
||||
let rgba_ifd = ifd0(&rgba);
|
||||
assert_eq!(rgba_ifd.u16(tags::PHOTOMETRIC), Some(2));
|
||||
assert_eq!(rgba_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(4));
|
||||
assert_eq!(tag_u16_vec(&rgba_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8, 8, 8, 8].as_slice()));
|
||||
assert_eq!(tag_u16_vec(&rgba_ifd, tags::EXTRA_SAMPLES).as_deref(), Some([2].as_slice()), "unassociated alpha");
|
||||
let opaque = art(9, 6, false);
|
||||
let rgb = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert_eq!(decoder(&rgb).colortype().unwrap(), tiff::ColorType::RGB(8));
|
||||
assert!(decoder(&rgb).find_tag(Tag::ExtraSamples).unwrap().is_none());
|
||||
let rgb_ifd = ifd0(&rgb);
|
||||
assert_eq!(rgb_ifd.u16(tags::PHOTOMETRIC), Some(2));
|
||||
assert_eq!(rgb_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(3));
|
||||
assert!(rgb_ifd.value(tags::EXTRA_SAMPLES).is_none());
|
||||
|
||||
let gray = t::encode_samples(&opaque, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap();
|
||||
assert_eq!(decoder(&gray).colortype().unwrap(), tiff::ColorType::Gray(8));
|
||||
assert_eq!(decoder(&gray).get_tag_unsigned::<u16>(Tag::PhotometricInterpretation).unwrap(), 1, "black is zero");
|
||||
let gray_ifd = ifd0(&gray);
|
||||
assert_eq!(gray_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(tag_u16_vec(&gray_ifd, tags::BITS_PER_SAMPLE).as_deref(), Some([8].as_slice()));
|
||||
assert_eq!(gray_ifd.u16(tags::PHOTOMETRIC), Some(1), "black is zero");
|
||||
let g = pixels(&gray);
|
||||
assert_eq!((g[0], g[8]), (super::jpeg::to_gray()([200, 30, 40]), 255), "lightness; white stays white");
|
||||
let on_white = t::encode_samples(&px, 9, 6, 72.0, &opts(ColorModel::Gray)).unwrap();
|
||||
assert_eq!(decoder(&on_white).colortype().unwrap(), tiff::ColorType::Gray(8), "grey has no alpha: few readers take it");
|
||||
let on_white_ifd = ifd0(&on_white);
|
||||
assert_eq!(on_white_ifd.u16(tags::SAMPLES_PER_PIXEL), Some(1), "grey has no alpha: few readers take it");
|
||||
assert_eq!(pixels(&on_white)[0], 255, "the transparent corner is white");
|
||||
|
||||
// CMYK: four samples a pixel, ink amounts as given.
|
||||
let inks: Vec<u8> = (0..9 * 6 * 4).map(|i| (i * 7 % 256) as u8).collect();
|
||||
let cmyk = t::encode_samples(&inks, 9, 6, 72.0, &opts(ColorModel::Cmyk)).unwrap();
|
||||
let mut d = decoder(&cmyk);
|
||||
assert_eq!(d.colortype().unwrap(), tiff::ColorType::CMYK(8));
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::SamplesPerPixel).unwrap(), 4);
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::PhotometricInterpretation).unwrap(), 5, "separated");
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::Unknown(332)).unwrap(), 1, "CMYK inks");
|
||||
assert_eq!(pixels(&cmyk), inks);
|
||||
let d = ifd0(&cmyk);
|
||||
assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(4));
|
||||
assert_eq!(d.u16(tags::PHOTOMETRIC), Some(5), "separated");
|
||||
assert_eq!(d.u16(332), Some(1), "CMYK inks");
|
||||
let cmyk_img = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &cmyk).unwrap();
|
||||
assert_eq!(cmyk_img.data(), inks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -106,16 +116,18 @@ fn resolution_tags_and_the_profile() {
|
||||
let px = art(4, 4, false);
|
||||
for (ppi, rational) in [(300.0, (300, 1)), (72.5, (7250, 100))] {
|
||||
let file = t::encode_samples(&px, 4, 4, ppi, &opts(ColorModel::Rgb)).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
for tag in [Tag::XResolution, Tag::YResolution] {
|
||||
assert_eq!(d.get_tag(tag).unwrap(), tiff::decoder::ifd::Value::Rational(rational.0, rational.1));
|
||||
let d = ifd0(&file);
|
||||
for tag in [tags::X_RESOLUTION, tags::Y_RESOLUTION] {
|
||||
let Some(craft_tiff::Value::Rational(v)) = d.value(tag) else { panic!("rational") };
|
||||
assert_eq!(v.as_slice(), &[rational]);
|
||||
}
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::ResolutionUnit).unwrap(), 2, "inches");
|
||||
assert_eq!(d.u16(tags::RESOLUTION_UNIT), Some(2), "inches");
|
||||
}
|
||||
for model in ColorModel::ALL {
|
||||
let src = if model == ColorModel::Cmyk { vec![0; 64] } else { px.clone() };
|
||||
let file = t::encode_samples(&src, 4, 4, 72.0, &TiffOptions { embed_icc: true, ..opts(model) }).unwrap();
|
||||
let icc = decoder(&file).get_tag_u8_vec(Tag::IccProfile).unwrap();
|
||||
let ifd = ifd0(&file);
|
||||
let icc = ifd.bytes(tags::ICC_PROFILE).unwrap();
|
||||
assert_eq!(&icc[36..40], b"acsp", "{model:?}: an ICC profile");
|
||||
let space: &[u8; 4] = match model {
|
||||
ColorModel::Rgb => b"RGB ",
|
||||
@@ -125,7 +137,7 @@ fn resolution_tags_and_the_profile() {
|
||||
assert_eq!(&icc[16..20], space, "{model:?}");
|
||||
}
|
||||
let file = t::encode_samples(&px, 4, 4, 72.0, &opts(ColorModel::Rgb)).unwrap();
|
||||
assert!(decoder(&file).find_tag(Tag::IccProfile).unwrap().is_none());
|
||||
assert!(ifd0(&file).value(tags::ICC_PROFILE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -135,10 +147,10 @@ fn big_images_take_several_strips_in_either_order() {
|
||||
for order in ByteOrder::ALL {
|
||||
for lzw in [false, true] {
|
||||
let file = t::encode_samples(&px, w, h, 72.0, &TiffOptions { lzw, byte_order: order, ..opts(ColorModel::Gray) }).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
let offsets = d.get_tag_u32_vec(Tag::StripOffsets).unwrap();
|
||||
let d = ifd0(&file);
|
||||
let offsets = tag_u32_vec(&d, tags::STRIP_OFFSETS).unwrap();
|
||||
// 300 bytes a row: 27 rows a strip.
|
||||
assert_eq!(d.get_tag_u32(Tag::RowsPerStrip).unwrap(), 27);
|
||||
assert_eq!(d.u32(tags::ROWS_PER_STRIP), Some(27));
|
||||
assert_eq!(offsets.len(), 4);
|
||||
assert!(offsets.iter().all(|o| o % 2 == 0), "strips start on a word");
|
||||
assert_eq!(pixels(&file).len(), (w * h) as usize, "{order:?} lzw {lzw}");
|
||||
@@ -152,11 +164,19 @@ fn packbits_and_bilevel_images_decode() {
|
||||
let rows = [0b1010_1010u8, 0b1100_0000, 0xFF, 0xC0, 0, 0];
|
||||
let image = Image { width: 10, height: 3, data: &rows, photometric: Photometric::WhiteIsZero, samples: 1, bits: 1, alpha: false };
|
||||
let file = t::write(&image, &Layout { byte_order: ByteOrder::Big, compression: Compression::PackBits, ppi: 72.0, icc: None }).unwrap();
|
||||
let mut d = decoder(&file);
|
||||
assert_eq!(d.colortype().unwrap(), tiff::ColorType::Gray(1));
|
||||
assert_eq!(d.get_tag_unsigned::<u16>(Tag::Compression).unwrap(), 32773);
|
||||
let d = ifd0(&file);
|
||||
assert_eq!(d.u16(tags::SAMPLES_PER_PIXEL), Some(1));
|
||||
assert_eq!(tag_u16_vec(&d, tags::BITS_PER_SAMPLE).as_deref(), Some([1].as_slice()));
|
||||
assert_eq!(d.u16(tags::COMPRESSION), Some(32773));
|
||||
// The decoder turns WhiteIsZero into black-is-zero.
|
||||
assert_eq!(pixels(&file), rows.map(|b| !b));
|
||||
let dec = craft_image_codecs::decode_as(craft_image_codecs::Format::Tiff, &file).unwrap();
|
||||
assert_eq!(dec.width(), 10);
|
||||
assert_eq!(dec.height(), 3);
|
||||
assert_eq!(
|
||||
dec.data(),
|
||||
[0, 255, 0, 255, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
|
||||
"WhiteIsZero samples are inverted and row padding is ignored"
|
||||
);
|
||||
// A buffer that doesn't match the size is refused, not written.
|
||||
let short = Image { data: &rows[..5], ..image };
|
||||
assert!(t::write(&short, &Layout { byte_order: ByteOrder::Little, compression: Compression::None, ppi: 72.0, icc: None }).is_err());
|
||||
|
||||
@@ -337,6 +337,38 @@ fn a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Transform effect listed after a Bas Relief turns its light with the art: a group of a black
|
||||
/// square centered on a white one, lit from the top and turned 90° counterclockwise about its
|
||||
/// center, draws as the group lit from the left.
|
||||
#[test]
|
||||
fn a_transform_after_bas_relief_turns_its_light_with_the_art() {
|
||||
let relieved = |effects: Vec<(&str, serde_json::Value)>| {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let mut square =
|
||||
|r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0)));
|
||||
let members = vec![square(Rect::new(20.0, 20.0, 80.0, 80.0), Color::WHITE), square(Rect::new(40.0, 40.0, 60.0, 60.0), Color::BLACK)];
|
||||
let mut g = Node::group(d.alloc_id(), members);
|
||||
g.appearance.effects = effects.into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, g).unwrap();
|
||||
render(&d)
|
||||
};
|
||||
let relief = |light: &str| ("sketch.basRelief", json!({"lightDirection": light}));
|
||||
let turned = relieved(vec![relief("top"), ("distort.transform", json!({"rotate": 90}))]);
|
||||
let left = relieved(vec![relief("left")]);
|
||||
let top = relieved(vec![relief("top")]);
|
||||
// The largest difference of a channel between two images.
|
||||
let diff = |a: &Rendered, b: &Rendered| {
|
||||
(0..100u32)
|
||||
.flat_map(|y| (0..100u32).map(move |x| (x, y)))
|
||||
.map(|(x, y)| a.pixel(x, y).iter().zip(b.pixel(x, y)).map(|(p, q)| p.abs_diff(q)).max().unwrap_or(0))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
};
|
||||
assert!(diff(&left, &top) > 50, "the light's direction shows: {}", diff(&left, &top));
|
||||
assert!(diff(&turned, &left) <= 2, "turned top light draws as a left light: {}", diff(&turned, &left));
|
||||
}
|
||||
|
||||
/// An object's or a group's Transform effect transforms the raster effects of what it holds with
|
||||
/// the art: halving a 40 pt square about its center halves the 10 pt offset of its fill's shadow,
|
||||
/// and of a group member's own shadow, with Scale Strokes & Effects off or on.
|
||||
|
||||
+173
-32
@@ -258,9 +258,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
return None;
|
||||
}
|
||||
let to = fitted_dims(w, h, allowance)?;
|
||||
// A PNG that isn't interlaced is read a row at a time when the reader's buffers fit the allowance.
|
||||
// A PNG that isn't interlaced or animated (and upright in pre-pixel EXIF) is read a row at a time when the reader's buffers fit the allowance.
|
||||
let row_scratch = if format == image::ImageFormat::Png {
|
||||
png_reader(bytes).filter(|r| !r.info().interlaced).and_then(|r| png_row_scratch(&r)).filter(|&s| s <= allowance)
|
||||
let streamed = craft_image_codecs::PngDecodeRows::new_streaming(bytes, &png_streaming_limits(allowance))
|
||||
.ok()
|
||||
.filter(|dec| dec.streamable())
|
||||
.and_then(|dec| png_row_scratch(&dec.header()));
|
||||
streamed.or_else(|| png_row_scratch_from_header(bytes, w, h, d.total_bytes())).filter(|&s| s <= allowance)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -272,6 +276,13 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
(rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch })
|
||||
}
|
||||
|
||||
/// Streaming retains rows, not the declared full image. Preserve the renderer's source-pixel
|
||||
/// allowance even when RGBA16's declared samples exceed the shared whole-image default budget.
|
||||
/// Row scratch and the reduced pixmap are admitted separately before decoding starts.
|
||||
fn png_streaming_limits(source_pixels: u64) -> craft_image_codecs::Limits {
|
||||
craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: source_pixels, max_alloc: source_pixels.saturating_mul(8) }
|
||||
}
|
||||
|
||||
/// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time.
|
||||
const BAND: u32 = 16;
|
||||
|
||||
@@ -283,17 +294,58 @@ const PNG_KEPT_ROWS: u64 = 128 << 10;
|
||||
/// stream buffer grows by.
|
||||
const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10);
|
||||
|
||||
/// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer
|
||||
/// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous
|
||||
/// and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer grows by doubling its reservation,
|
||||
/// and while it grows its old reservation and the new one, up to twice the size it holds, are both
|
||||
/// allocated: three times that size at most. A copy of a stored row and the row given out come on
|
||||
/// top. `None` when a row given out doesn't fit memory.
|
||||
fn png_row_scratch(r: &png::Reader<std::io::Cursor<&[u8]>>) -> Option<u64> {
|
||||
let info = r.info();
|
||||
// A filter byte and the row's samples, in whole bytes.
|
||||
let stored = 1 + (u64::from(info.width) * info.color_type.samples() as u64 * info.bit_depth as u64).div_ceil(8);
|
||||
let out = u64::try_from(r.output_line_size(info.width)?).ok()?;
|
||||
/// The most memory `craft-image-codecs`'s PNG row decoder takes in its buffers to read its image
|
||||
/// a row at a time: the stream buffer holds the rows already read up to [`PNG_KEPT_ROWS`] or four
|
||||
/// rows, whichever is more, the previous and current rows, and [`PNG_WINDOW_AND_STEP`]. The buffer
|
||||
/// grows by doubling its reservation, and while it grows its old reservation and the new one, up
|
||||
/// to twice the size it holds, are both allocated: three times that size at most. A copy of a
|
||||
/// stored row and the row given out come on top. `None` when a row given out doesn't fit memory.
|
||||
fn png_row_scratch(hdr: &craft_image_codecs::PngHeader) -> Option<u64> {
|
||||
let out = u64::from(hdr.width).checked_mul(hdr.layout.channels() as u64)?.checked_mul(hdr.sample.bytes() as u64)?;
|
||||
png_row_scratch_for_row(out)
|
||||
}
|
||||
|
||||
/// The row decoder rejects a truncated PNG's tiny IDAT before it can report its header. For a
|
||||
/// size estimate, the image decoder still gives us the declared output bytes; use those only when
|
||||
/// the PNG header says it is a static, non-interlaced image, the format the renderer can stream.
|
||||
fn png_row_scratch_from_header(bytes: &[u8], width: u32, height: u32, total_bytes: u64) -> Option<u64> {
|
||||
const SIG: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
|
||||
if bytes.get(..8)? != SIG || height == 0 || !total_bytes.is_multiple_of(u64::from(height)) {
|
||||
return None;
|
||||
}
|
||||
let mut at = 8usize;
|
||||
let mut header = false;
|
||||
loop {
|
||||
let len = u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize;
|
||||
let kind = bytes.get(at + 4..at + 8)?;
|
||||
let data_at = at.checked_add(8)?;
|
||||
let end = data_at.checked_add(len)?;
|
||||
let data = bytes.get(data_at..end)?;
|
||||
match kind {
|
||||
b"IHDR" if len == 13 && !header => {
|
||||
header = true;
|
||||
if at != 8
|
||||
|| u32::from_be_bytes(data[..4].try_into().ok()?) != width
|
||||
|| u32::from_be_bytes(data[4..8].try_into().ok()?) != height
|
||||
|| data[12] != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
b"acTL" | b"eXIf" => return None,
|
||||
b"IDAT" if header => {
|
||||
let row = total_bytes / u64::from(height);
|
||||
return row.checked_add(1).and_then(png_row_scratch_for_row);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
at = end.checked_add(4)?; // CRC
|
||||
}
|
||||
}
|
||||
|
||||
fn png_row_scratch_for_row(out: u64) -> Option<u64> {
|
||||
// A filter byte and the row's samples.
|
||||
let stored = 1u64.checked_add(out)?;
|
||||
let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS);
|
||||
let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP;
|
||||
Some(stream * 3 + stored + out)
|
||||
@@ -313,14 +365,6 @@ fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> {
|
||||
(u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh))
|
||||
}
|
||||
|
||||
/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its
|
||||
/// header and the chunks before the pixels read.
|
||||
fn png_reader(bytes: &[u8]) -> Option<png::Reader<std::io::Cursor<&[u8]>>> {
|
||||
let mut d = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
d.read_info().ok()
|
||||
}
|
||||
|
||||
/// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the
|
||||
/// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and
|
||||
/// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit
|
||||
@@ -335,19 +379,64 @@ fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result<vello_cpu::Pixmap, Unde
|
||||
|
||||
/// `bytes` read and shrunk as [`reduced_pixmap`] says.
|
||||
fn shrunk(bytes: &[u8], r: &Reduction) -> Option<vello_cpu::Pixmap> {
|
||||
shrunk_with_png_limits(bytes, r, &png_streaming_limits(allowance()))
|
||||
}
|
||||
|
||||
fn shrunk_with_png_limits(bytes: &[u8], r: &Reduction, png_limits: &craft_image_codecs::Limits) -> Option<vello_cpu::Pixmap> {
|
||||
let mut shrink = Shrink::new(r.size, r.to);
|
||||
if r.rows {
|
||||
let mut reader = png_reader(bytes)?;
|
||||
let (color, _) = reader.output_color_type();
|
||||
while let Some(row) = reader.next_row().ok()? {
|
||||
let data = row.data();
|
||||
match color {
|
||||
png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])),
|
||||
png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()),
|
||||
png::ColorType::Indexed => return None,
|
||||
}
|
||||
use craft_image_codecs::{ChannelLayout, CodecError, Format, PngDecodeRows, SampleType};
|
||||
let mut dec = PngDecodeRows::new_streaming(bytes, png_limits).ok()?;
|
||||
if !dec.streamable() {
|
||||
return None;
|
||||
}
|
||||
let hdr = dec.header();
|
||||
// Yield after each row and stop once all pixels have arrived. The pinned decoder's
|
||||
// first tail batch only locates a text chunk; later batches inflate/retain its value.
|
||||
// Never run those batches: the renderer needs pixels, not ancillary text. Its underlying
|
||||
// PNG reader also ignores text chunks before IDAT, so neither location retains text.
|
||||
for _ in 0..hdr.height {
|
||||
let _extras = dec
|
||||
.step_stream::<CodecError>(1, &mut || false, &mut |_y, row| {
|
||||
match (hdr.layout, hdr.sample) {
|
||||
(ChannelLayout::Gray, SampleType::U8) => shrink.row(row.iter().map(|&g| [g, g, g, 255])),
|
||||
(ChannelLayout::GrayA, SampleType::U8) => shrink.row(row.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
(ChannelLayout::Rgb, SampleType::U8) => shrink.row(row.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
(ChannelLayout::Rgba, SampleType::U8) => shrink.row(row.as_chunks::<4>().0.iter().copied()),
|
||||
(ChannelLayout::Gray, SampleType::U16) => shrink.row(row.as_chunks::<2>().0.iter().map(|&g| {
|
||||
let v = (u16::from_ne_bytes(g) >> 8) as u8;
|
||||
[v, v, v, 255]
|
||||
})),
|
||||
(ChannelLayout::GrayA, SampleType::U16) => shrink.row(row.as_chunks::<4>().0.iter().map(|&[g0, g1, a0, a1]| {
|
||||
let g = (u16::from_ne_bytes([g0, g1]) >> 8) as u8;
|
||||
let a = (u16::from_ne_bytes([a0, a1]) >> 8) as u8;
|
||||
[g, g, g, a]
|
||||
})),
|
||||
(ChannelLayout::Rgb, SampleType::U16) => shrink.row(row.as_chunks::<6>().0.iter().map(|&[r0, r1, g0, g1, b0, b1]| {
|
||||
[
|
||||
(u16::from_ne_bytes([r0, r1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([g0, g1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([b0, b1]) >> 8) as u8,
|
||||
255,
|
||||
]
|
||||
})),
|
||||
(ChannelLayout::Rgba, SampleType::U16) => {
|
||||
shrink.row(row.as_chunks::<8>().0.iter().map(|&[r0, r1, g0, g1, b0, b1, a0, a1]| {
|
||||
[
|
||||
(u16::from_ne_bytes([r0, r1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([g0, g1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([b0, b1]) >> 8) as u8,
|
||||
(u16::from_ne_bytes([a0, a1]) >> 8) as u8,
|
||||
]
|
||||
}))
|
||||
}
|
||||
_ => {
|
||||
return Err(CodecError::Unsupported { format: Format::Png, reason: "unsupported PNG channel layout".into() });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.ok()?;
|
||||
}
|
||||
} else {
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
@@ -589,6 +678,58 @@ mod tests {
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_header_accepts_rgba16_above_whole_image_default() {
|
||||
// Header-only fixture: opening the stream checks declared size without allocating or
|
||||
// decoding the 1.2 GB canvas. Padding meets the decoder's compressed-size plausibility
|
||||
// bound; no rows are requested from this deliberately incomplete image.
|
||||
let (w, h) = (10_000u32, 15_000u32);
|
||||
let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[16, 6, 0, 0, 0]].concat();
|
||||
let mut idat = b"IDAT\x78\x9c".to_vec();
|
||||
idat.resize(1_200_000, 0);
|
||||
for chunk in [&ihdr[..], &idat, b"IEND"] {
|
||||
bytes.extend((chunk.len() as u32 - 4).to_be_bytes());
|
||||
bytes.extend(chunk);
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(chunk);
|
||||
bytes.extend(crc.sum().to_be_bytes());
|
||||
}
|
||||
let default = craft_image_codecs::Limits { max_alloc: 1 << 30, max_pixels: 150_000_000, ..Default::default() };
|
||||
assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &default).is_err());
|
||||
let rows = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(150_000_000)).unwrap();
|
||||
assert_eq!((rows.header().width, rows.header().height), (w, h));
|
||||
assert!(rows.streamable());
|
||||
assert!(craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &png_streaming_limits(149_999_999)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_reduction_does_not_retain_text_after_pixels() {
|
||||
let mut bytes = Vec::new();
|
||||
striped(8).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
|
||||
let mut chunk = b"tEXtComment\0".to_vec();
|
||||
chunk.extend(std::iter::repeat_n(b'x', 1 << 20));
|
||||
// PNG's IEEE CRC over type and payload, kept local to this fixture.
|
||||
let mut crc = u32::MAX;
|
||||
for &byte in &chunk {
|
||||
crc ^= u32::from(byte);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xedb88320 & 0u32.wrapping_sub(crc & 1));
|
||||
}
|
||||
}
|
||||
let mut tail = ((chunk.len() - 4) as u32).to_be_bytes().to_vec();
|
||||
tail.extend(chunk);
|
||||
tail.extend((!crc).to_be_bytes());
|
||||
bytes.splice(bytes.len() - 12..bytes.len() - 12, tail);
|
||||
let limits = craft_image_codecs::Limits { max_alloc: 1 << 19, ..Default::default() };
|
||||
let mut full = craft_image_codecs::PngDecodeRows::new_streaming(&bytes, &limits).unwrap();
|
||||
assert!(full.step_stream::<craft_image_codecs::CodecError>(1, &mut || true, &mut |_, _| Ok(())).is_err());
|
||||
// The renderer stops after the pixels instead of retaining ancillary text.
|
||||
let reduced = shrunk_with_png_limits(&bytes, &Reduction { size: (8, 1), to: (4, 1), rows: true, scratch: 0 }, &limits).unwrap();
|
||||
assert_eq!((reduced.width(), reduced.height()), (4, 1));
|
||||
assert!(red_at_its_coverage(&reduced));
|
||||
}
|
||||
|
||||
/// Opaque red beside clear black, every other column of a `w` × 1 image.
|
||||
fn striped(w: u32) -> image::RgbaImage {
|
||||
image::RgbaImage::from_fn(w, 1, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })
|
||||
|
||||
@@ -1883,14 +1883,14 @@ fn a_png_past_the_allowance_draws_at_reduced_size() {
|
||||
assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (300, 300, [200, 40, 40, 255]));
|
||||
// A row is read only while the reader's buffers fit the allowance, counting the stream buffer
|
||||
// three times for the moment it grows. Below 4,096 columns of 16-bit RGBA they take 516,103
|
||||
// bytes and 60 a column: 1,398 columns take 599,983 bytes, within 600,000, and 1,399 columns
|
||||
// take 600,043 and are not decoded (their samples, 8 bytes a pixel, are past it too).
|
||||
// bytes plus 64 bytes a column: 1,310 columns take 599,943 bytes, within 600,000, and 1,311
|
||||
// columns take 600,007 and are not decoded (their samples, 8 bytes a pixel, are past it too).
|
||||
let wide = |w: u32| {
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(w, 60, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png)
|
||||
};
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1398))), Some((1398, 60)));
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1399))), None);
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1310))), Some((1310, 60)));
|
||||
assert_eq!(with_allowance(600_000, || paint::reduced_size(&wide(1311))), None);
|
||||
// An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray
|
||||
// pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not.
|
||||
let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png);
|
||||
@@ -1938,13 +1938,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() {
|
||||
// Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result
|
||||
// of 15,768 bytes.
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// Read a row at a time: 540,103 bytes in the reader's buffers for 400 columns of 16-bit RGBA,
|
||||
// Read a row at a time: 541,703 bytes in the reader's buffers for 400 columns of 16-bit RGBA,
|
||||
// beside a 387 × 387 result of 599,076 bytes.
|
||||
let png = encoded(
|
||||
image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(400, 400, image::Rgba([51400, 10280, 10280, 65535]))),
|
||||
image::ImageFormat::Png,
|
||||
);
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 540_103, (387, 387))] {
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 600_000, 599_076 + 541_703, (387, 387))] {
|
||||
let failed = decode_failures();
|
||||
let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes)));
|
||||
assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later");
|
||||
|
||||
@@ -86,11 +86,15 @@ impl Writer<'_> {
|
||||
// type with warichu, whose stacked lines a reader's <text> can't place either. So are
|
||||
// small capitals, superscript and subscript and tab leaders, which SVG text doesn't draw (#3869),
|
||||
// and a glyph chosen for a character, which a reader's <text> draws with the default glyph. So
|
||||
// is type in one of the document's composite fonts, which a reader can't find by its name.
|
||||
// is type in one of the document's composite fonts, which a reader can't find by its name,
|
||||
// and type with an Adjust Diacritic Position, whose marks a reader's <text> draws where the
|
||||
// font puts them.
|
||||
let unwritable = t.runs.iter().any(|r| {
|
||||
r.style.small_caps.is_some()
|
||||
|| r.style.position != vectorcraft_doc::CharPosition::Normal
|
||||
|| r.style.glyph_alternate.is_some()
|
||||
|| r.style.diacritic_horizontal != 0.0
|
||||
|| r.style.diacritic_vertical != 0.0
|
||||
|| vectorcraft_doc::CompositeFont::named(&doc.composite_fonts, &r.style.font_family).is_some()
|
||||
}) || std::iter::once(&t.para).chain(&t.paras).any(|p| p.tabs.iter().any(|tab| !tab.leader.is_empty()));
|
||||
let outlined = self.opts.outline_text
|
||||
|
||||
+57
-12
@@ -315,9 +315,51 @@ impl V {
|
||||
}
|
||||
}
|
||||
|
||||
/// σ of a blur with standard deviations `x`, `y` (their mean: the effects blur evenly).
|
||||
fn sd(x: f32, y: f32) -> f64 {
|
||||
(x as f64 + y as f64) / 2.0
|
||||
/// σ of a blur with standard deviations `x`, `y` in a user space the document scales by the same
|
||||
/// amount in every direction when `even` (turned, flipped or scaled alike along both axes). The
|
||||
/// effects blur evenly: `None` when the blur differs by direction in the document, unless `blurs`
|
||||
/// is [`Blurs::Nearest`], which takes the mean.
|
||||
fn sd(x: f32, y: f32, even: bool, blurs: Blurs) -> Option<f64> {
|
||||
let uneven = (x > 0.0 || y > 0.0) && (x != y || !even);
|
||||
(blurs == Blurs::Nearest || !uneven).then_some((x as f64 + y as f64) / 2.0)
|
||||
}
|
||||
|
||||
/// How [`effects`] reads a blur that differs by direction in the document, which the effects
|
||||
/// draw the same in every direction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Blurs {
|
||||
/// Not as an effect: the filter is left for an SVG Filters effect ([`kept`]), which draws it.
|
||||
Exact,
|
||||
/// As the even blur of the mean standard deviation.
|
||||
Nearest,
|
||||
}
|
||||
|
||||
/// Whether the linear part of `ts` scales every direction by the same amount (a turn, a flip and
|
||||
/// an even scale), so an even blur stays even in the document.
|
||||
fn even_space(ts: Affine) -> bool {
|
||||
let [a, b, c, d, _, _] = ts.as_coeffs();
|
||||
let tol = 1e-9 * ts.determinant().abs().sqrt().max(1.0);
|
||||
let near = |p: f64, q: f64| (p - q).abs() <= tol;
|
||||
(near(a, d) && near(b, -c)) || (near(a, -d) && near(b, c))
|
||||
}
|
||||
|
||||
/// `filters` (in the order they apply) imported in user space mapped to the document by `ts`: as
|
||||
/// the live effects they draw as ([`effects`]), else as SVG Filters effects that keep their XML
|
||||
/// ([`kept`]), else as the live effects nearest them (a blur that differs by direction drawn as
|
||||
/// an even one). With whether they are live effects. `None` when none of these takes them.
|
||||
pub(super) fn imported(
|
||||
filters: &[Arc<Filter>],
|
||||
ts: Affine,
|
||||
blends: &HashMap<String, String>,
|
||||
sources: &HashMap<String, Source>,
|
||||
) -> Option<(Vec<Effect>, bool)> {
|
||||
if let Some(fx) = effects(filters, ts, blends, Blurs::Exact) {
|
||||
return Some((fx, true));
|
||||
}
|
||||
if let Some(fx) = kept(filters, ts, sources) {
|
||||
return Some((fx, false));
|
||||
}
|
||||
effects(filters, ts, blends, Blurs::Nearest).map(|fx| (fx, true))
|
||||
}
|
||||
|
||||
fn color(c: usvg::Color) -> Color {
|
||||
@@ -364,9 +406,10 @@ fn transferred(v: V, [r, g, b, a]: [&TransferFunction; 4], srgb: bool) -> Option
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate one filter's primitives, `k` the scale from its user space to the document.
|
||||
/// Evaluate one filter's primitives, `k` the scale from its user space to the document, `even`
|
||||
/// when that scale is the same in every direction ([`even_space`]), blurs read as `blurs` says.
|
||||
/// `None` when one does something the effects cannot represent.
|
||||
fn eval(f: &Filter, k: f64) -> Option<V> {
|
||||
fn eval(f: &Filter, k: f64, even: bool, blurs: Blurs) -> Option<V> {
|
||||
let mut results: HashMap<&str, V> = HashMap::new();
|
||||
let mut last = V::Graphic;
|
||||
for p in f.primitives() {
|
||||
@@ -380,7 +423,7 @@ fn eval(f: &Filter, k: f64) -> Option<V> {
|
||||
let v = match p.kind() {
|
||||
Kind::GaussianBlur(b) => {
|
||||
let linear = p.color_interpolation() == ColorInterpolation::LinearRGB;
|
||||
input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get()), linear)?
|
||||
input(b.input())?.blur(sd(b.std_dev_x().get(), b.std_dev_y().get(), even, blurs)?, linear)?
|
||||
}
|
||||
Kind::Offset(o) => input(o.input())?.offset(o.dx() as f64, o.dy() as f64)?,
|
||||
Kind::Flood(fl) => V::Flood(color(fl.color()), fl.opacity().get()),
|
||||
@@ -450,8 +493,8 @@ fn eval(f: &Filter, k: f64) -> Option<V> {
|
||||
}
|
||||
}
|
||||
Kind::DropShadow(d) if matches!(input(d.input())?, V::Graphic) => {
|
||||
let shape =
|
||||
Shape { sd: sd(d.std_dev_x().get(), d.std_dev_y().get()), dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false };
|
||||
let sd = sd(d.std_dev_x().get(), d.std_dev_y().get(), even, blurs)?;
|
||||
let shape = Shape { sd, dx: d.dx() as f64, dy: d.dy() as f64, moved: true, inverted: false };
|
||||
V::Stack(vec![V::Paint { shape, color: color(d.color()), opacity: d.opacity().get(), clipped: false }, V::Graphic])
|
||||
}
|
||||
_ => return None,
|
||||
@@ -463,10 +506,12 @@ fn eval(f: &Filter, k: f64) -> Option<V> {
|
||||
}
|
||||
|
||||
/// The live effects `filters` (in the order they apply) stand for, in user space mapped to the
|
||||
/// document by `ts`; `blends`: the modes our export recorded ([`blends`]). `None` when one of
|
||||
/// them isn't an effect the canvas draws.
|
||||
pub(super) fn effects(filters: &[Arc<Filter>], ts: Affine, blends: &HashMap<String, String>) -> Option<Vec<Effect>> {
|
||||
/// document by `ts`; `blends`: the modes our export recorded ([`blends`]); `blurs`: how a blur
|
||||
/// that differs by direction reads ([`Blurs`]). `None` when one of them isn't an effect the
|
||||
/// canvas draws.
|
||||
fn effects(filters: &[Arc<Filter>], ts: Affine, blends: &HashMap<String, String>, blurs: Blurs) -> Option<Vec<Effect>> {
|
||||
let k = ts.determinant().abs().sqrt();
|
||||
let even = even_space(ts);
|
||||
let [a, b, c, d, _, _] = ts.as_coeffs();
|
||||
let along = |dx: f64, dy: f64| Vec2::new(a * dx + c * dy, b * dx + d * dy);
|
||||
let num = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
@@ -475,7 +520,7 @@ pub(super) fn effects(filters: &[Arc<Filter>], ts: Affine, blends: &HashMap<Stri
|
||||
let blur = |sd: f64| num(2.0 * sd * k);
|
||||
let mode = blends.get(f.id()).map_or("normal", String::as_str);
|
||||
let paint = |c: Color, o: f32| (c.to_hex(), num(o as f64 * 100.0));
|
||||
let (id, params) = match eval(f, k)? {
|
||||
let (id, params) = match eval(f, k, even, blurs)? {
|
||||
V::Graphic => continue,
|
||||
// SVG blurs in linear light unless the filter asks for sRGB (`color-interpolation-filters`).
|
||||
V::Blurred(sd, true) => ("blur.gaussian", json!({ "radius": blur(sd), "linear": true })),
|
||||
|
||||
@@ -303,11 +303,11 @@ impl Importer {
|
||||
(None, id) => format!("'{id}'"),
|
||||
};
|
||||
let mask = g.mask().and_then(|m| self.opacity_mask(m, ts, &label));
|
||||
// Blurs, shadows and glows become live effects (see [`fx`]); other filters become Effect ›
|
||||
// SVG Filters effects that keep their XML.
|
||||
// Blurs, shadows and glows become live effects (see [`fx`]); other filters, and blurs that
|
||||
// differ by direction in the document, become Effect › SVG Filters effects that keep their XML.
|
||||
let effects = match g.filters() {
|
||||
[] => vec![],
|
||||
filters => fx::effects(filters, ts, &self.blends).or_else(|| fx::kept(filters, ts, &self.filter_sources)).unwrap_or_else(|| {
|
||||
filters => fx::imported(filters, ts, &self.blends, &self.filter_sources).map(|(fx, _)| fx).unwrap_or_else(|| {
|
||||
// usvg wraps a filtered element in a group of its own: name the element then.
|
||||
let on = match g.children() {
|
||||
[usvg::Node::Group(_)] | [] => label.clone(),
|
||||
@@ -383,7 +383,7 @@ impl Importer {
|
||||
/// (<https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion>) cuts a filter's result at
|
||||
/// its region. A filter that didn't import (drawn without it) clips nothing.
|
||||
fn filter_regions(&mut self, g: &usvg::Group, ts: Affine, mut n: Node) -> Option<Node> {
|
||||
if g.filters().is_empty() || fx::effects(g.filters(), ts, &self.blends).is_none() {
|
||||
if g.filters().is_empty() || !fx::imported(g.filters(), ts, &self.blends, &self.filter_sources).is_some_and(|(_, live)| live) {
|
||||
return Some(n);
|
||||
}
|
||||
for f in g.filters() {
|
||||
|
||||
@@ -284,6 +284,63 @@ fn a_gaussian_blur_becomes_the_effect_with_its_radius() {
|
||||
assert_eq!(effects(&d)[0].params["radius"], json!(12.0));
|
||||
}
|
||||
|
||||
/// A blur that differs by direction in the document (standard deviations that differ, or an even
|
||||
/// one in a user space scaled unevenly or skewed) is kept as an SVG filter, which draws it as it
|
||||
/// is, not as an even Gaussian Blur. In a turned, flipped or evenly scaled user space an even blur
|
||||
/// stays the effect.
|
||||
#[test]
|
||||
fn a_blur_that_differs_by_direction_is_kept_as_its_filter() {
|
||||
let ids = |body: &str| {
|
||||
let (d, w) = open(body);
|
||||
assert!(w.is_empty(), "{w:?}");
|
||||
effects(&d).iter().map(|e| e.id.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let blur = |sd: &str, transform: &str| {
|
||||
format!(
|
||||
r##"<defs><filter id="b"><feGaussianBlur stdDeviation="{sd}"/></filter></defs><rect x="50" y="30" width="60" height="40" fill="#08f" transform="{transform}" filter="url(#b)"/>"##
|
||||
)
|
||||
};
|
||||
assert_eq!(ids(&blur("4 1", "translate(0)")), ["svg.filter"]);
|
||||
assert_eq!(ids(&blur("3", "scale(1 4)")), ["svg.filter"]);
|
||||
assert_eq!(ids(&blur("3", "skewX(30)")), ["svg.filter"]);
|
||||
assert_eq!(ids(&blur("3", "rotate(30) scale(2)")), ["blur.gaussian"]);
|
||||
assert_eq!(ids(&blur("3", "scale(-2 2)")), ["blur.gaussian"]);
|
||||
let shadow = |sd: &str| {
|
||||
format!(
|
||||
r##"<defs><filter id="s"><feDropShadow dx="2" dy="2" stdDeviation="{sd}"/></filter></defs><rect width="60" height="40" filter="url(#s)"/>"##
|
||||
)
|
||||
};
|
||||
assert_eq!(ids(&shadow("3 1")), ["svg.filter"]);
|
||||
assert_eq!(ids(&shadow("3")), ["stylize.dropShadow"]);
|
||||
}
|
||||
|
||||
/// An SVG filter's blur in a user space scaled unevenly is written live and opens again as the
|
||||
/// same effect, which blurs more along the stretched axis, not as an even Gaussian Blur.
|
||||
#[test]
|
||||
fn an_exported_blur_in_a_stretched_user_space_opens_as_the_same_effect() {
|
||||
let xml = r#"<filter id="b" x="-1" y="-1" width="3" height="3"><feGaussianBlur stdDeviation="3"/></filter>"#;
|
||||
let mut d = Document::new(200.0, 120.0);
|
||||
let mut n = Node::path(
|
||||
d.alloc_id(),
|
||||
shapes::rectangle(Rect::new(60.0, 40.0, 140.0, 80.0)),
|
||||
Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0),
|
||||
);
|
||||
let params = json!({ "xml": xml, "scale": 2.0, "origin": [0.0, 0.0], "axes": [0.5, 0.0, 0.0, 2.0] });
|
||||
n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }];
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let out = export(&d, &ExportOptions::default());
|
||||
assert!(out.contains("<g filter=\"url(#") && !out.contains("<image"), "{out}");
|
||||
let (back, w) = import_with_report(&out).unwrap();
|
||||
assert!(w.is_empty(), "{w:?}");
|
||||
let fx = effects(&back);
|
||||
assert_eq!(fx.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["svg.filter"], "{out}");
|
||||
let num = |v: &serde_json::Value| v.as_f64().unwrap();
|
||||
let axes: Vec<f64> = fx[0].params["axes"].as_array().unwrap().iter().map(num).collect();
|
||||
assert!(axes.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}");
|
||||
assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02);
|
||||
}
|
||||
|
||||
/// `color-interpolation-filters` (SVG 1.1 §15.7.6, initially linearRGB:
|
||||
/// https://www.w3.org/TR/SVG11/painting.html#ColorInterpolationFiltersProperty) picks whether the
|
||||
/// blur mixes colours in linear light; sRGB, on the primitive or the filter, keeps them as they
|
||||
|
||||
@@ -357,6 +357,19 @@ fn a_chosen_glyph_is_written_as_outlines() {
|
||||
assert!(!svg.contains("<text") && svg.contains("<path"), "{svg}");
|
||||
}
|
||||
|
||||
/// Type with an Adjust Diacritic Position is written as outlines: a reader's `<text>` would draw
|
||||
/// the marks where the font puts them.
|
||||
#[test]
|
||||
fn moved_diacritics_are_written_as_outlines() {
|
||||
let svg = export(&area_doc(vec![run("re\u{301}sume\u{301}", style(12.0))], 280.0, Justify::Left), &ExportOptions::default());
|
||||
assert!(svg.contains("<text"), "without a moved mark the text stays live: {svg}");
|
||||
for moved in [CharStyle { diacritic_horizontal: 100.0, ..style(12.0) }, CharStyle { diacritic_vertical: -100.0, ..style(12.0) }] {
|
||||
let d = area_doc(vec![run("re\u{301}", style(12.0)), run("sume\u{301}", moved)], 280.0, Justify::Left);
|
||||
let svg = export(&d, &ExportOptions::default());
|
||||
assert!(!svg.contains("<text") && svg.contains("<path"), "{svg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A run whose font size measures the cap height is written at the em size it is drawn at: 14 pt
|
||||
/// measuring a 0.7 em cap height is `font-size="20"`, after a 12 pt run measuring the em box,
|
||||
/// which takes the `<text>` element's 12.
|
||||
|
||||
@@ -13,6 +13,12 @@
|
||||
//! a mark on a ligature (for example Geeza Pro's Allah ligature) painted as its letter. Renderers
|
||||
//! and exporters read the glyph's run as they always did, so they need no change. The text itself
|
||||
//! is never changed.
|
||||
//!
|
||||
//! The Adjust Horizontal and Vertical Diacritic Positions ([`CharStyle::diacritic_horizontal`])
|
||||
//! move the face's mark glyphs (GDEF class 3) by the values of the glyph's run. Runs that differ
|
||||
//! only in paint and those positions stay one shaping cluster at an Arabic harakat or a Hebrew
|
||||
//! point ([`diacritic_mark_boundary`]), so a mark set apart from its letter takes its own values
|
||||
//! the same way it takes its own paint.
|
||||
|
||||
use skrifa::raw::TableProvider;
|
||||
use skrifa::raw::tables::layout::ClassDef;
|
||||
@@ -36,11 +42,24 @@ pub(crate) fn is_harakat(c: char) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// Is `c` a Hebrew point or cantillation mark (U+0591–U+05BD, U+05BF, U+05C1–U+05C2,
|
||||
/// U+05C4–U+05C5, U+05C7)?
|
||||
fn is_hebrew_mark(c: char) -> bool {
|
||||
matches!(c as u32, 0x0591..=0x05BD | 0x05BF | 0x05C1..=0x05C2 | 0x05C4..=0x05C5 | 0x05C7)
|
||||
}
|
||||
|
||||
/// Is `c` a diacritical mark the Adjust Diacritic Position fields set apart from its letter: an
|
||||
/// Arabic harakat ([`is_harakat`]) or a Hebrew point?
|
||||
pub(crate) fn is_diacritic(c: char) -> bool {
|
||||
is_harakat(c) || is_hebrew_mark(c)
|
||||
}
|
||||
|
||||
/// Do character styles `a` and `b` differ, if at all, only in paint: fill, stroke and how the
|
||||
/// stroke is drawn, overprint, and the character style name? OpenType feature differences are
|
||||
/// ignored here: they already apply to their own character ranges during shaping. Nor is the
|
||||
/// space before a line's first character read inside a cluster, which takes it from its first
|
||||
/// character (#5111). Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline
|
||||
/// character (#5111), nor the Adjust Diacritic Positions, which move a mark glyph by its own run's
|
||||
/// values. Stricter than [`crate::shape`]'s `shapes_alike` (which also ignores baseline
|
||||
/// shift, tracking, underline, …).
|
||||
pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
// Exhaustive: a new attribute must explicitly keep or relax this boundary rule.
|
||||
@@ -82,6 +101,8 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
warichu_scale,
|
||||
warichu_align,
|
||||
digits,
|
||||
diacritic_horizontal: _,
|
||||
diacritic_vertical: _,
|
||||
font_height_reference,
|
||||
no_break,
|
||||
language,
|
||||
@@ -150,6 +171,16 @@ pub(crate) fn paint_only_mark_boundary(text: &str, at: usize, before: &CharStyle
|
||||
(next.is_some_and(is_harakat) || previous.is_some_and(is_harakat)) && paint_only(before, after)
|
||||
}
|
||||
|
||||
/// Is the run boundary at byte `at` of `text`, between styles `before` and `after`, one where the
|
||||
/// Adjust Diacritic Positions differ, nothing but paint differs besides, and an Arabic harakat or a
|
||||
/// Hebrew point is on either side? It stays inside a shaping cluster as a paint-only one does.
|
||||
pub(crate) fn diacritic_mark_boundary(text: &str, at: usize, before: &CharStyle, after: &CharStyle) -> bool {
|
||||
let next = text.get(at..).and_then(|s| s.chars().next());
|
||||
let previous = text.get(..at).and_then(|s| s.chars().next_back());
|
||||
let moved = before.diacritic_horizontal != after.diacritic_horizontal || before.diacritic_vertical != after.diacritic_vertical;
|
||||
moved && (next.is_some_and(is_diacritic) || previous.is_some_and(is_diacritic)) && paint_only(before, after)
|
||||
}
|
||||
|
||||
/// The byte ranges of the harakat in `text[range]`, each run of consecutive harakat as one range.
|
||||
/// The range is normalised as [`crate::edit::style_range`] takes one: its ends clamped to the
|
||||
/// text, each moved back to the start of the character it falls in, and put in order.
|
||||
@@ -194,7 +225,8 @@ pub(crate) fn mark_classes(face: &FontFace) -> Option<ClassDef<'_>> {
|
||||
/// by glyph): repeated glyph ids alone could hide a changed correspondence. A glyph whose character
|
||||
/// lies outside its own shaping cluster of `raw` (from its cluster value up to the next larger one,
|
||||
/// else `end`) gets its cluster's first character instead. A later in-cluster character is kept
|
||||
/// only when the glyph is a GDEF mark and that character is a harakat; otherwise the cluster start
|
||||
/// only when the glyph is a GDEF mark and that character is a harakat or a Hebrew point
|
||||
/// ([`is_diacritic`]); otherwise the cluster start
|
||||
/// is kept (conservative: a mark may miss its colour; a base must never take a mark's). `raw`'s
|
||||
/// clusters are never changed. These are HarfBuzz shaping clusters, which can span more than one
|
||||
/// grapheme (a ligature).
|
||||
@@ -224,8 +256,9 @@ pub(crate) fn own_chars(
|
||||
if c.1 == r.1 {
|
||||
return c.1;
|
||||
}
|
||||
// Later in-cluster character: only a positively identified mark glyph on a harakat.
|
||||
let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_harakat);
|
||||
// Later in-cluster character: only a positively identified mark glyph on a harakat or
|
||||
// a Hebrew point.
|
||||
let mark_char = text.get(c.1 as usize..).and_then(|s| s.chars().next()).is_some_and(is_diacritic);
|
||||
if is_gdef_mark(r.0) && mark_char { c.1 } else { r.1 }
|
||||
})
|
||||
.collect()
|
||||
|
||||
+37
-10
@@ -1053,6 +1053,10 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
|
||||
warichu_scale: _,
|
||||
warichu_align: _,
|
||||
digits,
|
||||
// A mark glyph moves by its own run's values ([`shape_segment`]), so a mark keeps its
|
||||
// letter whatever they are.
|
||||
diacritic_horizontal: _,
|
||||
diacritic_vertical: _,
|
||||
font_height_reference,
|
||||
no_break,
|
||||
language,
|
||||
@@ -1127,7 +1131,8 @@ pub(crate) fn warichu_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
/// character style's name, leading, baseline shift, rotation, Character Alignment, Character
|
||||
/// Direction (text is shaped apart where its bidi level changes), Kashidas, the kerning (each glyph takes its
|
||||
/// run's, see [`shape_segment`]), the space before a line's first character ([`space_before`]),
|
||||
/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features
|
||||
/// Insert Aki ([`aki`]), Tsume ([`tighten`]), the Adjust Diacritic Positions (each mark glyph takes
|
||||
/// its run's), the OpenType features and the East Asian glyph form (each run's apply to its own characters, as features
|
||||
/// over a range of the one buffer) and the tracking, as long as the tracking keeps or drops
|
||||
/// standard ligatures alike ([`crate::features::ligatures_suppressed_by`]).
|
||||
fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
@@ -1186,6 +1191,8 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
warichu_scale: _,
|
||||
warichu_align: _,
|
||||
digits,
|
||||
diacritic_horizontal: _,
|
||||
diacritic_vertical: _,
|
||||
font_height_reference,
|
||||
no_break,
|
||||
language,
|
||||
@@ -1464,11 +1471,21 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
if !manual_ends.is_empty() {
|
||||
return shape_apart(manual_ends, out);
|
||||
}
|
||||
// Harakat styled apart from their letters (paint only): shaped with them, each glyph then
|
||||
// takes its own character's run ([`crate::harakat`]).
|
||||
// Harakat styled apart from their letters (paint only), and harakat and Hebrew points with
|
||||
// diacritic positions of their own: shaped with them, each glyph then takes its own
|
||||
// character's run ([`crate::harakat`]).
|
||||
let mark_boundaries: Vec<usize> = boundaries()
|
||||
.filter(|&b| run_at(b - 1).1 != run_at(b).1 && crate::harakat::paint_only_mark_boundary(text, b, run_at(b - 1).1, run_at(b).1))
|
||||
.filter(|&b| {
|
||||
let (before, after) = (run_at(b - 1).1, run_at(b).1);
|
||||
before != after
|
||||
&& (crate::harakat::paint_only_mark_boundary(text, b, before, after)
|
||||
|| crate::harakat::diacritic_mark_boundary(text, b, before, after))
|
||||
})
|
||||
.collect();
|
||||
// The face's mark classes, read once when any of the segment's runs moves its marks.
|
||||
let moves_marks =
|
||||
runs.get(source_runs.clone()).unwrap_or_default().iter().any(|(_, s)| s.diacritic_horizontal != 0.0 || s.diacritic_vertical != 0.0);
|
||||
let diacritic_classes = if moves_marks { crate::harakat::mark_classes(face) } else { None };
|
||||
// Source run starts are sorted. Reuse their classification when checking cluster splits.
|
||||
let styled_marks = !mark_boundaries.is_empty();
|
||||
let char_level = std::cell::Cell::new(false);
|
||||
@@ -1769,11 +1786,21 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
for (gi, &(gid, cl, xa, xo, yo)) in raw.iter().enumerate() {
|
||||
let cl = cl as usize;
|
||||
let (run, gst) = run_at(cl);
|
||||
// A glyph of a harakat styled apart takes its own character's run (paint only).
|
||||
let run = match chars.get(gi).map(|&c| run_at(c as usize)) {
|
||||
Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => own,
|
||||
_ => run,
|
||||
// A glyph of a harakat styled apart takes its own character's run (paint and diacritic
|
||||
// positions only).
|
||||
let (run, run_st) = match chars.get(gi).map(|&c| run_at(c as usize)) {
|
||||
Some((own, own_st)) if crate::harakat::paint_only(gst, own_st) => (own, own_st),
|
||||
_ => (run, gst),
|
||||
};
|
||||
// A mark glyph (GDEF class 3) moves by its run's Adjust Diacritic Positions, thousandths
|
||||
// of the em it is set in: right and up for positive values.
|
||||
let (mut dx, mut dy) = (xo as f64 * k * hs, -(yo as f64) * k * vs);
|
||||
if let Some(classes) = &diacritic_classes
|
||||
&& classes.get(skrifa::GlyphId::new(gid)) == 3
|
||||
{
|
||||
dx += run_st.diacritic_horizontal / 1000.0 * size * hs;
|
||||
dy -= run_st.diacritic_vertical / 1000.0 * size * vs;
|
||||
}
|
||||
let end = cluster_end(cl);
|
||||
let last_in_cluster = gi + 1 == n || raw[gi + 1].1 as usize != cl;
|
||||
let ch = first_char(cl);
|
||||
@@ -1828,8 +1855,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
run,
|
||||
adv,
|
||||
tracking: tracked,
|
||||
dx: xo as f64 * k * hs,
|
||||
dy: -(yo as f64) * k * vs,
|
||||
dx,
|
||||
dy,
|
||||
kern_shift,
|
||||
aki_shift,
|
||||
aki: aki_in_adv,
|
||||
|
||||
@@ -173,6 +173,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() {
|
||||
b.style_name = a.style_name.clone();
|
||||
b.kerning_before = a.kerning_before;
|
||||
b.features = a.features.clone();
|
||||
b.diacritic_horizontal = a.diacritic_horizontal;
|
||||
b.diacritic_vertical = a.diacritic_vertical;
|
||||
*a == b
|
||||
}
|
||||
|
||||
@@ -226,6 +228,8 @@ fn paint_only_keeps_every_drawing_attribute_and_partial_equality() {
|
||||
field!(tcy_left_right, 1.0, false);
|
||||
field!(standard_vertical_roman, true, false);
|
||||
field!(digits, Digits::Hindi, false);
|
||||
field!(diacritic_horizontal, 100.0, true);
|
||||
field!(diacritic_vertical, -100.0, true);
|
||||
field!(font_height_reference, FontHeightReference::CapHeight, false);
|
||||
field!(no_break, true, false);
|
||||
field!(language, Some("ar".into()), false);
|
||||
@@ -331,6 +335,74 @@ fn feature_only_harakat_boundaries_keep_attachment_and_ownership() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust Horizontal and Vertical Diacritic Position move the mark glyphs (GDEF class 3) by
|
||||
/// thousandths of an em of the glyph size, right and up for positive values, and leave the letters
|
||||
/// where they were. A mark styled apart from its letter takes its own values.
|
||||
#[test]
|
||||
fn diacritic_positions_move_marks_and_keep_letters() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").expect("the test font builds")), 1);
|
||||
let family = crate::test_fonts::lam_alef_family(b"rlig");
|
||||
let face = db.face(family, "Regular").expect("the test face");
|
||||
const WORD: &str = "بَبَبَ";
|
||||
let plain = TextObject::point(Point::ZERO, WORD, style(family));
|
||||
let before = layout(&db, &plain);
|
||||
assert_eq!(before.glyphs.len(), 6, "three bases with their attached marks");
|
||||
let (h, v) = (200.0, 100.0);
|
||||
let moved = (h / 1000.0 * 48.0, -v / 1000.0 * 48.0);
|
||||
// (letters set, marks set): which glyphs move.
|
||||
for (letters, marks) in [(true, true), (false, true), (true, false), (false, false)] {
|
||||
let mut text = plain.clone();
|
||||
for (byte, ch) in WORD.char_indices() {
|
||||
if (is_harakat(ch) && marks) || (!is_harakat(ch) && letters) {
|
||||
crate::edit::style_range(&mut text.runs, byte, byte + ch.len_utf8(), |st| {
|
||||
st.diacritic_horizontal = h;
|
||||
st.diacritic_vertical = v;
|
||||
});
|
||||
}
|
||||
}
|
||||
let after = layout(&db, &text);
|
||||
assert_eq!(after.glyphs.len(), before.glyphs.len(), "letters {letters}, marks {marks}");
|
||||
let mut marks_seen = 0;
|
||||
for (a, b) in before.glyphs.iter().zip(&after.glyphs) {
|
||||
assert_eq!((a.gid, a.byte, a.origin, a.advance), (b.gid, b.byte, b.origin, b.advance), "letters {letters}, marks {marks}");
|
||||
let (ta, tb) = (a.xf.translation(), b.xf.translation());
|
||||
let delta = (tb.x - ta.x, tb.y - ta.y);
|
||||
let mark = is_gdef_mark(&face, a.gid);
|
||||
marks_seen += usize::from(mark);
|
||||
let want = if mark && marks { moved } else { (0.0, 0.0) };
|
||||
assert!(
|
||||
(delta.0 - want.0).abs() < 1e-9 && (delta.1 - want.1).abs() < 1e-9,
|
||||
"letters {letters}, marks {marks}: glyph {} moved {delta:?}, want {want:?}",
|
||||
a.gid
|
||||
);
|
||||
}
|
||||
assert_eq!(marks_seen, 3, "the three fathas are marks");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hebrew points count as diacritics as well as Arabic harakat; Latin accents and letters do not.
|
||||
/// A boundary where only the diacritic positions differ asks for the character-level pass only
|
||||
/// at such a mark.
|
||||
#[test]
|
||||
fn hebrew_points_and_harakat_are_diacritics() {
|
||||
use crate::harakat::{diacritic_mark_boundary, is_diacritic};
|
||||
for c in ['\u{05B8}', '\u{05C1}', '\u{05BC}', '\u{064E}', '\u{0651}'] {
|
||||
assert!(is_diacritic(c), "{c:?}");
|
||||
}
|
||||
for c in ['\u{05D0}', '\u{0628}', '\u{0301}', 'a', '\u{05BE}'] {
|
||||
assert!(!is_diacritic(c), "{c:?}");
|
||||
}
|
||||
let a = style(FAMILY);
|
||||
let b = CharStyle { diacritic_vertical: 150.0, ..a.clone() };
|
||||
assert!(diacritic_mark_boundary("שָׁ", 2, &a, &b), "a Hebrew point styled apart");
|
||||
assert!(diacritic_mark_boundary("بَ", 2, &a, &b), "a fatha styled apart");
|
||||
assert!(!diacritic_mark_boundary("e\u{301}", 1, &a, &b), "a Latin accent keeps its cluster's values");
|
||||
assert!(!diacritic_mark_boundary("بَ", 2, &a, &a), "the same values");
|
||||
let c = CharStyle { size: 20.0, ..b.clone() };
|
||||
assert!(!diacritic_mark_boundary("بَ", 2, &a, &c), "a size change splits the run anyway");
|
||||
}
|
||||
|
||||
/// A range is normalised as `edit::style_range` takes one: clamped, each end moved back to the
|
||||
/// start of its character, put in order. Never a silent empty result for a usable range.
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user