Merge main into feat/revolve-cut-caps

This commit is contained in:
dotCooCoo
2026-11-15 17:49:31 -08:00
307 changed files with 21418 additions and 2715 deletions
Generated
+153 -18
View File
@@ -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",
@@ -1010,6 +1016,14 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
dependencies = [
"flate2",
]
[[package]]
name = "craft-i18n"
version = "0.1.0"
@@ -1033,6 +1047,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 +1134,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 +1160,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"
@@ -1156,7 +1220,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
dependencies = [
"flate2",
"serde",
@@ -1203,6 +1267,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 +1788,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 +2836,7 @@ dependencies = [
"moxcms",
"num-traits",
"png 0.18.1",
"qoi",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
@@ -3200,6 +3290,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 +3495,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 +4467,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 +5852,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 +6670,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 +6683,6 @@ dependencies = [
"log",
"proptest",
"rayon",
"roxmltree 0.21.2",
"rustix 1.1.6",
"ruzstd",
"same-file",
@@ -6625,6 +6749,7 @@ dependencies = [
name = "vectorcraft-format"
version = "0.24.1"
dependencies = [
"craft-gzip",
"craft-vectorcraft-format",
"flate2",
"proptest",
@@ -6734,6 +6859,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 +6870,6 @@ dependencies = [
"md-5",
"objc2-core-foundation",
"objc2-core-graphics",
"roxmltree 0.21.2",
"serde",
"serde_json",
"sha2",
@@ -6785,16 +6910,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 +7042,7 @@ dependencies = [
name = "vectorcraft-trace"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"image",
"kurbo 0.13.1",
"serde",
@@ -8371,6 +8497,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"
+8 -2
View File
@@ -21,7 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
@@ -30,9 +31,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" }
+3 -3
View File
@@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
@@ -102,14 +102,14 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
| Indonesian | `id` | none | 0% |
| Indonesian | `id` | 6,947 catalog rows; status and error messages partial | most dialogs and tooltips |
| Japanese | `ja` | full | 100% |
| German | `de` | full | 98% |
| Korean | `ko` | full | 100% |
| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% |
| Vietnamese | `vi` | full | 100% |
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian, Georgian, Dutch, Danish and Turkish (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
The Georgian catalog has had a native speaker's review; no other catalog has. Details: [localization-parity.md](docs/localization-parity.md).
## Upcoming
+2 -1
View File
@@ -238,10 +238,11 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
+302 -50
View File
@@ -155,8 +155,18 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
copied_file_within(paths, mimes, MAX_BYTES)
}
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
#[cfg_attr(windows, allow(dead_code))]
fn takes_files(mimes: &[&'static str]) -> bool {
mimes.iter().any(|&m| m != TEXT)
}
/// [`copied_file`] with a file of more than `limit` bytes skipped.
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
// A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at.
if paths.len() > MAX_URIS {
return None;
}
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -197,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>
(data.len() <= limit).then_some(data)
}
/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports
/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and
/// when the copy comes to more than `limit` bytes.
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<Vec<u8>>) -> Option<Vec<u8>> {
size.filter(|&n| n > 0 && n <= limit)?;
copy().filter(|data| data.len() <= limit)
}
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
#[cfg_attr(not(windows), allow(dead_code))]
fn utf8_most(utf16: usize) -> usize {
utf16.div_ceil(2).saturating_mul(3)
}
/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a
/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit`
/// files. Counting stops at the first name past `limit`. A block too short for its header, or
/// whose names would start past its end, is not within.
#[cfg_attr(not(windows), allow(dead_code))]
fn drop_files_within(block: &[u8], limit: usize) -> bool {
let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?));
let (Some(start), Some(wide)) = (field(0), field(16)) else {
return false;
};
let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else {
return false;
};
let (mut count, mut in_name) = (0usize, false);
for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) {
if unit.iter().all(|&b| b == 0) {
if !in_name {
break;
}
in_name = false;
} else if !in_name {
in_name = true;
count += 1;
if count > limit {
return false;
}
}
}
true
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
@@ -278,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
use std::num::{NonZeroU32, NonZeroUsize};
use clipboard_win::{formats, options::NoClear, raw};
use super::{
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png,
dib_image, drop_files_within, png_flavour, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -370,8 +428,11 @@ mod win {
let mut files = vec![];
{
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
// None copied when the clipboard holds no file list.
let _ = raw::get_file_list_path(&mut files);
// None copied when the clipboard holds no file list, or one of more than MAX_BYTES
// or MAX_URIS files: the list is counted before its names are copied.
if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) {
let _ = raw::get_file_list_path(&mut files);
}
}
// The files are read with the clipboard closed again, not keeping other apps waiting.
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
@@ -390,44 +451,64 @@ mod win {
}
}
/// Read the first registered format of `mime` the clipboard holds into `data`.
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
data.clear();
raw::get_vec(id, data).is_ok() && !data.is_empty()
/// The size the clipboard reports for format `id`, while it is open.
fn size_of(id: u32) -> Option<usize> {
raw::size(id).map(NonZeroUsize::get)
}
/// The data of format `id`, while the clipboard is open, copied only when its size is at most
/// `limit` bytes ([`copy_within`]).
fn copy_registered(id: u32, limit: usize) -> Option<Vec<u8>> {
copy_within(size_of(id), limit, || {
let mut data = vec![];
raw::get_vec(id, &mut data).ok()?;
Some(data)
})
}
/// The first registered format of `mime` the clipboard holds that is not empty and at most
/// [`MAX_BYTES`]; a larger one is skipped and the next tried.
fn read_registered(mime: &str) -> Option<Vec<u8>> {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
}
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
/// `size` gives each format's size before `get` copies it, and a format of more than
/// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried.
pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option<usize>, mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect();
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
}
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
/// the work that comes back decodes each captured format in preference order.
/// the work that comes back decodes each captured format in preference order. Text whose
/// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read.
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
let mut data = vec![];
let mime = match mime {
BITMAP if read_registered(PNG, &mut data) => PNG,
BITMAP => {
return read_dibs(|id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
let (mime, mut data) = match mime {
BITMAP => match read_registered(PNG) {
Some(png) => (PNG, png),
None => {
return read_dibs(size_of, |id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
},
TEXT => {
raw::get_string(&mut data).ok()?;
TEXT
let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || {
let mut text = vec![];
raw::get_string(&mut text).ok()?;
Some(text)
})?;
(TEXT, text)
}
m if read_registered(m, &mut data) => m,
_ => return None,
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
if mime == SVG
@@ -727,7 +808,7 @@ mod portable {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, takes_files, text_of};
/// What our last write put on the clipboard.
#[derive(Clone)]
@@ -741,7 +822,7 @@ mod portable {
}
/// A read of arboard's clipboard.
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Request {
Text,
Image,
@@ -813,6 +894,19 @@ mod portable {
}
}
/// Whether a paste of one of `mimes` can take what `cb` holds: text that is not empty when one
/// of `mimes` is text (`text` reads it), else files copied in a file manager when one of `mimes`
/// is not text (`files` reads the list). The list is read only when the text doesn't do, and no
/// copied file is opened: Paste checks the files themselves.
fn arboard_has<B>(
mimes: &[&'static str],
cb: &mut B,
text: impl FnOnce(&mut B) -> Result<String, String>,
files: impl FnOnce(&mut B) -> Vec<PathBuf>,
) -> bool {
(mimes.contains(&TEXT) && text(cb).is_ok_and(|t| !t.is_empty())) || (takes_files(mimes) && !files(cb).is_empty())
}
/// `request` read on `reads`' worker, waiting `wait` at most.
#[cfg(test)]
fn read_within(reads: &mut super::loads::Loads<Request, Answer>, request: Request, wait: Duration) -> Answer {
@@ -1441,10 +1535,11 @@ mod portable {
read
}
/// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
/// core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
/// Text or files copied in a file manager (their list read, no file opened:
/// [`arboard_has`]), on macOS vector art or a bitmap (by the pasteboard's types), and on the
/// Wayland core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
/// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it):
/// the paste keys take it, the menu item waits for text.
/// the paste keys take it, the menu item waits for text or copied files.
fn has(&mut self, mimes: &[&'static str]) -> bool {
#[cfg(target_os = "macos")]
if super::mac::has(mimes) {
@@ -1455,7 +1550,7 @@ mod portable {
if let Backend::Wayland(wl) = cb {
return wl.has(mimes);
}
mimes.contains(&TEXT) && cb.get_text().is_ok_and(|t| !t.is_empty())
arboard_has(mimes, cb, Backend::get_text, Backend::file_list)
}
}
@@ -1619,6 +1714,40 @@ mod portable {
assert!(Answer::Text(Ok("art.svg".into())).files().is_empty());
}
#[test]
fn paste_is_available_for_files_copied_in_a_file_manager() {
use vectorcraft_engine::cmd::clipboard::{PASTE_ORDER, SVG};
/// What the clipboard holds, and which reads [`arboard_has`] made.
struct Held {
text: Option<String>,
files: Vec<PathBuf>,
reads: Vec<Request>,
}
fn has(mimes: &[&'static str], text: Option<&str>, files: &[&str]) -> (bool, Vec<Request>) {
let mut held = Held { text: text.map(String::from), files: files.iter().map(PathBuf::from).collect(), reads: vec![] };
let text = |h: &mut Held| {
h.reads.push(Request::Text);
h.text.clone().ok_or_else(|| "no text".to_string())
};
let files = |h: &mut Held| {
h.reads.push(Request::Files);
h.files.clone()
};
let has = arboard_has(mimes, &mut held, text, files);
(has, held.reads)
}
// Files a file manager copied, with no text: the Paste menu item is available.
assert_eq!(has(&PASTE_ORDER, None, &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
assert_eq!(has(&PASTE_ORDER, Some(""), &["/tmp/art.svg"]), (true, vec![Request::Text, Request::Files]));
assert_eq!(has(&[SVG], None, &["/tmp/art.svg"]), (true, vec![Request::Files]));
// Text does, and the list is not read.
assert_eq!(has(&PASTE_ORDER, Some("hello"), &[]), (true, vec![Request::Text]));
// An empty list and no text: nothing to paste.
assert_eq!(has(&PASTE_ORDER, None, &[]), (false, vec![Request::Text, Request::Files]));
// A paste of text alone can't take copied files, and their list is not read.
assert_eq!(has(&[TEXT], None, &["/tmp/art.svg"]), (false, vec![Request::Text]));
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
@@ -1925,7 +2054,7 @@ mod wayland {
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
@@ -2016,11 +2145,6 @@ mod wayland {
Some(first)
}
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
fn takes_files(mimes: &[&'static str]) -> bool {
mimes.iter().any(|&m| m != TEXT)
}
/// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case.
fn file_list_type(offered: &[String]) -> Option<&str> {
FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str)
@@ -3092,7 +3216,7 @@ mod mac {
use objc2_app_kit::NSPasteboard;
use objc2_foundation::{NSArray, NSString};
use super::{Flavour, pasteboard_types};
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
@@ -3103,13 +3227,16 @@ mod mac {
})
}
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is
/// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger
/// type is skipped and the next tried.
pub fn read(mime: &str) -> Option<Flavour> {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
(!data.is_empty()).then_some(Flavour { mime, data })
let held = pasteboard.dataForType(&NSString::from_str(t))?;
let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?;
Some(Flavour { mime, data })
})
})
}
@@ -3296,6 +3423,102 @@ mod tests {
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
}
/// A copied file list of more than 1,024 files pastes none, before any file is looked at,
/// wherever the list came from; 1,024 files paste the first that is art.
#[test]
fn a_copied_file_list_longer_than_the_limit_pastes_no_file() {
let d = dir("many");
let art = d.path().join("art.svg");
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::<Vec<_>>();
let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat();
assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// The art first: no file is opened past the count.
let first = [vec![art.clone()], missing(MAX_URIS)].concat();
assert!(copied_file(first, &PASTE_ORDER).is_none());
assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none());
}
/// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit,
/// and the copy is not asked for otherwise.
#[test]
fn clipboard_data_is_copied_only_when_its_size_fits() {
let copy = |size: Option<usize>, got: usize| {
let mut asked = false;
let data = copy_within(size, 8, || {
asked = true;
Some(vec![1; got])
});
(data.map(|d| d.len()), asked)
};
assert_eq!(copy(Some(8), 8), (Some(8), true));
assert_eq!(copy(Some(1), 1), (Some(1), true));
for size in [None, Some(0), Some(9), Some(usize::MAX)] {
assert_eq!(copy(size, 1), (None, false), "{size:?}");
}
// Data that comes to more than the limit after all is refused.
assert_eq!(copy(Some(8), 9), (None, true));
assert_eq!(MAX_BYTES, 64 << 20);
}
/// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before
/// the text is converted: a block that could pass the limit as UTF-8 is not read.
#[test]
fn text_is_bounded_by_what_its_utf8_could_come_to() {
for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] {
let utf16 = text.encode_utf16().count() * 2;
assert!(utf8_most(utf16) >= text.len(), "{text:?}");
}
// Every code unit at 3 bytes of UTF-8: the bound is exact.
assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len());
let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some();
assert!(copied(MAX_BYTES / 3 * 2));
assert!(!copied(MAX_BYTES / 3 * 2 + 2));
assert!(!copied(MAX_BYTES));
assert_eq!(utf8_most(usize::MAX), usize::MAX);
}
/// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one
/// byte a character, each ended by a NUL, and one more NUL.
fn drop_files(names: &[&str], wide: bool) -> Vec<u8> {
let mut block = vec![];
block.extend(20u32.to_le_bytes());
block.extend([0u8; 12]);
block.extend(u32::from(wide).to_le_bytes());
for name in names.iter().copied().chain([""]) {
for unit in name.encode_utf16().chain([0]) {
if wide {
block.extend(unit.to_le_bytes());
} else {
block.push(unit as u8);
}
}
}
block
}
#[test]
fn a_windows_file_list_is_counted_before_its_names_are_read() {
let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::<Vec<_>>();
for wide in [true, false] {
let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::<Vec<_>>(), wide);
assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}");
assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}");
assert!(drop_files_within(&list(0), MAX_URIS), "{wide}");
// Names past the list's closing NUL are not counted.
let mut ended = list(2);
ended.extend(list(MAX_URIS + 1).get(20..).unwrap());
assert!(drop_files_within(&ended, 2), "{wide}");
// A list cut short counts the names it holds.
assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}");
}
// A header cut short, or names that would start past the block's end.
assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS));
let mut past = drop_files(&["a"], true);
past[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(!drop_files_within(&past, MAX_URIS));
}
#[test]
fn gnome_files_list_names_its_files_after_copy_or_cut() {
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
@@ -3349,19 +3572,48 @@ mod tests {
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
let mut captured = Vec::new();
let read = win::read_dibs(|id| {
captured.push(id);
match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
}
})
let get = |id: u32| match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
};
let read = win::read_dibs(
|id| get(id).map(|d| d.len()),
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
let flavour = read.flavour().unwrap();
assert_eq!(flavour.mime, PNG);
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
// A bitmap larger than the limit is not copied, and the other one still pastes.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
// Each format has the limit to itself: a first one at the limit that doesn't decode
// leaves the second to paste.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
}
#[test]
+47 -8
View File
@@ -1,7 +1,8 @@
//! VectorCraft desktop app.
//!
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
//! [--in-window-menus] [--new-instance] [--safe-mode] [--present-mode <mode>] [--frame-latency <frames>] [--] [files…]`,
//! `vectorcraft --version`, `vectorcraft --help` (or `-h`)
//!
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
//! a file.
@@ -19,6 +20,9 @@
//! `--automation-write-root` (or `VECTORCRAFT_AUTOMATION_READ_ROOT` / `_WRITE_ROOT`) confine the
//! files its requests read and write (`vectorcraft_engine::file_access`); the person at the
//! keyboard isn't confined.
//!
//! `--present-mode` and `--frame-latency` (or `VECTORCRAFT_PRESENT_MODE` / `_FRAME_LATENCY`) change
//! how the window's frames reach the display (`presentation`).
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod automation_args;
@@ -59,6 +63,7 @@ mod portal_request;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
mod portal_save;
mod prefs_dir;
mod presentation;
mod printing;
#[cfg(not(any(target_os = "macos", windows)))]
mod quit_windows;
@@ -158,6 +163,14 @@ Options:
--safe-mode Start without plug-ins: none loads or runs until
VectorCraft starts normally (Help › Safe Mode); the
files open in a new window, as with --new-instance
--present-mode <mode> How frames reach the display: fifo (vsync),
autovsync (the default; relaxed vsync where the
driver offers it) or novsync
(or VECTORCRAFT_PRESENT_MODE)
--frame-latency <frames> Frames the display may queue, 1 to 3 (the default
is 1) (or VECTORCRAFT_FRAME_LATENCY); with either
one set, the files open in a new window, as with
--new-instance
--version Print the version and exit
-h, --help Print this help and exit
-- Treat every argument after it as a file
@@ -177,13 +190,16 @@ struct CommandLine {
safe_mode: bool,
}
/// Reads the arguments after the program name. The automation roots and the control port go into
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
/// Reads the arguments after the program name. The automation roots, the control port and the
/// presentation overrides (with `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY` filling
/// what the flags leave unset) go into `roots_args`, `control` and `presentation`. `Err` is the exit code
/// when the process ends here: `--version` and `--help` print and succeed; a bad automation or
/// presentation option or an unknown option prints an error and fails.
fn read_command_line(
mut args: impl Iterator<Item = String>,
control: &mut automation_args::ControlArg,
roots_args: &mut automation_args::AutomationArgs,
presentation: &mut presentation::Overrides,
) -> Result<CommandLine, std::process::ExitCode> {
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
@@ -196,7 +212,11 @@ fn read_command_line(
files.extend(args.by_ref());
break;
}
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
match roots_args
.consume(&a, &mut args)
.and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) })
.and_then(|taken| if taken { Ok(true) } else { presentation.consume(&a, &mut args) })
{
Ok(true) => continue,
Ok(false) => {}
Err(e) => {
@@ -235,6 +255,14 @@ fn read_command_line(
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
return Err(std::process::ExitCode::FAILURE);
}
// After the arguments: the flags, `--version` and `--help` win over a bad environment value.
match presentation.with_env(std::env::var_os("VECTORCRAFT_PRESENT_MODE"), std::env::var_os("VECTORCRAFT_FRAME_LATENCY")) {
Ok(overrides) => *presentation = overrides,
Err(e) => {
eprintln!("vectorcraft: {e}");
return Err(std::process::ExitCode::FAILURE);
}
}
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
}
@@ -253,8 +281,9 @@ fn main() -> std::process::ExitCode {
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
let mut roots_args =
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
let mut presentation = presentation::Overrides::default();
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args, &mut presentation) {
Ok(command_line) => command_line,
Err(code) => return code,
};
@@ -275,7 +304,8 @@ fn main() -> std::process::ExitCode {
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
// the log file is attached: a launch that hands its files over leaves the running app's log be.
#[cfg(not(target_os = "macos"))]
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
// A launch that sets the presentation runs as its own app: a running app keeps its own surface.
match single_instance::start(control_port.is_some(), new_instance || presentation.is_set(), safe_mode_flag, &files) {
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
single_instance::Start::Running(primary) => single_instance::hold(primary),
}
@@ -427,7 +457,10 @@ fn main() -> std::process::ExitCode {
let mut options = options;
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
// composites it, so the window answers the pointer a frame sooner (#444).
options.wgpu_options.surface = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
@@ -458,6 +491,10 @@ fn main() -> std::process::ExitCode {
}
options
};
#[cfg(not(feature = "wgpu"))]
if presentation != presentation::Overrides::default() {
log::warn!("--present-mode and --frame-latency set the wgpu renderer's window surface: ignored without it");
}
#[cfg(feature = "wgpu")]
gpu::watch_panics();
#[cfg(feature = "wgpu")]
@@ -498,6 +535,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
+8
View File
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Metadata Templates") {
session.attach_metadata_templates_dir(dir);
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
+242
View File
@@ -0,0 +1,242 @@
//! `--present-mode <mode>` (or `VECTORCRAFT_PRESENT_MODE`) and `--frame-latency <frames>` (or
//! `VECTORCRAFT_FRAME_LATENCY`) set how the window's frames reach the display for one launch. The
//! modes are `fifo` (vsync), `autovsync` (the default: wgpu picks relaxed vsync, which tears a late
//! frame, else vsync, by what the driver offers) and `novsync` (wgpu picks Immediate, else Mailbox,
//! else Fifo). A mode the driver may not offer is never requested. The latency is the number of
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
//! overrides its variable; a value that isn't one of these stops the app with a message, as
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
//! The surface the app asks for is logged at start-up.
use std::ffi::OsString;
/// A present mode the command line or the environment can ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
Fifo,
AutoVsync,
NoVsync,
}
/// The present mode and frame latency this launch asked for (`None`: the app's own setting).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Overrides {
pub mode: Option<Mode>,
pub latency: Option<u32>,
}
/// A present mode named by `name` (the flag or the variable): `fifo`, `autovsync` or `novsync`, any case.
fn mode(name: &str, value: Option<&str>) -> Result<Mode, String> {
let need = format!("{name} needs fifo, autovsync or novsync");
let Some(v) = value else { return Err(need) };
match v.trim().to_ascii_lowercase().as_str() {
"fifo" => Ok(Mode::Fifo),
"autovsync" => Ok(Mode::AutoVsync),
"novsync" => Ok(Mode::NoVsync),
_ => Err(format!("{need}, not `{v}`")),
}
}
/// A frame latency named by `name`: 1, 2 or 3.
fn latency(name: &str, value: Option<&str>) -> Result<u32, String> {
let need = format!("{name} needs 1, 2 or 3 frames");
let Some(v) = value else { return Err(need) };
v.trim().parse().ok().filter(|n| (1..=3).contains(n)).ok_or(format!("{need}, not `{v}`"))
}
/// The value of `--flag <value>` or `--flag=<value>` when `arg` is that flag; `None` when it isn't.
fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) -> Option<Option<String>> {
match arg.strip_prefix(flag)? {
"" => Some(args.next()),
rest => rest.strip_prefix('=').map(|v| Some(v.to_owned())),
}
}
impl Overrides {
/// Whether a flag or a variable set the present mode or the frame latency.
pub fn is_set(&self) -> bool {
*self != Self::default()
}
/// Returns whether this argument is `--present-mode` or `--frame-latency`. The next argument is
/// its value whatever it is, as with `--control`.
pub fn consume(&mut self, arg: &str, args: &mut impl Iterator<Item = String>) -> Result<bool, String> {
if let Some(value) = flag_value("--present-mode", arg, args) {
if self.mode.is_some() {
return Err("--present-mode given twice".into());
}
self.mode = Some(mode("--present-mode", value.as_deref())?);
return Ok(true);
}
if let Some(value) = flag_value("--frame-latency", arg, args) {
if self.latency.is_some() {
return Err("--frame-latency given twice".into());
}
self.latency = Some(latency("--frame-latency", value.as_deref())?);
return Ok(true);
}
Ok(false)
}
/// Fills what the flags left unset from `VECTORCRAFT_PRESENT_MODE` and `VECTORCRAFT_FRAME_LATENCY`.
/// Unset or empty is no override; a variable is not read when its flag was given.
pub fn with_env(self, mode_var: Option<OsString>, latency_var: Option<OsString>) -> Result<Self, String> {
let set = |v: Option<OsString>| v.filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned());
let mode = match (self.mode, set(mode_var)) {
(Some(m), _) => Some(m),
(None, Some(v)) => Some(mode("VECTORCRAFT_PRESENT_MODE", Some(&v))?),
(None, None) => None,
};
let latency = match (self.latency, set(latency_var)) {
(Some(n), _) => Some(n),
(None, Some(v)) => Some(latency("VECTORCRAFT_FRAME_LATENCY", Some(&v))?),
(None, None) => None,
};
Ok(Self { mode, latency })
}
/// `surface` with the overrides applied.
#[cfg(feature = "wgpu")]
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
use eframe::wgpu::PresentMode;
let present_mode = match self.mode {
Some(Mode::Fifo) => PresentMode::Fifo,
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
None => surface.present_mode,
};
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
}
}
/// The present mode and frame latency `surface` asks for, for the start-up log:
/// "autovsync, frame latency 1", with "(override)"
/// after a value a flag or variable set.
#[cfg(feature = "wgpu")]
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
use eframe::wgpu::PresentMode;
let mode = match surface.present_mode {
PresentMode::AutoVsync => "autovsync",
PresentMode::AutoNoVsync => "novsync",
PresentMode::Fifo => "fifo",
PresentMode::FifoRelaxed => "fiforelaxed",
PresentMode::Immediate => "immediate",
PresentMode::Mailbox => "mailbox",
};
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
let tag = |set: bool| if set { " (override)" } else { "" };
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(args: &[&str]) -> Result<Overrides, String> {
let mut overrides = Overrides::default();
let mut args = args.iter().map(|a| a.to_string());
while let Some(a) = args.next() {
assert!(overrides.consume(&a, &mut args)?, "{a}");
}
Ok(overrides)
}
#[test]
fn flags_take_the_three_modes_and_latencies_from_1_to_3() {
assert_eq!(parse(&[]), Ok(Overrides::default()));
assert_eq!(parse(&["--present-mode", "fifo"]).map(|o| o.mode), Ok(Some(Mode::Fifo)));
assert_eq!(parse(&["--present-mode=AutoVsync"]).map(|o| o.mode), Ok(Some(Mode::AutoVsync)));
assert_eq!(parse(&["--present-mode", " novsync "]).map(|o| o.mode), Ok(Some(Mode::NoVsync)));
for n in 1..=3 {
assert_eq!(parse(&["--frame-latency", &n.to_string()]).map(|o| o.latency), Ok(Some(n)));
}
assert_eq!(parse(&["--frame-latency=2", "--present-mode", "fifo"]), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
}
#[test]
fn bad_flag_values_are_errors() {
let modes = "--present-mode needs fifo, autovsync or novsync";
assert_eq!(parse(&["--present-mode"]), Err(modes.into()));
for bad in ["mailbox", "immediate", "vsync", "fast", ""] {
assert_eq!(parse(&["--present-mode", bad]), Err(format!("{modes}, not `{bad}`")));
assert_eq!(parse(&[&format!("--present-mode={bad}")]), Err(format!("{modes}, not `{bad}`")));
}
assert_eq!(parse(&["--present-mode", "--frame-latency"]), Err(format!("{modes}, not `--frame-latency`")));
let frames = "--frame-latency needs 1, 2 or 3 frames";
assert_eq!(parse(&["--frame-latency"]), Err(frames.into()));
for bad in ["0", "4", "-1", "one", "1.5", "99999999999", ""] {
assert_eq!(parse(&["--frame-latency", bad]), Err(format!("{frames}, not `{bad}`")));
}
assert_eq!(parse(&["--present-mode", "fifo", "--present-mode=novsync"]), Err("--present-mode given twice".into()));
assert_eq!(parse(&["--frame-latency=1", "--frame-latency", "2"]), Err("--frame-latency given twice".into()));
}
#[test]
fn other_arguments_are_not_presentation_flags() {
let mut overrides = Overrides::default();
let mut args = ["fifo".to_owned()].into_iter();
for other in ["--present-modes", "--present", "--frame-latency-2", "drawing.svg", "--control"] {
assert!(!overrides.consume(other, &mut args).unwrap(), "{other}");
}
assert_eq!(args.next().as_deref(), Some("fifo"));
assert_eq!(overrides, Overrides::default());
}
#[test]
fn variables_fill_what_the_flags_leave_unset_and_bad_values_are_errors() {
let none = Overrides::default();
assert_eq!(none.with_env(None, None), Ok(none));
assert_eq!(none.with_env(Some("".into()), Some("".into())), Ok(none));
assert_eq!(none.with_env(Some("FIFO".into()), Some("2".into())), Ok(Overrides { mode: Some(Mode::Fifo), latency: Some(2) }));
assert_eq!(
none.with_env(Some("mailbox".into()), None),
Err("VECTORCRAFT_PRESENT_MODE needs fifo, autovsync or novsync, not `mailbox`".into())
);
assert_eq!(none.with_env(None, Some("0".into())), Err("VECTORCRAFT_FRAME_LATENCY needs 1, 2 or 3 frames, not `0`".into()));
// A flag wins, and its variable is not read, so a bad value there doesn't stop the app.
let flags = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
assert_eq!(flags.with_env(Some("bad".into()), Some("9".into())), Ok(flags));
let mode_only = Overrides { mode: Some(Mode::AutoVsync), latency: None };
assert_eq!(mode_only.with_env(Some("bad".into()), Some("1".into())), Ok(Overrides { mode: Some(Mode::AutoVsync), latency: Some(1) }));
// Either value set makes the launch run as its own app.
assert!(!none.is_set());
assert!(mode_only.is_set());
assert!(Overrides { mode: None, latency: Some(1) }.is_set());
}
/// `--help` states the app's own surface as the default, so it changes with it.
#[cfg(feature = "wgpu")]
#[test]
fn the_usage_names_the_app_surface_as_the_default() {
let app = eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY;
let usage = crate::USAGE.split_whitespace().collect::<Vec<_>>().join(" ");
assert_eq!(app.present_mode, eframe::wgpu::PresentMode::AutoVsync, "the usage calls autovsync the default");
assert!(usage.contains("autovsync (the default"), "{usage}");
let Some(frames) = app.desired_maximum_frame_latency else { panic!("the usage gives a default frame latency") };
assert!(usage.contains(&format!("(the default is {frames})")), "{usage}");
}
#[cfg(feature = "wgpu")]
#[test]
fn overrides_change_only_what_they_set_on_the_app_surface() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
// No override: the surface the app asks for is unchanged.
assert_eq!(Overrides::default().apply(app), app);
let latency = Overrides { mode: None, latency: Some(2) };
let s = latency.apply(app);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
let s = fifo.apply(app);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
let s = novsync.apply(app);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
}
}
+37 -1
View File
@@ -52,7 +52,17 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
for flag in [
"--control",
"--automation-read-root",
"--automation-write-root",
"--in-window-menus",
"--safe-mode",
"--present-mode",
"--frame-latency",
"--version",
"--help",
] {
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
}
// Headless work is the CLI's: the usage says where to go.
@@ -73,6 +83,32 @@ fn help_wins_over_a_bad_control_port_variable() {
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
}
/// A bad presentation variable stops the app with a message before it starts; `--help` and the
/// matching flag win over it. A run that gets past it stops at the control port `run` makes fail.
#[test]
fn a_bad_presentation_variable_is_an_error_unless_help_or_its_flag_is_given() {
for (var, value, need) in [
("VECTORCRAFT_FRAME_LATENCY", "0", "needs 1, 2 or 3 frames, not `0`"),
("VECTORCRAFT_PRESENT_MODE", "mailbox", "needs fifo, autovsync or novsync, not `mailbox`"),
] {
let out = run(&[], &[(var, value)]);
assert!(!out.status.success(), "{var}");
assert_eq!(String::from_utf8(out.stderr).unwrap(), format!("vectorcraft: {var} {need}\n"));
prints_usage(&["--help"], &[(var, value)]);
}
for (args, env) in [
(&["--frame-latency", "2"][..], ("VECTORCRAFT_FRAME_LATENCY", "0")),
(&["--present-mode=fifo"], ("VECTORCRAFT_PRESENT_MODE", "mailbox")),
(&[], ("VECTORCRAFT_FRAME_LATENCY", "3")),
] {
let stderr = String::from_utf8(run(args, &[env]).stderr).unwrap();
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains(env.0), "{args:?}: {stderr}");
}
let out = run(&["--frame-latency", "4"], &[]);
assert!(!out.status.success());
assert_eq!(String::from_utf8(out.stderr).unwrap(), "vectorcraft: --frame-latency needs 1, 2 or 3 frames, not `4`\n");
}
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
/// plug-ins; a later `--help` still wins.
#[test]
+1 -1
View File
@@ -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
+21 -6
View File
@@ -1,4 +1,4 @@
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and a reader on
//! CAD interchange: a DXF writer (versions R12 to 2018) on `craft_dxf::drawing` and a reader on
//! `craft_dxf::model`, and an HP-GL/2 plot file reader and writer.
//!
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
@@ -15,7 +15,7 @@
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
//!
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
//! - `writer`: group codes, handles and the file's sections, tables and objects.
//! - The ASCII file around those entities is written by `craft_dxf::drawing`.
//! - `scene`: the document walk that turns objects into entities.
//! - `import`: the reader, entities to art, blocks to symbols.
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
@@ -24,7 +24,6 @@ mod aci;
pub mod hpgl;
pub mod import;
mod scene;
mod writer;
use vectorcraft_doc::{Document, Unit};
use vectorcraft_geom::Rect;
@@ -136,11 +135,27 @@ impl DxfVersion {
self >= Self::R2004
}
/// Text is UTF-8 (earlier versions escape what isn't ASCII as `\U+XXXX`).
fn utf8(self) -> bool {
pub fn utf8(self) -> bool {
self >= Self::R2007
}
}
impl From<DxfVersion> for craft_dxf::drawing::Format {
fn from(v: DxfVersion) -> Self {
match v {
DxfVersion::R12 => Self::R12,
DxfVersion::R13 => Self::R13,
DxfVersion::R14 => Self::R14,
DxfVersion::R2000 => Self::R2000,
DxfVersion::R2004 => Self::R2004,
DxfVersion::R2007 => Self::R2007,
DxfVersion::R2010 => Self::R2010,
DxfVersion::R2013 => Self::R2013,
DxfVersion::R2018 => Self::R2018,
}
}
}
/// How many colours entities may use: indexed colours of the 256-colour palette, or true colour
/// (with the nearest index for apps that read only the index).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -429,8 +444,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
return Err("the export region is not finite".into());
}
// Symbols' art is placed without clipping, as the scene places it.
let baked =
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers);
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
}
+4 -4
View File
@@ -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,
+20
View File
@@ -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());
}
}
-674
View File
@@ -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");
}
}
+448
View File
@@ -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
+13 -12
View File
@@ -323,34 +323,31 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
let walk = ArtWalk::open();
let _walk = ArtWalk::open();
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
// while a group (including a clipping group) is selected as one object. Repeatedly
// searching the full tree for each hit made a stack of n overlapping paths O(n^2).
// Isolation and Edit Contents change where selection groups begin; keep the original
// traversal for those cases rather than change their Select Behind semantics.
if opt.scope.is_some() {
// Malformed files may contain non-layer roots; let the general traversal handle them.
if opt.scope.is_some() || doc.layers.iter().any(|l| !l.is_layer()) {
return objects_at_repeated(doc, p, opt, scope);
}
let mut tops = Vec::new();
let mut seen = HashSet::new();
let symbols = doc.symbol_boxes();
for layer in doc.layers.iter().rev() {
// Malformed files may contain non-layer roots; let the general traversal handle them.
if !layer.is_layer() {
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
}
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
}
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
// An envelope in Edit Contents may expose objects *within* a top-level group.
// The repeated traversal handles that mixed hierarchy precisely, with the whole
// limit of symbol art to walk.
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
// The repeated traversal handles that mixed hierarchy precisely. The objects found
// so far lie above the envelope and stay first; the repeated traversal finds the
// rest with what is left of the limit of symbol art to walk.
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
break;
}
}
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
@@ -414,7 +411,11 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
/// The general selection order also handles isolation and nested Edit Contents.
fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
let mut tops: Vec<NodeId> = vec![];
objects_at_repeated_after(doc, p, opt, scope, vec![])
}
/// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found.
fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
// Each round leaves out the objects found so far (and everything inside them).
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
+70
View File
@@ -1452,6 +1452,76 @@ fn objects_at_edit_contents_uses_general_order() {
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
}
/// Select Behind keeps one limit of symbol art to walk when it falls back to the general
/// traversal, for an envelope in Edit Contents and for a root that is not a layer: the fallback
/// walks no more art than what the first pass left, and keeps what the first pass found.
#[test]
fn select_behind_keeps_one_art_limit_when_it_falls_back() {
// 60 instances of `Clipped` with the rectangle hidden, which a click at (150, 50) walks the art
// of and misses: each walk takes 3 objects of the 100.
let stack = |d: &mut Document, count: usize| {
let l = d.layers[0].id;
for _ in 0..count {
let inst = instance_of(d, "Clipped");
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
}
};
// An envelope in Edit Contents at the bottom of the layer, its contents under (150, 50).
let envelope = |d: &mut Document| {
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
let (a, b) = (d.alloc_id(), d.alloc_id());
let e = Node::new(
d.alloc_id(),
NodeKind::Envelope {
content: vec![inner(a), inner(b)],
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }),
fidelity: 100.0,
editing: true,
options: Default::default(),
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
},
);
let l = d.layers[0].id;
d.insert(Some(l), 0, e).unwrap();
(a, b)
};
let p = Point::new(150.0, 50.0);
let mut d = Document::new(600.0, 400.0);
clipped_symbol(&mut d, false);
let (a, b) = envelope(&mut d);
stack(&mut d, 60);
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
assert_eq!(behind, vec![b, a]);
assert!(arts <= 34, "envelope in Edit Contents: {arts} instances' art walked");
// An instance that the first pass hits by its art, the limit then used up, stays in the list:
// `Shown` is `Clipped` with its rectangle shown, below 32 instances of `Clipped`.
let mut d = Document::new(600.0, 400.0);
clipped_symbol(&mut d, false);
let (a, b) = envelope(&mut d);
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
group_symbol(&mut d, "Shown", vec![Arc::new(clip)]);
let hit = instance_of(&mut d, "Shown");
let hit_id = hit.id;
let l = d.layers[0].id;
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
stack(&mut d, 32);
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
assert_eq!(behind, vec![hit_id, b, a], "hit before the fallback");
assert!(arts <= 34, "hit before the fallback: {arts} instances' art walked");
// A root that is not a layer, below the layer.
let mut d = Document::new(600.0, 400.0);
clipped_symbol(&mut d, false);
stack(&mut d, 60);
let root = Arc::new(Node::group(d.alloc_id(), vec![]));
d.layers.insert(0, root);
let (behind, _, arts) = with_art_limit(100, || objects_at(&d, p, HitOptions::default(), None));
assert!(behind.is_empty());
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
}
#[test]
fn locked_and_hidden_skip() {
let mut d = Document::new(200.0, 200.0);
+2
View File
@@ -28,6 +28,7 @@ pub mod shared;
mod symbol_export_type;
mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_pixel_aligned;
mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
@@ -37,6 +38,7 @@ pub use symbol_nine_slice::{
SymbolNineSlice, charge_symbol_art,
};
pub use symbol_overrides::SymbolOverride;
pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
pub mod links;
pub mod live;
+1
View File
@@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
for h in &mut feed.0 {
h.write_u8(u8::from(text.first_para_continues));
h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from));
for b in inline_bounds.clone() {
match b {
None => h.write_u8(0),
+8
View File
@@ -16,6 +16,11 @@ pub trait ColorVisitor {
fn color(&mut self, c: Color) -> Color;
/// The key of embedded image `key` recoloured, `None` when it stays as it is.
fn image(&mut self, key: &str) -> Option<String>;
/// Whether the pass recolors child `n` of a container: false leaves `n` and everything inside
/// it as they are.
fn enters(&mut self, _n: &Node) -> bool {
true
}
}
/// What a recolouring pass reaches: fills (including colorized image fills and gradient-mesh
@@ -82,6 +87,9 @@ pub fn recolor_node(n: &mut Node, reach: Reach, v: &mut dyn ColorVisitor) -> usi
}
_ => {
for c in n.children_mut().into_iter().flatten() {
if !v.enters(c) {
continue;
}
let mut m = (**c).clone();
let k = recolor_node(&mut m, reach, v);
if k > 0 {
+80
View File
@@ -0,0 +1,80 @@
//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their
//! actual size wherever they are placed
//! (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28>).
//!
//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned
//! (the default) is left out of the map.
use std::collections::HashSet;
use crate::Document;
/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol.
pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned";
impl Document {
/// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off).
pub fn symbol_pixel_aligned(&self, name: &str) -> bool {
self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false)
}
/// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map,
/// and the map goes when it is empty.
pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) {
if on {
let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({}));
if let Some(o) = m.as_object_mut() {
o.insert(name.into(), serde_json::json!(true));
}
return;
}
let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return };
o.remove(name);
if o.is_empty() {
self.unknown.remove(SYMBOL_PIXEL_ALIGNED);
}
}
/// Move the stored setting when a symbol is renamed.
pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) {
if from == to {
return;
}
let on = self.symbol_pixel_aligned(from);
self.set_symbol_pixel_aligned(from, false);
self.set_symbol_pixel_aligned(to, on);
}
/// The names of the pixel-aligned symbols the document holds (empty for most documents).
pub fn pixel_aligned_symbols(&self) -> HashSet<String> {
let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() };
o.iter()
.filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name))
.map(|(name, _)| name.clone())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_setting_is_off_by_default_and_follows_a_rename() {
let mut d = Document::new(100.0, 100.0);
let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![]));
d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art });
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
d.set_symbol_pixel_aligned("A", true);
assert!(d.symbol_pixel_aligned("A"));
assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()]));
d.symbols[0].name = "B".into();
d.rename_symbol_pixel_aligned("A", "B");
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.symbol_pixel_aligned("B"));
d.set_symbol_pixel_aligned("B", false);
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
assert!(d.pixel_aligned_symbols().is_empty());
}
}
+7 -1
View File
@@ -35,7 +35,7 @@ pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
};
pub use wrap::{resolve_wrap, wrap_work};
pub use wrap::{resolve_wrap, wrap_sources, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
///
@@ -67,6 +67,12 @@ pub struct TextObject {
/// it on a frame that leaves its thread and on a copy. Not saved.
#[serde(skip)]
pub first_para_continues: bool,
/// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the
/// last character of that paragraph in the frames before that a repeat mark could stand for
/// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout
/// reads it only while `first_para_continues` is on. Not saved.
#[serde(skip)]
pub first_para_lead: Option<char>,
/// Area Type Options (area type only).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub area: AreaOptions,
+3 -1
View File
@@ -48,8 +48,10 @@ pub struct CharStyle {
/// of the character's ink, inside its own width, that is taken away, 0 to [`MAX_TSUME`]. 50
/// halves that space and 100 sets the ink edge to edge; the glyph itself is not scaled. A
/// cluster takes the value of its first character. Tracking, kerning and Insert Aki are added
/// after it. Horizontal type only.
/// after it. In vertical type an upright character is measured above and below its ink, inside
/// its cell down the column.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
/// <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html>
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub tsume: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
+1
View File
@@ -94,6 +94,7 @@ impl TextObject {
para: ParaStyle::default(),
paras: Vec::new(),
first_para_continues: false,
first_para_lead: None,
area: AreaOptions::default(),
path_effect: PathEffect::default(),
path_align: PathAlign::default(),
+9
View File
@@ -271,6 +271,9 @@ pub struct ParaStyle {
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
/// with kinsoku None, where it has no effect. Off by default.
pub bunri_kinshi: bool,
/// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts
/// a line is drawn as the character it repeats, and the text keeps the mark. Off by default.
pub kurikaeshi_moji_shori: bool,
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
@@ -375,6 +378,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
bunri_kinshi: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kurikaeshi_moji_shori: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -412,6 +417,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -439,6 +445,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -470,6 +477,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -496,6 +504,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
+58 -34
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use vectorcraft_geom::{PathData, shapes};
use super::{TextKind, WrapShape};
use super::{TextKind, TextObject, WrapShape};
use crate::{Document, Node, NodeId, NodeKind};
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
@@ -82,6 +82,57 @@ pub fn wrap_work(doc: &Document) -> usize {
total
}
/// Each area text object of `layer`, from the top down, with the wrap objects above it in the
/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in
/// document coordinates. Each wrap object's outline is made once.
fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) {
let mut items = vec![];
collect(layer, &mut items);
let mut above: Vec<(&Node, WrapShape)> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }));
}
}
Item::Text(n) => f(n, &above),
}
}
}
/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as
/// [`each_text`] gives them: bottom first.
fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
let inv = t.xf.inverse();
above
.iter()
.rev()
.map(|(_, s)| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect()
}
/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap
/// objects whose outlines make them, bottom first, and those shapes (text space), as
/// [`resolve_wrap`] works them out. The copying is [`wrap_work`].
pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec<WrapShape>)) {
for layer in &doc.layers {
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind
&& !above.is_empty()
{
f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above));
}
});
}
}
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
@@ -95,41 +146,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId
{
continue;
}
let mut items = vec![];
collect(layer, &mut items);
if items.is_empty() {
continue;
}
// From the top down, each wrap object's outline is made once; each area text object takes
// those above it, bottom first.
let mut above: Vec<WrapShape> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
}
}
Item::Text(n) => {
let NodeKind::Text(t) = &n.kind else { continue };
let inv = t.xf.inverse();
let shapes: Vec<WrapShape> = above
.iter()
.rev()
.map(|s| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect();
if shapes != t.wrap {
updates.push((n.id, shapes));
}
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind {
let shapes = shapes_of(t, above);
if shapes != t.wrap {
updates.push((n.id, shapes));
}
}
}
});
}
let mut changed = Vec::with_capacity(updates.len());
for (id, shapes) in updates {
+48 -16
View File
@@ -117,6 +117,11 @@ thread_local! {
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// The objects in the baked art of the instances inside the art of other instances that
/// [`bake_node`] baked for one export and then left as they are, counted with
/// [`NESTED_NODES`] against [`crate::SYMBOL_ART_MAX_NODES`] before more art is baked. Never
/// given back.
static NESTED_DROPPED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
/// placed art ([`placed_symbol_art`]).
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
@@ -162,7 +167,7 @@ struct Placing {
layers: WrittenLayers,
}
/// The layers an exporter writes besides the shown, printing ones
/// The layers and objects an exporter writes besides the shown, printing ones
/// ([`bake_document_placing_symbols`]). Template layers are never written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WrittenLayers {
@@ -170,16 +175,19 @@ pub struct WrittenLayers {
pub hidden: bool,
/// Layers that do not print.
pub non_printing: bool,
/// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden
/// layers).
pub hidden_objects: bool,
}
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer
/// that does not print when the export leaves those out ([`WrittenLayers`]).
fn unwritten(n: &Node) -> bool {
PLACING.with(|p| {
p.borrow().as_ref().is_some_and(|p| match n.kind {
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
_ => !n.visible,
_ => !(n.visible || p.layers.hidden_objects),
})
})
}
@@ -369,17 +377,29 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
};
// Instances baked inside the art of others stop at the depth limit, or once their art
// passes the objects one export bakes that way: an instance of a symbol whose art holds
// instances of itself is kept as it is there.
// instances of itself is kept as it is there. The symbol's art is held in the count while
// it bakes, so the instances inside it bake only within what is left; the art it bakes to,
// with what its effects add, then takes its place in the count. When that art does not
// fit, the instance stays as it is, and the art baked for it, with the art dropped for the
// instances inside it, still counts against the instances after it.
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
let nested = instance && INSTANCE_DEPTH.with(|c| c.get()) > 0;
let before = NESTED_NODES.with(|c| c.get());
if nested {
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
let spent = before.saturating_add(count);
let dropped = NESTED_DROPPED.with(|c| c.get());
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent.saturating_add(dropped) > crate::SYMBOL_ART_MAX_NODES {
return None;
}
NESTED_NODES.with(|c| c.set(spent));
}
let m = reshape(Some(d), n, symbol.as_ref())?;
let Some(m) = reshape(Some(d), n, symbol.as_ref()) else {
if nested {
NESTED_NODES.with(|c| c.set(before));
}
return None;
};
if instance {
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
}
@@ -387,7 +407,17 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
if instance {
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
}
return Some(baked.unwrap_or(m));
let baked = baked.unwrap_or(m);
if nested {
let spent = before.saturating_add(baked.count() as u64);
if spent.saturating_add(NESTED_DROPPED.with(|c| c.get())) > crate::SYMBOL_ART_MAX_NODES {
NESTED_NODES.with(|c| c.set(before));
NESTED_DROPPED.with(|c| c.set(c.get().saturating_add(baked.count() as u64)));
return None;
}
NESTED_NODES.with(|c| c.set(spent));
}
return Some(baked);
}
// Symbol instances whose art draws live effects, when the caller asks for them: the art
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
@@ -1014,13 +1044,14 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
/// symbols' own art is left as it is.
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and
/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`:
/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`:
/// the hidden layers, layers that do not print and hidden objects that the exporter writes.
/// Instances the export does not write (template layers, and the hidden objects and layers
/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as
/// it is.
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
}
@@ -1068,6 +1099,7 @@ fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<D
}
let mut d = placed.into_owned();
NESTED_NODES.with(|c| c.set(0));
NESTED_DROPPED.with(|c| c.set(0));
let layers = d.layers.clone();
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
Some(d)
+134 -2
View File
@@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() {
}
/// Every layer written, as DXF writes them (template layers are never written).
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
fn is_instance(d: &Document, id: u64) -> bool {
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
@@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() {
}
// An export that writes the layers that do not print, or the hidden layers, places that
// layer's instance first; the template layer's instance is never placed.
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
for (layers, first) in
[(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)]
{
let out = bake(&d, Some((true, each, layers))).unwrap();
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
}
// An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance
// first, and the instance in the hidden group would come next; the hidden layer's instance
// stays, since that layer is still left out.
let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap();
assert!(!is_instance(&out, 901), "the hidden instance is placed");
for id in [900, 903, 911, 921, 931] {
assert!(is_instance(&out, id), "{id} stays as it is");
}
}
/// `leaf` in `levels` groups, with ids from `id` up.
@@ -1525,3 +1535,125 @@ fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
}
/// Instance `id` of `symbol` with a geometry effect, so baking it reshapes its art.
fn offset_instance(id: u64, symbol: &str) -> Node {
let mut n = instance(id, symbol, vectorcraft_geom::Affine::IDENTITY);
n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1.0})));
n
}
/// `n` baked as an instance inside another instance's art, with `spent` objects of nested symbol
/// art already baked: the baked object, and the objects counted after it, art baked and dropped
/// included.
fn bake_nested(d: &mut Document, n: &Node, spent: u64) -> (Option<Node>, u64) {
INSTANCE_DEPTH.with(|c| c.set(1));
NESTED_NODES.with(|c| c.set(spent));
NESTED_DROPPED.with(|c| c.set(0));
let out = bake_node(d, n);
INSTANCE_DEPTH.with(|c| c.set(0));
(out, NESTED_NODES.with(|c| c.replace(0)).saturating_add(NESTED_DROPPED.with(|c| c.replace(0))))
}
/// The object with id `id` in `n`'s subtree.
fn find(n: &Node, id: u64) -> Option<&Node> {
if n.id == NodeId(id) {
return Some(n);
}
n.children().into_iter().flatten().find_map(|c| find(c, id))
}
/// Is `n` an object other than a symbol instance?
fn baked(n: Option<&Node>) -> bool {
n.is_some_and(|n| !matches!(n.kind, NodeKind::SymbolInstance { .. }))
}
/// An instance baked inside another instance's art counts the art it bakes to, the copies its
/// symbol's effects make included: art that fits exactly takes the last of the budget, and art
/// whose symbol fits but whose baked art does not leaves the instance as it is and still counts.
#[test]
fn nested_reshape_counts_baked_art() {
let mut d = Document::new(400.0, 400.0);
add_symbol(&mut d, "Inner", gradient_copies(800));
let n = offset_instance(900, "Inner");
let source = d.symbols[0].art.count() as u64;
let (all, spent) = bake_nested(&mut d, &n, 0);
let baked = all.map_or(0, |m| m.count() as u64);
assert!(baked > source + 1, "the copies are objects of their own: {baked} > {source} + 1");
assert_eq!(spent, baked, "the baked art is counted in place of the symbol's art");
let max = crate::SYMBOL_ART_MAX_NODES;
let (exact, spent) = bake_nested(&mut d, &n, max - baked);
assert!(exact.is_some(), "{baked} objects fit in {baked}");
assert_eq!(spent, max);
let (short, spent) = bake_nested(&mut d, &n, max - baked + 1);
assert!(short.is_none(), "the symbol's {source} objects fit, the {baked} baked ones do not");
assert_eq!(spent, max + 1, "the art baked for the instance left as it is still counts");
}
/// An instance left as it is because its baked art does not fit still counts the art baked for
/// it: an instance after it is left as it is too, before its art bakes.
#[test]
fn nested_reshape_refusal_keeps_its_work_counted() {
let mut d = Document::new(400.0, 400.0);
add_symbol(&mut d, "Big", gradient_copies(800));
add_symbol(&mut d, "Small", moved_square(810));
let (big, small) = (offset_instance(900, "Big"), offset_instance(901, "Small"));
let count = |d: &mut Document, n: &Node| bake_nested(d, n, 0).0.map_or(0, |m| m.count() as u64);
let (b, s) = (count(&mut d, &big), count(&mut d, &small));
assert!(s < b, "{s} < {b}");
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
let (refused, spent) = bake_nested(&mut d, &big, first);
assert!(refused.is_none(), "the big art passes the budget");
assert_eq!(spent, first + b, "the big art baked and dropped counts");
let (later, after) = bake_nested(&mut d, &small, spent);
assert!(later.is_none(), "the small art does not fit after the dropped art");
assert_eq!(after, spent, "the small instance is refused before it bakes");
}
/// Sibling instances inside other instances' art whose baked art each passes what is left: the
/// first is baked and dropped, and its art counts, so the others are left as they are before
/// their art bakes. With room for all of them, every one is baked.
#[test]
fn nested_reshape_refused_siblings_bake_once() {
let mut d = Document::new(400.0, 400.0);
add_symbol(&mut d, "Big", gradient_copies(800));
let one = offset_instance(900, "Big");
let b = bake_nested(&mut d, &one, 0).0.map_or(0, |m| m.count() as u64);
let siblings: Vec<Arc<Node>> = (0..16).map(|i| Arc::new(offset_instance(1000 + i, "Big"))).collect();
let group = Node::group(NodeId(999), siblings);
let first = crate::SYMBOL_ART_MAX_NODES - b + 1;
let (refused, spent) = bake_nested(&mut d, &group, first);
let refused = refused.unwrap_or_else(|| group.clone());
assert!((0..16).all(|i| !baked(find(&refused, 1000 + i))), "no sibling fits: {refused:?}");
assert_eq!(spent, first + b, "only the first sibling's art is baked and counted: {spent}");
let (room, spent) = bake_nested(&mut d, &group, 0);
let room = room.unwrap_or_else(|| panic!("the siblings are baked"));
assert!((0..16).all(|i| baked(find(&room, 1000 + i))), "every sibling is baked");
assert_eq!(spent, 16 * b);
}
/// An instance inside another instance's art whose own art holds a reshaped instance counts that
/// instance's baked art once: a budget of exactly the outer art's baked objects bakes both, and
/// with one object less the art baked and dropped still counts.
#[test]
fn nested_reshape_counts_successful_descendants_once() {
let mut d = Document::new(400.0, 400.0);
add_symbol(&mut d, "Inner", gradient_copies(800));
let square = Node::path(NodeId(803), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(offset_instance(802, "Inner")), Arc::new(square)]));
let outer = offset_instance(900, "Outer");
let (all, spent) = bake_nested(&mut d, &outer, 0);
let all = all.unwrap_or_else(|| panic!("the outer instance is baked"));
assert!(baked(find(&all, 802)), "the inner instance is baked: {all:?}");
let total = all.count() as u64;
assert_eq!(spent, total);
let max = crate::SYMBOL_ART_MAX_NODES;
let (exact, spent) = bake_nested(&mut d, &outer, max - total);
let exact = exact.unwrap_or_else(|| panic!("{total} objects fit in {total}"));
assert!(baked(find(&exact, 802)), "the inner instance is baked too");
assert_eq!(spent, max);
let (short, spent) = bake_nested(&mut d, &outer, max - total + 1);
assert!(short.as_ref().is_none_or(|m| !baked(find(m, 802))), "with one object less, not both are baked");
assert!(spent > max, "the art baked and dropped counts: {spent}");
assert!(spent <= max - total + 1 + 2 * total, "at most the outer and the inner art are dropped: {spent}");
}
+3 -3
View File
@@ -210,21 +210,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
CLASSIC_EXTRUDE,
"Extrude & Bevel (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
),
g(
CLASSIC_REVOLVE,
"Revolve (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
CLASSIC_ROTATE,
"Rotate (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
+17 -5
View File
@@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineH
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
if outline {
let fill = src.appearance.fill_paint();
let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill };
appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() };
// The edges take the paint, opacity, blend mode and overprint of the top fill that paints,
// or of the top stroke that paints when no fill does.
let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i)));
let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0);
if let Some(i) = layer {
(stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint());
}
appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
}
let mut n = Node::path(src.id, path, appearance);
n.opacity = src.opacity;
@@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
.iter()
.filter_map(|l| {
let (path, rule) = geometry(l)?;
Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() }))
let fill = top_painting_fill(&l.appearance).map_or(Paint::None, |i| i.paint().clone());
Some((l.id, crate::trap::TrapSource { path, rule, fill }))
})
.unzip();
let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params));
@@ -580,7 +586,8 @@ fn mixing_rate(params: &Value) -> f64 {
}
fn fill_cmyk(src: &Node) -> Option<[f32; 4]> {
let paint = src.appearance.fill_paint();
// The top fill that paints: a hidden fill adds no color.
let paint = top_painting_fill(&src.appearance)?.paint().clone();
let color = paint.color()?;
let tinted = match paint {
Paint::Solid { tint, .. } => color.tinted(tint),
@@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
}
/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped.
fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> {
a.items.iter().rev().find(|i| i.is_fill() && paints(i))
}
/// Does `item` paint anything?
pub fn paints(item: &AppearanceItem) -> bool {
item.visible()
+94 -1
View File
@@ -1,6 +1,6 @@
use super::*;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject};
use vectorcraft_geom::{Point, Rect, shapes};
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
@@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
assert_eq!(fill.paint.color(), Some(yellow));
}
/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member
/// whose only fill is hidden does not take part.
#[test]
fn trap_skips_a_hidden_fill() {
let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0);
let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0);
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
let trap = |members: Vec<Arc<Node>>| {
let mut g = Node::group(NodeId(10), members);
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
pathfinder_children(None, &g, None).unwrap()
};
let mut covered = (*sq(1, 0.0, yellow)).clone();
covered.appearance.items.push(AppearanceItem::Fill(hidden.clone()));
let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]);
assert_eq!(out.len(), 3, "both squares and one trap");
assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow));
let only_hidden = Node::path(
NodeId(1),
shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)),
Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() },
);
assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap");
}
#[test]
fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() {
let mut g = two_overlapping_cmyk_squares();
@@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}");
}
/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color.
#[test]
fn mixes_skip_a_hidden_fill() {
for effect in ["pathfinder.softMix", "pathfinder.hardMix"] {
let mut plain = two_overlapping_cmyk_squares();
plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true });
let mut covered = plain.clone();
let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") };
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
for c in children.iter_mut() {
Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone()));
}
assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}");
}
}
/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend
/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill
/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes.
#[test]
fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() {
use vectorcraft_doc::StrokeLayer;
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let mut fill = FillLayer::new(red.clone());
(fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
hidden.visible = false;
let mut stroke = StrokeLayer::new(blue.clone(), 2.0);
(stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0);
hidden_stroke.visible = false;
let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0);
let look = |items: Vec<AppearanceItem>| Appearance { items, ..Default::default() };
let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke);
let cases = [
(look(vec![f(fill.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())),
(look(vec![f(hidden.clone())]), None),
(look(vec![s(stroke.clone())]), Some(blue.clone())),
(look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())),
(look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())),
(look(vec![s(zero_stroke)]), None),
];
for (appearance, want) in cases {
let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance));
let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]);
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect();
assert!(!edges.is_empty(), "{out:#?}");
for n in edges {
let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") };
match &want {
Some(paint) => {
assert_eq!(&s.paint, paint);
assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}");
}
None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"),
}
}
}
}
#[test]
fn shape_modes_follow_the_pathfinder_panel() {
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
+2 -2
View File
@@ -103,8 +103,8 @@ pub use solids::{
with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
rename_appearance_graphic_symbol,
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+31 -3
View File
@@ -175,6 +175,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
/// in a clip of its footprint, neither with an opacity mask.
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
use std::sync::Arc;
use vectorcraft_doc::{Node, NodeKind};
let (clip, mut underlay) = underlay(id, faces)?;
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to,
/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same
/// conditions as [`sealed`].
pub(crate) fn underlay(
id: vectorcraft_doc::NodeId,
faces: &[std::sync::Arc<vectorcraft_doc::Node>],
) -> Option<(vectorcraft_doc::Node, Vec<std::sync::Arc<vectorcraft_doc::Node>>)> {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
let mut outline = vectorcraft_geom::BezPath::new();
@@ -207,9 +221,7 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vector
_ => return None,
}
}
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default());
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay))
}
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
@@ -321,6 +333,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
(base, transparent.then_some(mask))
}
/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient
/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the
/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement.
/// An opaque gradient is returned as [`opaque_paint`] returns it.
pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option<Paint>) {
let (base, mask) = opaque_paint(paint);
if mask.is_none() || !matches!(paint, Paint::Gradient(_)) {
return (base, mask);
}
let mut pinned = paint.clone();
if let Paint::Gradient(g) = &mut pinned {
g.pin(bounds().inflate(1.0, 1.0));
}
opaque_paint(&pinned)
}
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
use std::sync::Arc;
use vectorcraft_doc::color::BlendMode;
+285 -19
View File
@@ -297,11 +297,35 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize {
faces.saturating_mul(4).saturating_mul(paint_bytes(paint))
}
/// Do Revolve's `options` light its surface with colored lights?
fn colored(options: &Revolve) -> bool {
options.light_color != [1.0; 3] || options.lights.is_some()
}
/// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under
/// colored lights (`colored`), in a solid color or a gradient, when a face takes a smooth light
/// ramp ([`crate::lighting::rgb_gradient_art`], [`crate::lighting::gradient_art`],
/// [`crate::lighting::smooth_paint`]). Not in a gradient with transparent stops: its composed faces
/// carry its opacity mask, which the underlay does not take ([`crate::lighting::underlay`]).
fn seals(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> bool {
colored
&& (matches!(paint, Paint::Gradient(_)) || paint.color().is_some())
&& faces.iter().any(|f| f.rgb_gradient.is_some() || f.light_gradient.is_some())
&& crate::lighting::opaque_paint(paint).1.is_none()
}
/// The bytes the copies of `paint` take on Revolve's `faces` ([`paint_copies`]), twice that when the
/// faces lie over an underlay of themselves ([`seals`]).
fn surface_copies(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> usize {
let copies = paint_copies(faces.len(), paint);
if seals(faces, paint, colored) { copies.saturating_mul(2) } else { copies }
}
/// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the
/// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`].
fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> {
let faces = vectorcraft_three_d::revolve(path, b, options)?;
*copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0)));
*copies = copies.saturating_add(item.map_or(0, |i| surface_copies(&faces, &paint_of(i).0, colored(&options))));
if *copies > MAX_PAINT_COPIES {
return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into());
}
@@ -439,7 +463,9 @@ fn group_shadow(
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last
/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them
/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them.
#[allow(clippy::too_many_arguments)]
fn surface(
doc: Option<&Document>,
@@ -454,7 +480,7 @@ fn surface(
expand: bool,
copies: &mut Copies,
cast: bool,
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>, bool)> {
#[cfg(test)]
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
// A loaded file or a profile edited past the limits keeps drawing its source path instead
@@ -474,15 +500,16 @@ fn surface(
let drawn =
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
let p = merged_params(&fx.id, &fx.params);
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false));
}
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
let colored = colored(&options);
let (faces, kept) = if cast {
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
} else {
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
};
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
let seal = seals(&faces, &paint, colored);
copies.surfaces = copies.surfaces.saturating_add(surface_copies(&faces, &paint, colored));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
}
@@ -605,7 +632,62 @@ fn surface(
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
Some((keys, group, kept))
Some((keys, group, kept, seal))
}
/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal`
/// ([`sealed_run`]), keeping the surface's opacity and blending mode.
fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node {
let NodeKind::Group { children, clip: false } = &surface.kind else { return surface };
let Some(mut out) = seal.then(|| sealed_run(id, children)).flatten() else { return surface };
out.opacity = surface.opacity;
out.blend = surface.blend;
out
}
/// The faces `run` of one surface, in drawing order, over an underlay of themselves, all clipped
/// once to the faces' outline, as [`crate::lighting::sealed`] draws them. A face drawn with a part
/// of a graphic, a group of the face and that part, takes its face's underlay and stays in the
/// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]),
/// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces.
fn sealed_run(id: NodeId, run: &[Arc<Node>]) -> Option<Node> {
let faces: Vec<Arc<Node>> = run
.iter()
.map(|face| match &face.kind {
NodeKind::Group { children, clip: false } => children.first().cloned(),
_ => Some(face.clone()),
})
.collect::<Option<_>>()?;
if faces.is_empty() {
return None;
}
let (clip, mut underlay) = crate::lighting::underlay(id, &faces)?;
underlay.extend(run.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive
/// faces of one surface that `seal` takes lies over an underlay of its own faces ([`sealed_run`]),
/// so no underlay reaches under another surface's faces, as Inflate's surfaces do
/// (`crate::solids::underlaid_runs`). A run the underlay does not take keeps its faces.
fn sealed_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, seal: impl Fn(usize) -> bool) -> Vec<Arc<Node>> {
let mut out = Vec::with_capacity(faces.len());
let mut run: Vec<Arc<Node>> = vec![];
let mut faces = faces.into_iter().peekable();
while let Some((surface, face)) = faces.next() {
run.push(face);
if faces.peek().is_some_and(|(next, _)| *next == surface) {
continue;
}
match seal(surface).then(|| sealed_run(id, &run)).flatten() {
Some(sealed) => {
out.push(Arc::new(sealed));
run.clear();
}
None => out.append(&mut run),
}
}
out
}
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
@@ -640,7 +722,8 @@ fn object_surface(
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
let cast = casts(fx, opacity);
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast)
.map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept))
}
/// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides
@@ -1066,6 +1149,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let mut surfaces = vec![];
// The faces each member's surface kept for the shadow, member by member.
let mut kept = vec![];
// Whether each member's faces lie over an underlay of themselves ([`surface`]).
let mut seals = vec![];
let mut opaque = true;
// The graphics go once, on the side of the member with the longest profile. Without graphics
// no member is measured for them.
@@ -1084,10 +1169,14 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let doc = doc.filter(|_| longest == Some(k));
let cast = casts(fx, opacity * s.opacity);
let options = Revolve { fill_rule: s.rule, ..options };
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
surfaces.push((depths, art, s.scopes.as_slice()));
kept.push(faces);
seals.push(seal);
}
// The faces of a member whose surface takes an underlay lie over one, run by run in the one
// order of every member's faces ([`sealed_runs`]).
let seal = |member: usize| seals.get(member) == Some(&true);
if surfaces.is_empty() {
return None;
}
@@ -1113,7 +1202,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let order = crate::solids::surface_order(faces.iter().map(|(d, ..)| (d.points.as_slice(), d.plane, d.depth)));
let faces = in_order(faces, &order);
if opaque {
vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))]
vec![Arc::new(Node::group(n.id, sealed_runs(n.id, faces.into_iter().map(|(_, member, .., face)| (member, face)).collect(), seal)))]
} else {
// An opaque member's face goes in the order on its own. The faces of a member with
// transparency share a run, one group with the opacity and blending mode of its fill or
@@ -1122,6 +1211,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
// where one group can't be both behind and in front of another face.
struct Run<'a> {
member: Option<usize>,
// The member the faces are of.
of: usize,
scopes: &'a [Scope],
bounds: Rect,
faces: Vec<Arc<Node>>,
@@ -1137,12 +1228,12 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0);
let Some(cover) = Coverage::of(&face).filter(|_| paints) else {
// A face that paints nothing goes in the order on its own and overlaps nothing.
runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
runs.push(Run { member: None, of: member, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend });
continue;
};
let masked = masks.get(member).is_some_and(Option::is_some);
if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked {
runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
runs.push(Run { member: None, of: member, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
continue;
}
let mut clear = |r: &Run| {
@@ -1165,24 +1256,49 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if let Some(last) = last_run.get_mut(member) {
*last = Some(runs.len());
}
runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend });
runs.push(Run {
member: Some(member),
of: member,
scopes,
bounds: cover.bounds,
faces: vec![face],
cover: vec![cover],
opacity,
blend,
});
}
}
}
let runs = runs.into_iter().filter_map(|mut r| {
// Consecutive faces of opaque members on their own wait in `solo` and go over an
// underlay of their member's faces, run by run ([`sealed_runs`]).
let mut out: Vec<(&[Scope], Arc<Node>)> = Vec::with_capacity(runs.len());
let mut solo: Vec<(usize, Arc<Node>)> = vec![];
for mut r in runs {
// A face on its own needs a group only for the opacity or blending mode of its fill or stroke.
if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() {
return r.faces.pop().map(|face| (r.scopes, face));
let Some(face) = r.faces.pop() else { continue };
if r.scopes.is_empty() && !r.cover.is_empty() {
solo.push((r.of, face));
} else {
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
out.push((r.scopes, face));
}
continue;
}
let mut group = Node::group(n.id, r.faces);
out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face)));
let mut group = match r.member.filter(|m| seal(*m)).and_then(|_| sealed_run(n.id, &r.faces)) {
Some(sealed) => sealed,
None => Node::group(n.id, r.faces),
};
group.opacity = r.opacity;
group.blend = r.blend;
if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() {
group.extras_mut().mask = Some(mask);
}
Some((r.scopes, Arc::new(group)))
});
scoped(n.id, runs.collect(), 0)
out.push((r.scopes, Arc::new(group)));
}
out.extend(sealed_runs(n.id, solo, seal).into_iter().map(|face| (&[][..], face)));
scoped(n.id, out, 0)
}
};
// One shadow for every member's surface, behind them all.
@@ -1705,6 +1821,156 @@ mod tests {
assert_eq!(revolve_art(&two), None, "past the budget the source draws");
let object = painted(3, 0.0, stops * 2);
assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget");
// Under a colored light the faces lie over an underlay of themselves, which copies their
// paints again: the gradient that fits in white light is past the budget.
let lit = json!({"lightColor": "#ff0000"});
let object = painted(4, 0.0, stops);
assert_eq!(validate_revolve(&object, &json!({})), Ok(()));
let refused = validate_revolve(&object, &lit).unwrap_err();
assert!(refused.contains("simplify the gradient"), "{refused}");
let mut drawn = (*object).clone();
drawn.appearance.effects.push(crate::new_effect(REVOLVE, &lit).unwrap());
assert_eq!(revolve_art(&drawn), None, "past the budget the source draws");
}
/// Is `u` the underlay [`crate::lighting::underlay`] draws for `face`, a face [`surface`] draws?
fn underlies(u: &Node, face: &Node) -> bool {
match (&u.kind, &face.kind) {
(NodeKind::Path { .. }, NodeKind::Path { .. }) => {
u.path_data() == face.path_data()
&& u.appearance.items.iter().all(|i| !matches!(i, AppearanceItem::Stroke(s) if s.width != crate::lighting::UNDERLAY_SEAM))
}
(NodeKind::Group { children: under, clip: true }, NodeKind::Group { children, clip: true }) => {
matches!((under.get(1), children.get(1)), (Some(a), Some(b)) if Arc::ptr_eq(a, b))
}
(_, NodeKind::Group { children, clip: false }) => children.first().is_some_and(|f| underlies(u, f)),
_ => false,
}
}
/// The runs of faces in `art` that lie over an underlay of themselves ([`sealed_run`]), each
/// run's faces in drawing order.
pub(super) fn sealed_faces(art: &Node) -> Vec<Vec<Arc<Node>>> {
let mut out = vec![];
art.walk(&mut |n| {
let NodeKind::Group { children, clip: true } = &n.kind else { return };
let [clip, inner] = &children[..] else { return };
let NodeKind::Group { children: drawn, clip: false } = &inner.kind else { return };
let (under, faces) = drawn.split_at(drawn.len() / 2);
if clip.path_data().is_some() && !inner.isolate && drawn.len() % 2 == 0 && under.iter().zip(faces).all(|(u, f)| underlies(u, f)) {
out.push(faces.to_vec());
}
});
out
}
/// `n`'s surface as [`surface`] draws it before its faces are sealed, and whether they are.
fn unsealed(n: &Node) -> (Node, bool) {
let path = n.path_data().unwrap();
let fx = n.appearance.effects.first().unwrap();
let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap());
let (_, art, _, seal) =
surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap();
(art, seal)
}
#[test]
fn colored_light_faces_lie_over_an_underlay_of_themselves_once_per_surface() {
use vectorcraft_doc::color::{BlendMode, Gradient, GradientKind, GradientPaint, GradientStop};
let lit = |params: Value, paint: Paint| {
let mut n = profile_node();
n.appearance = Appearance::basic(paint, Paint::None, 0.0).into();
n.appearance.effects.push(crate::new_effect(REVOLVE, &params).unwrap());
n
};
let red = Paint::solid(Color::rgb(0.8, 0.2, 0.1));
let ramp = |opacity: f32| {
let stops = [Color::WHITE, Color::rgb(0.5, 0.5, 0.5)].into_iter().enumerate();
let stops = stops.map(|(i, c)| GradientStop { opacity, ..GradientStop::new(i as f32, c) }).collect();
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))
};
let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]);
// In white light nothing is sealed.
let white = lit(json!({}), red.clone());
assert!(!unsealed(&white).1);
assert!(sealed_faces(&revolve_art(&white).unwrap()).is_empty());
for (name, n) in [
("solid", lit(json!({"lightColor": "#ff0000"}), red.clone())),
("gradient", lit(json!({"lightColor": "#ff0000"}), ramp(1.0))),
("two lights", lit(json!({"lights": lights}), ramp(1.0))),
("edge-on", lit(json!({"lightColor": "#ff0000", "rotationX": -80}), red.clone())),
] {
// Every face of the surface, in its order, lies over its underlay, once.
let (plain, seal) = unsealed(&n);
assert!(seal, "{name}");
let faces = plain.children().unwrap().to_vec();
assert_eq!(sealed_faces(&revolve_art(&n).unwrap()), vec![faces], "{name}");
}
// The surface's opacity and blending mode apply once, to the sealed surface.
let mut n = lit(json!({"lightColor": "#ff0000"}), ramp(1.0));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.5;
f.blend = BlendMode::Multiply;
}
let art = revolve_art(&n).unwrap();
assert_eq!(sealed_faces(&art).len(), 1);
// Inside the surface only a face's own lit art blends (its light multiplied over its paint).
let once = |chain: &Chain| chain.first() == Some(&(0.5, BlendMode::Multiply)) && chain.iter().skip(1).all(|(o, _)| *o == 1.0);
let faces = faces_in_order(&art);
assert!(faces.iter().all(|(_, chain)| once(chain)), "{:?}", faces.iter().map(|f| &f.1).find(|c| !once(c)));
// Faces in a gradient with transparent stops carry its opacity mask, which the underlay
// does not take: the surface keeps its faces as they are, and their paints are not
// counted twice.
let n = lit(json!({"lightColor": "#ff0000"}), ramp(0.6));
let (plain, seal) = unsealed(&n);
assert!(!seal);
assert_eq!(sealed_surface(n.id, plain.clone(), true), plain);
assert!(sealed_faces(&revolve_art(&n).unwrap()).is_empty());
let path = n.path_data().unwrap();
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), fx_options(&n.appearance.effects[0])).unwrap();
assert_eq!(surface_copies(&faces, &ramp(0.6), true), paint_copies(faces.len(), &ramp(0.6)));
assert_eq!(surface_copies(&faces, &ramp(1.0), true), 2 * paint_copies(faces.len(), &ramp(1.0)));
// Revolve (Classic) takes no colored light, so none of its faces are sealed.
assert!(!colored(&classic::options(&json!({"lightColor": "#ff0000"}))));
}
#[test]
fn each_members_run_of_faces_lies_over_an_underlay_of_its_own() {
// Rings one above the other: their faces alternate in the one order, so each ring's
// faces go over underlays run by run, and no run holds faces of both.
let ring = |id, y: f64, opacity: f32| {
let mut n = (*member(id, 40.0)).clone();
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = opacity;
}
if let NodeKind::Path { path, .. } = &mut n.kind {
*path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath()));
}
Arc::new(n)
};
let lit = json!({"segments": 16, "lightColor": "#ff0000"});
for opacity in [1.0, 0.5] {
let members = vec![ring(1, 0.0, 1.0), ring(2, 200.0, opacity)];
let art = revolve_art(&group_with(lit.clone(), members.clone())).unwrap();
let runs = sealed_faces(&art);
assert!(runs.len() >= 2, "{opacity}: {} runs", runs.len());
for run in &runs {
let ys: Vec<f64> = run.iter().filter_map(|f| f.visual_bounds()).map(|b| b.center().y).collect();
assert!(ys.iter().all(|y| *y < 100.0) || ys.iter().all(|y| *y > 100.0), "{opacity}: a run holds one ring's faces: {ys:?}");
}
// Each ring's opacity applies once, to its faces and their underlays; inside, only a
// face's own lit art blends.
let faded = |chain: &Chain| chain.iter().filter(|(o, _)| *o != 1.0).count();
let chains: Vec<Chain> = faces_in_order(&art).into_iter().map(|(_, c)| c).collect();
assert!(chains.iter().all(|c| faded(c) <= 1 && c.iter().all(|(o, _)| *o == 1.0 || *o == opacity)), "{opacity}");
assert_eq!(chains.iter().any(|c| faded(c) == 1), opacity < 1.0, "{opacity}");
if opacity == 1.0 {
// Opaque rings share one order, and every face in it lies over an underlay.
let white = revolve_art(&group_with(json!({"segments": 16}), members)).unwrap();
let count = white.children().unwrap()[0].children().unwrap().len();
assert_eq!(runs.iter().map(Vec::len).sum::<usize>(), count);
}
}
}
#[test]
+35
View File
@@ -164,6 +164,41 @@ mod tests {
}
}
/// With Black Overprint every face keeps the blue, and the faces that darken get black over it,
/// overprinting, as strong as the darkening of the shading color Black.
#[test]
fn black_overprint_keeps_the_blue_under_overprinting_black() {
let darkened = revolved(json!({"surface": "diffuse"}));
let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"}));
let (darkened, drawn) = (faces(&darkened), faces(&art));
assert_eq!(darkened.len(), drawn.len());
let mut shaded = 0;
for (face, black) in drawn.iter().zip(&darkened) {
let fills: Vec<&vectorcraft_doc::FillLayer> = face
.appearance
.items
.iter()
.filter_map(|i| match i {
AppearanceItem::Fill(f) => Some(f),
AppearanceItem::Stroke(_) => None,
})
.collect();
assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false));
let k = match fills.get(1) {
Some(shadow) => {
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
shaded += 1;
k
}
None => 0.0,
};
let b = fill(black).unwrap().to_rgb()[2];
assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}");
}
assert!(shaded > 0, "faces turned from the light get black");
}
#[test]
fn angle_offset_edge_and_cap_shape_the_surface() {
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
@@ -279,6 +279,23 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() {
assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}");
}
#[test]
fn under_a_colored_light_each_part_of_a_graphic_stays_right_after_its_face_over_the_underlay() {
let d = document();
let n = revolved(&CYLINDER, json!({"shade": true, "lightColor": "#ff8040", "graphics": [{"symbol": "Red"}]}));
let art = revolve_art_in(Some(&d), &n).unwrap();
// One run holds every face; a face with a part of the bar is a group of the face and that part.
let runs = super::tests::sealed_faces(&art);
assert_eq!(runs.len(), 1);
let carrying: Vec<&Arc<Node>> = runs[0].iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).collect();
assert!(!carrying.is_empty());
assert!(carrying.iter().all(|f| f.children().is_some_and(|c| c.len() > 1 && parts(&c[0], false).is_empty())));
// Every part of the bar is drawn in the run, after its face, and none in the underlay.
let in_run: usize = carrying.iter().map(|f| parts(f, false).len()).sum();
assert!(in_run > 0);
assert_eq!(in_run, parts(&art, false).len());
}
#[test]
fn graphics_past_the_point_limit_are_refused() {
let mut d = document();
+24 -2
View File
@@ -102,6 +102,21 @@ pub fn has_solid(n: &Node) -> bool {
solid(&n.appearance.effects).is_some() || n.appearance.items.iter().any(|i| i.visible() && solid(i.effects()).is_some())
}
/// Does `n` carry a 3D effect that [`three_d_meshes`] builds solids from: a visible Revolve, or
/// else a visible Extrude & Bevel, Inflate or Rotate effect, which on a group or layer must be on
/// the object itself (one on a group's fill or stroke draws nothing to export)? It does not build
/// the solids, so [`three_d_meshes`] can still refuse an object it passes.
pub fn exports_three_d(n: &Node) -> bool {
let container = is_container(n);
if crate::has_revolve(n) {
!container || n.appearance.effects.iter().any(|e| e.visible && crate::is_revolve(&e.id))
} else if container {
solid(&n.appearance.effects).is_some()
} else {
has_solid(n)
}
}
/// The Position presets: (id, [rotation X, Y, Z]). Front, Back, Left, Right, Top and Bottom face
/// the art that way; Off-Axis tilts each 20° down and 25° aside (showing the top and right);
/// Isometric lays the art on the left, right, top or bottom plane of an isometric view (the
@@ -625,7 +640,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
/// with the faces of other solids.
/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn
/// opaque under one mask of its transparency, placed once on all the facets when it has no
/// placement of its own ([`crate::lighting::opaque_surface_paint`]).
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
if !faces && composites_facets(&facets, paint, colored) {
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
@@ -634,7 +651,7 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
return group;
}
// Preserve existing white-light paints and alpha composition exactly.
let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) };
let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) };
let paint = &opaque;
let children = facets
.into_iter()
@@ -671,6 +688,11 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any).
pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect {
facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO)
}
/// The width of the stroke of a facet's own paint that closes the seams between `face` and its
/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than
/// the stroke, and its stroke would then paint over its neighbors.
+53 -19
View File
@@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"];
/// The width of a Wireframe edge, in points.
const WIRE: f64 = 0.5;
/// The Shading Color choices: black, a custom color, or none.
pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"];
/// The Shading Color choices: black, a custom color, none, or black overprinting the paint.
pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"];
/// The surface settings of Extrude & Bevel (Classic)'s parameters.
pub fn classic_shading(p: &Value) -> ClassicShading {
@@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude {
}
}
/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only
/// the highlight lightens them).
/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces
/// keep their paint and only the highlight lightens them).
fn shading_color(p: &Value) -> Option<Color> {
match text(p, "shadingColor", "black") {
"none" => None,
@@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool {
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
/// tone `tone` is below full light and the faces darken (`shade`), black over it as
/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam
/// stroke each layer draws around the face.
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
if shade.is_some() && tone < 1.0 {
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
let mut layer = FillLayer::new(black.clone());
layer.blend = BlendMode::Multiply;
layer.overprint = true;
let mut edge = crate::lighting::seam_stroke(black, seam);
edge.blend = BlendMode::Multiply;
edge.overprint = true;
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
if shade.is_some() {
items.extend(overprinting_black(tone, seam));
}
items
}
/// The black that shades a face at tone `tone` on the black plate, when the tone is below full
/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam`
/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a
/// neighbor's, the face is not darkened twice.
fn overprinting_black(tone: f64, seam: f64) -> Vec<AppearanceItem> {
if tone >= 1.0 {
return vec![];
}
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
let mut layer = FillLayer::new(black.clone());
layer.blend = BlendMode::Multiply;
layer.overprint = true;
let mut edge = crate::lighting::seam_stroke(black, seam);
edge.blend = BlendMode::Darken;
edge.overprint = true;
vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]
}
/// Whether the shading color of parameters `p` is Black Overprint.
fn black_overprint(p: &Value) -> bool {
text(p, "shadingColor", "black") == "blackOverprint"
}
/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full
/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they
/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of
/// the seam stroke each layer draws around the face.
fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec<AppearanceItem> {
let mut items =
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))];
items.extend(overprinting_black(tone, seam));
items
}
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
/// Wireframe, else the seam between faces.
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
@@ -229,16 +256,19 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
/// its own transparency, so the shading follows the gradient's coverage.
/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot
/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops
/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's
/// coverage; without a placement of its own, it is placed once on all the faces
/// ([`crate::lighting::opaque_surface_paint`]).
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
let shading = classic_shading(p);
let lights = lights(p);
let shade = shading_color(p);
let preserve = preserves_spot_colors(p);
let overprint = black_overprint(p);
let wire = shading.surface == ClassicSurface::Wireframe;
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) };
let paint = &paint;
let children = facets
.into_iter()
@@ -251,6 +281,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
let (tone, spec) = shading.tone(face.normal, &lights);
// A narrow stroke of the face's own paint closes the hairline seams between faces.
let seam = super::seam_width(&face);
if overprint {
let items = overprinted_face(paint, tone, seam);
return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }));
}
let items = match paint.color() {
// Unshaded (No Shading, no shading color, or a face in full light) with no
// highlight: the paint itself, its color space and swatch kept.
+140 -2
View File
@@ -1908,6 +1908,89 @@ fn classic_shading_color_blend_steps_and_lights() {
assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6);
}
/// The fills, then the strokes, of face `face`.
fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) {
let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect();
let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect();
(fills, strokes)
}
/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in
/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice);
/// `None` when the face has none.
fn overprinted_black(face: &Node) -> Option<f32> {
let (fills, strokes) = layers_of(face);
assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke");
let shadow = fills.get(1)?;
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true));
assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out");
Some(k)
}
/// Black Overprint keeps the paint on every face and draws the shading over it as black,
/// overprinting, as strong as the darkening of the shading color Black; the
/// highlight is not drawn, and No Shading adds no black.
#[test]
fn classic_black_overprint_keeps_the_paint_under_overprinting_black() {
let diffuse = json!({"surface": "diffuse", "ambient": 20});
let mut over = diffuse.clone();
over["shadingColor"] = json!("blackOverprint");
let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect();
let faces = classic_faces(over);
assert_eq!(faces.len(), darkened.len());
let mut shaded = 0;
for (face, rgb) in faces.iter().zip(&darkened) {
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept");
let k = overprinted_black(face).unwrap_or(0.0);
assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}");
shaded += usize::from(k > 0.0);
}
assert!(shaded > 0, "faces turned from the light get black");
// Plastic: no white layer for the highlight.
let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
for face in classic_faces(shiny) {
let (fills, _) = layers_of(&face);
assert_eq!(fills[0].paint, Paint::solid(RED));
assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}");
}
// No Shading: the paint alone.
for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) {
assert_eq!(overprinted_black(&face), None);
assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED));
}
}
/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate
/// (Classic) draws its plane the same way.
#[test]
fn classic_black_overprint_keeps_gradients_and_shades_rotate() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint};
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
GradientKind::Linear,
vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)],
))));
let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = gradient.clone();
}
let art = solid_art(&n).unwrap();
let mut shaded = 0;
for face in faces(&art) {
assert_eq!(layers_of(face).0[0].paint, gradient);
shaded += usize::from(overprinted_black(face).is_some());
}
assert!(shaded > 0);
// Rotate (Classic), turned from the light: red with black over it; facing it: red alone.
let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
let face = &turned[0].children().unwrap()[0];
assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED));
assert!(overprinted_black(face).is_some_and(|k| k > 0.05));
let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"}));
assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None);
}
#[test]
fn classic_bevel_height_extent_and_cap_shape_the_solid() {
let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap();
@@ -1960,6 +2043,57 @@ fn classic_shading_keeps_a_gradients_transparency() {
}
}
/// A gradient without a placement and with a transparent stop, under colored lights or classic
/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask
/// share one placement, so the color and transparency ramps line up across the faces. A gradient
/// placed in the document keeps its placement.
#[test]
fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() {
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
// The source's stops carry an unusual midpoint, so its color and mask copies can be told from
// the light ramps.
const MARK: f32 = 0.37;
let mut first = GradientStop::new(0.0, RED);
first.midpoint = MARK;
let mut end = GradientStop::new(1.0, Color::BLACK);
end.opacity = 0.25;
let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end]));
let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None };
// The placement of each copy of the source gradient: its own, else its fit on the path it fills.
fn placements(n: &Node, out: &mut Vec<GradientGeom>) {
n.walk(&mut |c| {
if let Some(mask) = &c.extras().mask {
placements(&mask.art, out);
}
let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO);
for item in &c.appearance.items {
if let Paint::Gradient(g) = paint_ref(item)
&& g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK)
{
out.push(g.resolve(bounds));
}
}
});
}
let lit = json!({"lights": [{"color": "#ff8080"}]});
for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] {
for geom in [None, Some(placed)] {
let mut n = square_node();
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))];
n.appearance.effects.push(fx(id, params.clone()));
let art = solid_art(&n).unwrap_or_else(|| panic!("{id}"));
let mut masks = 0;
art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some()));
assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask");
let mut found = vec![];
placements(&art, &mut found);
assert!(found.len() > 2, "{id}: the faces' colors and the mask");
let expected = geom.unwrap_or(found[0]);
assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}");
}
}
}
/// A group member in a gradient with transparent stops keeps the shared back-to-front order of
/// every member's faces: its faces go in runs that carry its opacity mask, and the other member's
/// faces are drawn between them where they are in front of some and behind others. Here a square
@@ -2083,9 +2217,12 @@ fn classic_parameters_are_checked() {
let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p));
assert!(check(json!({})).is_ok());
assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok());
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
for (p, says) in [
(json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"),
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
(json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"),
(json!({"shadingColor": true}), "`shadingColor` must be one of"),
(json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"),
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
(json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"),
@@ -2162,11 +2299,12 @@ fn classic_rotate_parameters_are_checked() {
let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p));
assert!(check(json!({})).is_ok());
assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok());
assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok());
for (p, says) in [
(json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"),
(json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"),
(json!({"surface": 2}), "`surface` must be one of"),
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"),
(json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"),
(json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"),
(json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"),
(json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"),
+1 -1
View File
@@ -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 }
+2
View File
@@ -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;
+19 -2
View File
@@ -446,7 +446,7 @@ pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId],
}
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
fn targets_contents(p: &Value) -> Result<bool> {
pub(crate) fn targets_contents(p: &Value) -> Result<bool> {
match p.get("target") {
None | Some(Value::Null) => Ok(false),
Some(v) => match v.as_str() {
@@ -508,6 +508,20 @@ pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId>
ids
}
/// [`drop_design_art`] for an edit of the `item` rows of `ids` (`fill`: fill rows): an explicit `item` that a design's
/// art has no row of that kind for is still an error of `cmd`, as on any other object.
pub(crate) fn drop_design_art_rows(s: &Session, ids: Vec<NodeId>, item: ItemTarget, fill: bool, cmd: &str) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
for (id, it) in ids.iter().zip(item.per_target(s, &ids)) {
if let (Some(it), Some(n)) = (it, d.node(*id))
&& super::graph::is_design_art(d, *id)
{
it.resolve(&n.appearance, fill, cmd)?;
}
}
Ok(drop_design_art(d, ids))
}
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
/// [`super::graph::is_design_art`] accepts.
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
@@ -720,7 +734,10 @@ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bo
let holder = match reference_of(s, p, item, cmd)? {
Some(of) => Some(of),
None => {
let ids = drop_design_art(d, appearance_targets(s, p)?);
let all = appearance_targets(s, p)?;
// The art of a graph design is left out, unless it is all there is: the item is then a row of that art.
let kept = drop_design_art(d, all.clone());
let ids = if kept.is_empty() { all } else { kept };
ids.get(item.anchor(s, &ids)).copied()
}
};
+29 -3
View File
@@ -8,7 +8,7 @@ use std::collections::HashSet;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{ExportAsset, NodeId};
use super::edit::{roots_of, selected_roots};
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
use super::fileio::{
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export 3D Object",
[],
None,
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}",
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object in ids without such an effect is refused. Without ids, the selected objects without one (on a group or layer, one on its fill or stroke draws nothing and does not count), and a selected object inside another selected object that has one, are left out; refused when none is left → {assets: [asset id…] (in order), added: n}",
has_doc,
add_3d
),
@@ -203,10 +203,36 @@ fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &
Ok(ids)
}
/// The selected objects `assets.add3D` collects without `ids`: those with a 3D effect it exports
/// ([`vectorcraft_render::effects::exports_three_d`]; a path of a compound path counts as the
/// compound path), layers included, in tree order, dropping
/// each one inside another of them (that one's asset holds it). Refused while an object of a
/// dynamic symbol instance's art is selected, as [`selected_roots`] is.
fn selected_3d_roots(s: &Session) -> Result<Vec<NodeId>> {
refuse_symbol_part(s)?;
let st = s.doc()?;
// A path of a compound path stands for the compound path, which holds the paint and effects.
let found = st
.selection
.objects
.iter()
.map(|id| super::path::compound_or_self(&st.doc, *id))
.filter(|id| st.doc.node(*id).is_some_and(vectorcraft_render::effects::exports_three_d));
let mut paths: Vec<(Vec<usize>, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect();
paths.sort_by(|a, b| a.0.cmp(&b.0));
let mut kept: Vec<(Vec<usize>, NodeId)> = Vec::with_capacity(paths.len());
for (path, id) in paths {
if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) {
kept.push((path, id));
}
}
Ok(kept.into_iter().map(|(_, id)| id).collect())
}
fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "assets.add3D";
let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?;
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? };
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_3d_roots(s)? };
if ids.is_empty() {
return Err(bad(C, "select an object with a 3D effect (or give its ids)"));
}
+3 -3
View File
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbols",
[],
None,
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}",
"{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}",
has_doc,
symbol_list
),
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Symbol…",
[],
None,
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}",
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_selection,
symbol_new
),
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}",
has_doc,
symbol_options
),
+42 -9
View File
@@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option<SymbolNineSlice>) -> R
})
}
/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any
/// value other than true or false, null included, is an error.
fn pixel_grid_param(p: &Value, cmd: &str) -> Result<Option<bool>> {
match p.get("alignToPixelGrid") {
None => Ok(None),
Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")),
}
}
fn nine_slice_json(d: &Document, name: &str) -> Value {
d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value)
}
@@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result<Value> {
"exportType": d.symbol_export_type(&sym.name).id(),
"nineSlice": nine_slice_json(d, &sym.name),
"type": type_id(sym.dynamic),
"alignToPixelGrid": d.symbol_pixel_aligned(&sym.name),
})
})
.collect();
@@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
let export = export_type_param(p, C)?.unwrap_or_default();
let nine = nine_slice_param(p, C, None)?.flatten();
let dynamic = type_param(p, C)?.unwrap_or(false);
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
let id = s.edit("New Symbol", |d, sel| {
@@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&name, reg);
d.set_symbol_export_type(&name, export);
d.set_symbol_nine_slice(&name, nine);
d.set_symbol_pixel_aligned(&name, pixel);
let id = instance_in_place(d, &ids, &name, place)?;
sel.set([id]);
Ok(id)
@@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
"exportType": export.id(),
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
"type": type_id(dynamic),
"alignToPixelGrid": pixel,
}))
}
@@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
let reg = registration_param(p, C)?;
let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?;
let dynamic = type_param(p, C)?;
let pixel = pixel_grid_param(p, C)?;
let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() {
return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type"));
match pixel {
None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")),
// Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added.
Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)),
Some(_) => {}
}
}
if let Some(ref n) = new_name
&& n != &name
@@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
d.rename_symbol_nine_slice(&name, n);
d.rename_symbol_pixel_aligned(&name, n);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.insert(CURRENT_SYMBOL.into(), json!(n));
}
@@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
sym.dynamic = dynamic;
fit_overrides(d, &instances_of(d, Some(&final_name)));
}
// Turning it on snaps the art and the instances at actual size when the edit ends
// (`object::refresh_pixel_aligned`).
if let Some(on) = pixel {
d.set_symbol_pixel_aligned(&final_name, on);
}
Ok(())
})?;
let d = &s.doc()?.doc;
Ok(json!({
"name": final_name,
"registration": d.symbol_registration(&final_name).0,
"exportType": d.symbol_export_type(&final_name).id(),
"nineSlice": nine_slice_json(d, &final_name),
"type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)),
}))
Ok(options_json(&s.doc()?.doc, &final_name))
}
/// What `symbol.options` answers for symbol `name`.
fn options_json(d: &Document, name: &str) -> Value {
json!({
"name": name,
"registration": d.symbol_registration(name).0,
"exportType": d.symbol_export_type(name).id(),
"nineSlice": nine_slice_json(d, name),
"type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)),
"alignToPixelGrid": d.symbol_pixel_aligned(name),
})
}
fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result<String> {
@@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(name, SymbolRegistration::CENTER);
d.clear_symbol_export_type(name);
d.set_symbol_nine_slice(name, None);
d.set_symbol_pixel_aligned(name, false);
if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) {
d.unknown.remove(CURRENT_SYMBOL);
}
@@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let reg = d.symbol_registration(&name);
let export = d.symbol_export_type(&name);
let nine = d.symbol_nine_slice(&name);
let pixel = d.symbol_pixel_aligned(&name);
s.edit("Duplicate Symbol", |d, _| {
let art = d.reid(&sym.art);
d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) });
@@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
d.set_symbol_registration(&new, reg);
d.set_symbol_export_type(&new, export);
d.set_symbol_nine_slice(&new, nine);
d.set_symbol_pixel_aligned(&new, pixel);
Ok(())
})?;
Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) }))
+2 -2
View File
@@ -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), 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)}",
"{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 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), 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
),
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
@@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
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")))?;
// Each id in `through` is an edge of the group, given once.
let group_edges: std::collections::HashSet<NodeId> = b::edges(n).iter().map(|e| e.id).collect();
let mut seen = std::collections::HashSet::new();
if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) {
return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice")));
}
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
+11 -4
View File
@@ -173,7 +173,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clipboard Formats",
[],
None,
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut",
"{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); under read roots, SVG and its markup as text are left out when clipboard.exportSvg would refuse; the app publishes them on Copy and Cut",
always,
flavours
),
@@ -369,13 +369,20 @@ impl Session {
/// The MIME types of [`Self::clipboard_flavours`], without making them.
pub fn clipboard_flavour_types(&self) -> Vec<&'static str> {
self.clipboard.flavour_types(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
self.clipboard.flavour_types(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
}
/// What Copy offers other apps, best first (see `clipboard.flavours`): [`Clipboard::flavours`]
/// by the Clipboard Handling preferences.
/// by the Clipboard Handling preferences, without the SVG (and the SVG markup as text) that
/// [`Self::clipboard_svg_refused`] withholds from the caller asking now.
pub fn clipboard_flavours(&self) -> Vec<Flavour> {
self.clipboard.flavours(self.prefs.copy_as_svg, self.prefs.copy_as_pdf)
self.clipboard.flavours(self.clipboard_svg_offered(), self.prefs.copy_as_pdf)
}
/// Does Copy offer the SVG: Include SVG Code is on and the SVG is not withheld from the caller
/// asking now.
fn clipboard_svg_offered(&self) -> bool {
self.prefs.copy_as_svg && !self.clipboard_svg_refused()
}
/// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first
+8 -1
View File
@@ -766,6 +766,8 @@ pub struct SymbolOptions {
pub export_type: SymbolExportType,
/// 9-slice guides (`None`: 9-slice scaling off).
pub nine_slice: Option<SymbolNineSlice>,
/// Align to Pixel Grid.
pub pixel_aligned: bool,
}
impl SymbolOptions {
@@ -776,6 +778,7 @@ impl SymbolOptions {
registration: d.symbol_registration(name),
export_type: d.symbol_export_type(name),
nine_slice: d.symbol_nine_slice(name),
pixel_aligned: d.symbol_pixel_aligned(name),
}
}
@@ -785,6 +788,7 @@ impl SymbolOptions {
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
d.set_symbol_nine_slice(name, self.nine_slice);
d.set_symbol_pixel_aligned(name, self.pixel_aligned);
}
}
@@ -1035,10 +1039,13 @@ impl Imported {
self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone());
}
}
/// Point a pasted copy at the document's resources.
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
}
}
+12 -1
View File
@@ -221,6 +221,8 @@ pub(crate) struct Recolor<'a> {
patterns: HashMap<String, Option<String>>,
new_images: Vec<(String, ImageBlob)>,
new_patterns: Vec<PatternDef>,
/// Objects inside the recolored ones that keep their colors, with everything inside them.
skip: HashSet<NodeId>,
changed: usize,
}
@@ -236,6 +238,7 @@ impl<'a> Recolor<'a> {
patterns: HashMap::new(),
new_images: vec![],
new_patterns: vec![],
skip: HashSet::new(),
changed: 0,
}
}
@@ -254,7 +257,7 @@ impl<'a> Recolor<'a> {
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, ..Self::new(self.scope, self.f) }
Self { links: self.links, gray_images: self.gray_images, remake: self.remake, skip: self.skip.clone(), ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
@@ -440,12 +443,20 @@ impl ColorVisitor for Visit<'_, '_> {
fn image(&mut self, key: &str) -> Option<String> {
self.pass.image(self.d, key)
}
fn enters(&mut self, n: &Node) -> bool {
!self.pass.skip.contains(&n.id)
}
}
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
}
/// [`recolor`] that leaves the objects `skip` inside the recolored ones, and everything inside them, as they are.
pub(crate) fn recolor_except(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, skip: HashSet<NodeId>) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { skip, ..Recolor::new(Scope::of(p, cmd)?, f) })
}
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
+21 -3
View File
@@ -26,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
has_doc,
ellipse
),
@@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
}
/// The most anchors `shape.ellipse` draws, as many as a polygon's sides.
const MAX_ELLIPSE_ANCHORS: u64 = 1000;
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
let r = rect_of(p, "shape.ellipse")?;
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0))
// One message for every number that is not a whole count in range (a fraction, a negative,
// 0, 1, too many); a value that is not a number gets `number_or`'s.
let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS);
let n = number_or(p, key, 4.0, "shape.ellipse")?;
if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) {
return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})")));
}
let x = n as u64;
let xf = rect_transform(r, p, "shape.ellipse")?;
let rotation = f64_or(p, "rotation", 0.0);
if x != 4 {
// Another count is a plain path: a live ellipse always has 4 anchors.
let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf);
return add_art_turned(s, "Ellipse", path_kind(path, None), rotation);
}
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf };
add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation)
}
/// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or
+6 -7
View File
@@ -631,13 +631,12 @@ impl LiquifyStroke {
}
let msg = (!ids.is_empty()).then(|| {
let n = ids.len();
format!(
"{} left {n} object{} under the brush as {} ({}): it reshapes paths only",
self.prm.kind.label(),
if n == 1 { "" } else { "s" },
if n == 1 { "it was" } else { "they were" },
kinds.join(", ")
)
let (tool, kinds) = (self.prm.kind.label(), kinds.join(", "));
if n == 1 {
format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only")
} else {
format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only")
}
});
(ids, msg)
}
+27
View File
@@ -270,6 +270,33 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
super::fileinfo::file_info
),
cmd!(
"file.info.saveTemplate",
"Save Metadata Template…",
[],
None,
"{name?: save into the metadata templates folder as <name>.xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither",
has_doc,
super::fileinfo::save_template
),
cmd!(
"file.info.applyTemplate",
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
cmd!(
query "file.info.templates",
"Metadata Templates",
[],
None,
"{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}",
super::always,
super::fileinfo::templates
),
]
}
+1 -1
View File
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eraser",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
has_doc,
erase_region
),
+76 -6
View File
@@ -3,9 +3,10 @@ use super::common::{
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
};
use super::{
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session,
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
};
use kurbo::{CubicBez, Line, PathSeg};
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
use vectorcraft_doc::StrokeLayer;
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
@@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
/// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment
/// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least
/// `step` long is found.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<SubPath>> {
/// `step` long is found, and also at the parameters `extra` gives for it.
fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<SubPath>> {
let nseg = sp.segment_count();
if nseg == 0 {
return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]);
@@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot());
let wanted = (3.0 * edge / step).ceil();
let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K };
let mut ts: Vec<f64> = (1..=samples).map(|k| k as f64 / samples as f64).collect();
let more = extra(c);
if !more.is_empty() {
ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0));
ts.sort_by(f64::total_cmp);
ts.dedup();
}
let mut prev_t = 0.0;
let mut prev_rm = remove(c.eval(0.0));
let mut start = if prev_rm { None } else { Some(0.0) };
@@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
runs.push(std::mem::take(&mut cur));
}
}
for k in 1..=samples {
let t = k as f64 / samples as f64;
for t in ts {
let rm = remove(c.eval(t));
if rm != prev_rm {
let (mut lo, mut hi) = (prev_t, t);
@@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio
/// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output
/// object (one object per piece when the path had a single subpath), or None if unchanged.
pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option<Vec<PathData>> {
erase_outline_at(pd, step, remove, &|_| vec![])
}
/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it.
fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec<f64>) -> Option<Vec<PathData>> {
let mut changed = false;
let mut subs = vec![];
for sp in &pd.subpaths {
match cut_subpath(sp, step, remove) {
match cut_subpath(sp, step, remove, extra) {
Some(pieces) => {
changed = true;
subs.extend(pieces);
@@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "path.eraseRegion";
if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) {
if p.get("points").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "give `points` or `rect`, not both"));
}
return erase_rect(s, marquee_param(rect, C)?);
}
let samples = samples_param(p, "points", C)?;
let size = number_or(p, "size", 10.0, C)?;
if !(size.is_finite() && size > 0.0) {
@@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
apply_plan(s, "Eraser", plan)
}
/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a
/// height above 0.
fn marquee_param(v: &Value, cmd: &str) -> Result<Rect> {
const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0";
let n: Vec<f64> = match v.as_array() {
Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::<Option<_>>().ok_or_else(|| bad(cmd, SHAPE))?,
_ => return Err(bad(cmd, SHAPE)),
};
let [x, y, w, h] = [n[0], n[1], n[2], n[3]];
if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) {
return Err(bad(cmd, SHAPE));
}
Ok(Rect::new(x, y, x + w, y + h))
}
/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or
/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges.
fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
let region =
PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true));
let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1;
// An open path is sampled at least every half of the rectangle's shorter side, and also where
// each segment crosses the rectangle's edges and halfway between those crossings, so a stretch
// inside the rectangle is found however long the segment is.
let step = r.width().min(r.height()) / 2.0;
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
let crossings = |c: CubicBez| {
let mut ts: Vec<f64> = (0..4)
.flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4])))
.map(|x| x.segment_t)
.filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)
.collect();
ts.sort_by(f64::total_cmp);
let mids: Vec<f64> = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect();
ts.extend(mids);
ts
};
let st = s.doc()?;
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? {
if pd.is_closed() {
if po::area(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
continue;
}
plan.push((id, components(&po::boolean(&pd, rule, &region, FillRule::NonZero, BoolOp::Difference))));
} else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) {
plan.push((id, pieces));
}
}
apply_plan(s, "Eraser", plan)
}
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
/// `sizeMode`.
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
+64 -13
View File
@@ -117,11 +117,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
let mut spans = [reach, 2.0 * reach];
// The lengths along the path ahead and back, measured once when an anchor needs them.
let (mut ahead, mut back) = (None, None);
if closed {
let mut total = 0.0;
for i in 0..n {
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
}
let total = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach)).first().map_or(0.0, |lens| lens.iter().take(n).sum());
if !(total.is_finite() && total > 0.0) {
return corners;
}
@@ -137,8 +136,10 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
continue;
}
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
let back = back.get_or_insert_with(|| walk_blocks(anchors, closed, false, reach));
let [Some(back_near), Some(back_far)] = spans.map(|r| point_along(anchors, closed, (i, false), r, back, reach)) else { continue };
let ahead = ahead.get_or_insert_with(|| walk_blocks(anchors, closed, true, reach));
let [Some(ahead_near), Some(ahead_far)] = spans.map(|r| point_along(anchors, closed, (i, true), r, ahead, reach)) else { continue };
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
.into_iter()
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
@@ -146,9 +147,54 @@ fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
corners
}
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
/// anchor on a path of very many very short segments.
const MAX_CORNER_WALK: usize = 256;
/// The lengths [`walk`] measures along the segments of `anchors`, in the order a walk ahead
/// (`forward`) or back passes them, twice round, starting at the first anchor ahead or the last
/// anchor back, and added up in blocks: element `l` holds the lengths of each run of 2^`l`
/// segments that starts at a multiple of 2^`l`. Each block adds up only its own segments, so a short
/// stretch keeps its length next to very long ones. The segment past an open path's end has no
/// length.
fn walk_blocks(anchors: &[Anchor], closed: bool, forward: bool, reach: f64) -> Vec<Vec<f64>> {
let n = anchors.len();
let lens: Vec<f64> =
(0..n).map(|k| walk(anchors, closed, (if forward { k } else { n - 1 - k }, forward), [f64::INFINITY; 2], reach, 1).1).collect();
let mut blocks = vec![(0..2 * n).map(|k| lens[k % n]).collect::<Vec<f64>>()];
while let Some(last) = blocks.last().filter(|b| b.len() > 1) {
let next = last.as_chunks::<2>().0.iter().map(|[a, b]| a + b).collect();
blocks.push(next);
}
blocks
}
/// The point `dist` along the path `anchors` from anchor `from.0`, ahead when `from.1` and back
/// otherwise, as [`walk`] finds it: an open path's end for a distance beyond the end, and `None`
/// when a length is not a number or is too large to add. The walk skips whole blocks of `blocks`
/// ([`walk_blocks`] in the same direction) that end no more than `dist` along the path, so a path of
/// very many short segments is not walked one segment at a time from each anchor.
fn point_along(anchors: &[Anchor], closed: bool, from: (usize, bool), dist: f64, blocks: &[Vec<f64>], reach: f64) -> Option<Point> {
let (n, (i, forward)) = (anchors.len(), from);
let start = if forward { i } else { n - 1 - i };
let end = start
+ if closed {
n
} else if forward {
n - 1 - i
} else {
i
};
let (mut pos, mut gone) = (start, 0.0);
// The largest block that starts at `pos`, stays within the walk and ends within `dist`, until
// none does; a block whose length is not a number is never skipped.
while let Some((size, len)) = blocks.iter().enumerate().rev().find_map(|(l, lens)| {
let size = 1usize << l;
let len = lens.get(pos >> l).copied()?;
(pos % size == 0 && pos + size <= end && gone + len <= dist).then_some((size, len))
}) {
pos += size;
gone += len;
}
let at = if forward { pos % n } else { n - 1 - pos % n };
walk(anchors, closed, (at, forward), [(dist - gone).max(0.0); 2], reach, n).0[0]
}
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
/// past no more than `segments` segments, measured along the lines between each curved segment's
@@ -1099,11 +1145,12 @@ mod tests {
}
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
/// over that reach.
/// of 10 pt, and of 300 pt, where twice the reach passes the bump's 566 segments on each side, its
/// top is a corner, and with a reach of 1,000 pt its top is not one, as the path turns by about 51°
/// over that reach. The turns into and between 1 pt segments that follow two segments 1e16 pt long
/// are corners too.
#[test]
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
fn a_bump_of_many_short_segments_is_a_corner_where_it_turns_over_the_reach() {
let side = 400.0 * std::f64::consts::SQRT_2;
let steps = side.ceil() as usize;
let mut pts = vec![(-3000.0, 0.0)];
@@ -1120,6 +1167,10 @@ mod tests {
let top = steps + 1;
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
assert!(smooth_corners(&anchors, false, 10.0)[top]);
assert!(smooth_corners(&anchors, false, 300.0)[top]);
let long = polyline(&[(0.0, 0.0), (1e16, 0.0), (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 2.0)]);
let corners = smooth_corners(&long, false, 0.5);
assert!(corners[2] && corners[3] && corners[4], "{corners:?}");
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
}
+1 -1
View File
@@ -179,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
+56 -27
View File
@@ -978,15 +978,18 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
/// id): those made from its own fills and strokes, or with `all` every member. The other members
/// that repeat an id ([`repeats_an_id`]) and hold a random Transform effect ([`has_seeded`]) are
/// expanded as well ([`expand_in_place`]). Then the members get ids of their own. Random in a
/// Transform effect takes its seed from the id, and the canvas draws the pieces with the ids they
/// have before that. Returns what each of those other members' expansions lists, by the member's
/// new id.
/// expanded as well ([`expand_in_place`]), except the objects `skip` lists. Then the members get ids
/// of their own. Random in a Transform effect takes its seed from the id, and the canvas draws the
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
/// the member's new id.
fn expand_pieces(
d: &mut Document,
m: &mut Node,
all: bool,
brushes: &[vectorcraft_brush::Brush],
skip: &[NodeId],
kept: &mut Vec<NodeId>,
stroke_art: effects::StrokeArt,
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
let id = m.id;
@@ -1002,9 +1005,23 @@ fn expand_pieces(
if all || c.id == id {
effects::expand_art(d, c, stroke_art);
} else if has_seeded(c) && repeats_an_id(c, &seen) {
listed = Some(expand_in_place(d, c, brushes));
listed = Some(expand_in_place(d, c, brushes, skip));
}
let mut was = vec![];
if !skip.is_empty() {
c.walk(&mut |n| was.push(n.id));
}
fresh_ids_listed(d, c, &mut seen, listed.as_deref_mut().unwrap_or_default());
if !was.is_empty() {
// A copy of an object `skip` lists is left as it is too.
let mut at = 0;
c.walk(&mut |n| {
if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) {
kept.push(n.id);
}
at += 1;
});
}
if let Some(listed) = listed {
expanded.insert(c.id, listed);
}
@@ -1058,9 +1075,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
type Listed = (NodeId, usize);
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush]) -> Vec<Listed> {
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
let mut listed = vec![];
if let Some(e) = expanded_node(d, c.clone(), brushes, &mut listed) {
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
*c = e;
}
listed
@@ -1084,9 +1101,16 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
/// transparency.
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
expand_node_except(d, id, brushes, &[], out);
}
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
/// copies of it that such an effect makes are left as they are too.
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
let Some(n) = d.node(id).cloned() else { return };
let mut listed = vec![];
let m = expanded_node(d, n, brushes, &mut listed);
let m = expanded_node(d, n, brushes, skip, &mut listed);
out.extend(listed.into_iter().map(|(id, _)| id));
if let Some(mut m) = m {
// Art made from type takes its emoji's pixels into the document.
@@ -1099,10 +1123,10 @@ pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_b
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
/// of the expanded `n`, `n`'s first when its own does.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<Listed>) -> Option<Node> {
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
let id = n.id;
if !expandable(&n) {
if skip.contains(&id) || !expandable(&n) {
return None;
}
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
@@ -1139,7 +1163,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
let c = Arc::make_mut(c);
if i == 0 {
expanded = expand_in_place(d, c, brushes);
expanded = expand_in_place(d, c, brushes, skip);
fresh_ids_listed(d, c, &mut seen, &mut expanded);
} else {
effects::fresh_ids(d, c, &mut seen);
@@ -1169,6 +1193,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st);
// Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists.
let mut members = std::collections::HashMap::new();
// New ids of the copies of objects `skip` lists among those members.
let mut kept = vec![];
let expanded = match image {
// Blur, feather and inner glow change the object itself: it becomes the image (a layer
// keeps it as its only member).
@@ -1180,7 +1206,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
} else if container {
// A group's or layer's own fills and strokes become art among its members.
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
members = expand_pieces(d, &mut m, false, brushes, &mut stroke_art);
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
m
})
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
@@ -1201,7 +1227,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
m
})
};
@@ -1223,6 +1249,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
}
}
if container {
let skip = if kept.is_empty() { std::borrow::Cow::Borrowed(skip) } else { std::borrow::Cow::Owned([skip, &kept].concat()) };
// The place of each member in the walk of `n`: after `n` and the members before it.
let mut at = 1;
for c in n.children_mut().into_iter().flatten() {
@@ -1235,7 +1262,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
match members.remove(&c.id) {
Some(listed) => out.extend(listed),
None => {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, out) {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
*c = Arc::new(e);
changed = true;
}
@@ -1280,9 +1307,20 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
// geometry it hasn't changed.
if vectorcraft_plugins::safe_mode::active() {
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
// series.
// series, unless an effect of a group around it, the selected graph or series group or one inside it, draws it
// with that group: an effect of the group's own, or a raster effect of one of its fills or strokes (the group
// then becomes an image of all of it).
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
let designs = super::appearance::design_art_in(&d, &roots);
let draws_members = |g: &Node| g.appearance.effects.iter().any(|e| e.visible) || !rasterfx::raster_fx(g).is_empty();
let designs: Vec<NodeId> = super::appearance::design_art_in(&d, &roots)
.into_iter()
.filter(|art| {
!d.ancestry(*art).is_some_and(|up| {
let from = up.iter().position(|a| roots.contains(a)).unwrap_or(up.len());
up.get(from..up.len().saturating_sub(1)).is_some_and(|around| around.iter().filter_map(|a| d.node(*a)).any(draws_members))
})
})
.collect();
if !designs.is_empty() {
let view = d.to_mut();
for id in designs {
@@ -1313,16 +1351,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = vec![];
let threaded = super::threads::frames(d);
for id in &roots {
expand_node(d, *id, &brushes, &mut out);
}
for id in &designs {
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
*slot = was.clone();
}
}
if !designs.is_empty() {
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
expand_node_except(d, *id, &brushes, &designs, &mut out);
}
super::dimension::put_back(d, lifted);
// A dimension whose source was replaced stays where it was, no longer linked.
+321 -13
View File
@@ -3,14 +3,28 @@
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
//!
//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file
//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File
//! Info, and `file.info.templates` lists those in the metadata templates folder.
use serde_json::{Map, Value, json};
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document};
use super::{Result, Session, bad};
use super::{Result, Session, bad, switch_or, text_param};
const C: &str = "file.info";
const SAVE: &str = "file.info.saveTemplate";
const APPLY: &str = "file.info.applyTemplate";
const LIST: &str = "file.info.templates";
/// The extension of a metadata template file.
const TEMPLATE_EXT: &str = "xmp";
/// The most templates `file.info.templates` lists.
const MAX_LISTED: usize = 1000;
/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate`
/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB.
const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES;
/// Longest text field, in characters.
const MAX_TEXT: usize = 65_536;
/// Longest keyword, in characters.
@@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
/// What `file.info` reports (and takes back).
pub(crate) fn info_json(d: &Document) -> Value {
let m = &d.metadata;
info_json_with(d, d.info_title(), &d.metadata)
}
/// [`info_json`] with the title `title` and the metadata `m` in place of the document's.
fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value {
json!({
"title": d.info_title(),
"title": title,
"author": m.author,
"authorTitle": m.author_title,
"description": m.description,
@@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
Value::Object(o) => o,
_ => return Err(bad(C, "params must be an object")),
};
let (title, m) = edited(s, Some(o))?;
commit(s, title, m)?;
Ok(info_json(&s.doc()?.doc))
}
/// The active document's File Info title and metadata with `fields` (as `file.info` takes them)
/// applied.
fn edited(s: &Session, fields: Option<&Map<String, Value>>) -> Result<(String, DocMetadata)> {
let d = &s.doc()?.doc;
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
for (k, v) in o {
for (k, v) in fields.into_iter().flatten() {
apply(&mut title, &mut m, k, v)?;
}
Ok((title, m))
}
/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when
/// they are what it has. Whether anything changed.
fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result<bool> {
let d = &s.doc()?.doc;
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
// offer it where the document has no file), and replaces the one its file gave.
@@ -60,16 +92,290 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
if retitled {
m.title = None;
}
if retitled || m != d.metadata {
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
if !retitled && m == d.metadata {
return Ok(false);
}
Ok(info_json(&s.doc()?.doc))
s.edit("File Info", |d, _| {
if retitled {
d.title = title;
}
d.metadata = m;
Ok(())
})?;
Ok(true)
}
/// The optional object `p` gives for `key`.
fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result<Option<&'a Map<String, Value>>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Object(o)) => Ok(Some(o)),
Some(_) => Err(bad(c, format!("`{key}` must be an object"))),
}
}
impl Session {
/// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the
/// metadata templates in the folder `dir`, which a save makes when it is missing.
pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) {
self.metadata_templates_dir = Some(dir);
}
/// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web,
/// which has no folders.
pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> {
self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
}
/// The metadata template of the File Info `title` and `m`: each field that has a value, the title
/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up.
fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo {
let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string());
vectorcraft_pdf::FileInfo {
title: super::fileio::is_own_title(title).then(|| title.to_string()),
author: text(&m.author),
author_title: text(&m.author_title),
description: text(&m.description),
keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()),
rating: (m.rating > 0).then_some(m.rating),
copyright_notice: text(&m.copyright_notice),
copyright_url: text(&m.copyright_url),
copyrighted: match m.copyright_status {
CopyrightStatus::Copyrighted => Some(true),
CopyrightStatus::PublicDomain => Some(false),
CopyrightStatus::Unknown => None,
},
..Default::default()
}
}
/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with
/// [`TEMPLATE_EXT`].
fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() {
return Err(bad(c, "the template name can't be empty"));
}
Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned())
}
/// The error for a template over [`MAX_TEMPLATE_FILE`].
fn too_big(c: &str) -> crate::EngineError {
bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20))
}
/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`.
pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result<Value> {
let name = text_param(p, "name", SAVE)?;
let path = text_param(p, "path", SAVE)?;
let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?;
let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m));
if xmp.len() > MAX_TEMPLATE_FILE {
return Err(too_big(SAVE));
}
match (name, path) {
(Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")),
(Some(name), None) => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf();
let path = template_path(&dir, name, SAVE)?;
// The name is the file name as it is, so two names never share a file.
let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned());
if listed.as_deref() != Some(name.trim()) {
return Err(bad(SAVE, "the template name isn't usable as a file name"));
}
// Only a file in the folder itself is replaced: a link there is not followed.
if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
let dir = dir.to_string_lossy().into_owned();
// The app's own folder, under a name checked above: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?;
Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) }))
}
(None, Some(path)) => {
super::fileio::write_file(path, xmp.as_bytes())?;
Ok(json!({ "path": path }))
}
(None, None) => Ok(json!({ "data": xmp })),
}
}
/// How `file.info.applyTemplate` merges a template's fields into the File Info.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Merge {
/// Clear the fields a template can hold, then take the template's.
Replace,
/// Keep the fields, and take each one the template gives.
Keep,
/// Keep the fields: add the template's keywords, and take its other fields only where the File
/// Info has none.
Append,
}
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
let mode = match text_param(p, "mode", APPLY)? {
Some("replace") => Merge::Replace,
Some("keep") => Merge::Keep,
Some("append") => Merge::Append,
_ => return Err(bad(APPLY, "mode must be replace, keep or append")),
};
let apply = switch_or(p, "apply", true, APPLY)?;
let base = fields_param(p, "base", APPLY)?;
let bytes = template_bytes(s, p)?;
let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?;
let (mut title, mut m) = edited(s, base)?;
merge(&mut title, &mut m, t, mode);
if !apply {
return Ok(info_json_with(&s.doc()?.doc, &title, &m));
}
let changed = commit(s, title, m)?;
let mut out = info_json(&s.doc()?.doc);
out["changed"] = json!(changed);
Ok(out)
}
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
// At most one byte past the limit is read, so a huge file is never read whole.
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
let bytes = match given {
[Some(path), None, None] => read(path)?,
[None, Some(name), None] => {
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
let mut path = template_path(dir, name, APPLY)?;
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
// the extension in lowercase, then in other letter case. Only files in the folder itself
// are listed: a link there is not followed.
let name = name.trim();
let own = format!("{name}.{TEMPLATE_EXT}");
let listed = template_files(dir)
.filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name))
.min_by_key(|f| (f != name, *f != own));
if let Some(file) = listed {
path = dir.join(file).to_string_lossy().into_owned();
} else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) {
// A name that is not a file name as it is never opens another template.
return Err(bad(APPLY, "the template name isn't usable as a file name"));
}
let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file());
if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) {
return Err(crate::EngineError::Other(format!("{path}: not a file")));
}
// The app's own folder: no root applies.
crate::file_access::unconfined(|| read(&path))?
}
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
[None, None, Some(data)] => data.as_bytes().to_vec(),
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
};
if bytes.len() > MAX_TEMPLATE_FILE {
return Err(too_big(APPLY));
}
Ok(bytes)
}
/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as
/// `file.info` would take it; a value it would refuse is left out.
fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) {
if mode == Merge::Replace {
// The title is never cleared: a document always has one.
m.author.clear();
m.author_title.clear();
m.description.clear();
m.keywords.clear();
m.rating = 0;
m.copyright_status = CopyrightStatus::Unknown;
m.copyright_notice.clear();
m.copyright_url.clear();
}
let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("title", t.title.map(Value::from)),
("author", t.author.map(Value::from)),
("authorTitle", t.author_title.map(Value::from)),
("description", t.description.map(Value::from)),
("keywords", t.keywords.map(Value::from)),
("rating", t.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", t.copyright_notice.map(Value::from)),
("copyrightUrl", t.copyright_url.map(Value::from)),
];
for (k, v) in fields {
let Some(mut v) = v else { continue };
if mode == Merge::Append {
let empty = match k {
"title" => !super::fileio::is_own_title(title),
"author" => m.author.is_empty(),
"authorTitle" => m.author_title.is_empty(),
"description" => m.description.is_empty(),
"rating" => m.rating == 0,
"copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown,
"copyrightNotice" => m.copyright_notice.is_empty(),
"copyrightUrl" => m.copyright_url.is_empty(),
_ => true,
};
if !empty {
continue;
}
if k == "keywords" {
let mut all: Vec<Value> = m.keywords.iter().cloned().map(Value::from).collect();
all.extend(v.as_array().cloned().unwrap_or_default());
v = Value::from(all);
}
}
// `apply` changes the field only when it takes the value.
let _ = apply(title, m, k, &v);
}
}
/// The file names of the templates in the folder `dir`: its files with a name before the
/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made
/// yet holds none.
fn template_files(dir: &std::path::Path) -> impl Iterator<Item = String> {
std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty()))
}
/// `file.info.templates {create?}`: the metadata templates in the folder, by name.
pub(crate) fn templates(s: &mut Session, p: &Value) -> Result<Value> {
let create = switch_or(p, "create", false, LIST)?;
let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else {
return Ok(json!({ "templates": [] }));
};
if create {
// The app's own folder: no root applies.
crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?;
}
// The first [`MAX_LISTED`] by name, with no more than that many held at once.
let mut files = std::collections::BTreeSet::new();
for file in template_files(std::path::Path::new(&dir)) {
files.insert(file);
if files.len() > MAX_LISTED {
files.pop_last();
}
}
let list: Vec<Value> = files
.iter()
.filter_map(|file| {
let (stem, _) = file.rsplit_once('.')?;
let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned();
Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) }))
})
.collect();
let mut out = json!({ "templates": list });
if super::fileio::shown_path(&dir) == dir.as_str() {
out["folder"] = json!(dir);
}
Ok(out)
}
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
@@ -79,8 +385,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
let fields = [
("author", f.author.map(Value::from)),
("authorTitle", f.author_title.map(Value::from)),
("description", f.description.map(Value::from)),
("keywords", f.keywords.map(Value::from)),
("rating", f.rating.map(Value::from)),
("copyrightStatus", status.map(|s| Value::from(s.id()))),
("copyrightNotice", f.copyright_notice.map(Value::from)),
("copyrightUrl", f.copyright_url.map(Value::from)),
+1 -1
View File
@@ -39,7 +39,7 @@ pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note};
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
mod heifread;
mod hpgl;
mod jp2read;
+18 -10
View File
@@ -149,7 +149,9 @@ pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
/// and symbol editing layers never, opacity masks not with SVG Tiny 1.2, and objects with effects
/// SVG has no filters for as the images the file draws of them), of the art the file draws for each
/// placed document, and of the symbols, patterns and brushes that art uses; with
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
/// and each data set's image. The error names no file or folder.
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
@@ -162,21 +164,27 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
return Ok(());
}
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
// layers kept: the encoder refuses them anyway.
let (link, preserve, hidden) = match super::svg::options_map(p) {
// Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden
// layers kept and SVG 1.1: the encoder refuses them anyway.
let (link, preserve, hidden, tiny) = match super::svg::options_map(p) {
Ok(m) => {
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
let tiny = m.get("profile").and_then(Value::as_str) == Some("tiny12");
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"), tiny)
}
Err(_) => (true, true, true),
Err(_) => (true, true, true, false),
};
// The opacity-mask and symbol editing layers are never written.
let d = &*d.without_edit_modes();
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
if preserve && crate::cmd::links::names_hidden_file(d, base)
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
{
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden, tiny);
// The SVG draws the objects with effects it has no filters for as images of them, as the
// encoder and the clipboard prepare them.
let drawing_names = || {
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(d, !tiny);
let d = flat.as_ref().unwrap_or(d);
names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
};
if preserve && crate::cmd::links::names_hidden_file(d, base) || names(d) && drawing_names() {
return Err(bad(cmd, IMAGE_OUTSIDE));
}
Ok(())
File diff suppressed because one or more lines are too long
+9 -3
View File
@@ -199,8 +199,12 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
/// out, at any depth of layers, sublayers and groups that don't clip, unless what the renderer
/// draws for them, their effects included ([`vectorcraft_render::effect_bounds`]), reaches it.
/// Objects that reach it stay whole (the file's bounds clip them), as DXF's crop leaves them.
/// Symbol instances are measured by their art, and the box of one whose art holds brushed strokes
/// grows by as far as their brush art can paint ([`SymbolBoxes::with_brush_art`]). An object that
/// Both boxes grow by the room brush art can paint past the brushed strokes of the object and of
/// the objects in it ([`vectorcraft_brush::reach_within`]: a clipping group or layer by its clipping
/// path's, a compound path by its own strokes'), so a brushed path just off `rect` stays when its
/// brush art reaches it. Symbol instances are measured by their art, and the box of one whose art
/// holds brushed strokes grows by as far as their brush art can paint
/// ([`SymbolBoxes::with_brush_art`]). An object that
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
@@ -233,7 +237,9 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
let mut holds_instance = false;
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
let reach = vectorcraft_brush::reach_within(n);
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
}
let symbols = doc.symbol_boxes().with_brush_art();
let mut d = doc.clone();
+57 -8
View File
@@ -73,8 +73,10 @@ pub struct RasterImage {
pub height: u32,
/// The resolution the file declares (see [`super::ppi::resolution`]).
pub ppi: Option<(f64, f64)>,
/// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]).
pub clip: Option<vectorcraft_geom::PathData>,
/// The clipping path its file draws it through, in the image's pixel space, with its fill rule:
/// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd,
/// [`psdread::clipping_path`]).
pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>,
}
pub(super) fn err(e: impl std::fmt::Display) -> EngineError {
@@ -894,12 +896,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
@@ -942,7 +951,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA.
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
/// names ([`png_with_clip`]).
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
@@ -950,7 +960,8 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
}
if psdread::is_psd(bytes) {
let cms = vectorcraft_color::cms::active();
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi);
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
}
if jxlread::is_jxl(bytes) {
let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?;
@@ -1118,10 +1129,48 @@ fn stored(bytes: Vec<u8>, mime: &'static str, (width, height): (u32, u32), ppi:
Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None })
}
/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from
/// ([`png_with_clip`]).
const CLIP_KEYWORD: &str = "VectorCraft clip";
/// Longest clipping path a PNG keeps (bytes of its JSON).
const MAX_PNG_CLIP: usize = 16 << 20;
/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the
/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the
/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is
/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped.
fn png_with_clip(mut img: RasterImage, clip: Option<vectorcraft_geom::PathData>) -> RasterImage {
let Some(clip) = clip else { return img };
let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img };
let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]);
img.blob = ImageBlob::new("image/png", png);
img.key = img.blob.content_key();
img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd));
img
}
/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel
/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path
/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data.
pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
return None;
}
let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat();
let json = super::ppi::png_chunks(png)
.take_while(|(ty, _)| *ty != b"IDAT")
.find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?;
if json.len() > MAX_PNG_CLIP {
return None;
}
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?;
let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?;
let (sx, sy) = crate::cmd::place::pt_per_px(ppi);
let mut d = Document::new(width as f64 * sx, height as f64 * sy);
let layer = d.layers[0].id;
@@ -1131,7 +1180,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
id,
NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })),
);
let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes));
let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path));
n.name = Some(name.to_string());
d.images.insert(key, blob);
d.insert(Some(layer), 0, n).map_err(err)?;
File diff suppressed because one or more lines are too long
+44 -6
View File
@@ -87,8 +87,9 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let one_after_another = records_one_after_another(Reader::new(r.rest()), count, *budget);
let mut out = vec![];
for _ in 0..count {
for i in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
@@ -116,9 +117,10 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
// doesn't start one is the next slice. When the records follow one another, only the
// last one may be followed by a descriptor. A descriptor read that uses up the budget is
// an error.
if (!one_after_another || i + 1 == count) && r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
@@ -139,6 +141,37 @@ fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, St
Ok(out)
}
/// Whether `r` holds `count` version 6 records one after another, followed by nothing or by one
/// descriptor (version 16) that reads within `budget`, as ag-psd writes them. A record whose ID is
/// 16 then isn't taken for a descriptor. Otherwise each record may be followed by a descriptor.
fn records_one_after_another(mut r: Reader<'_>, count: usize, mut budget: usize) -> bool {
if !(0..count).all(|_| skip_record(&mut r).is_ok()) {
return false;
}
r.rest().is_empty() || (r.rest().starts_with(&16u32.to_be_bytes()) && r.u32().is_ok() && descriptor(&mut r, 0, &mut budget).is_ok())
}
/// Reads past the version 6 record `r` starts with, in the layout [`version_6`] reads. Its strings
/// are checked and read past without being decoded.
fn skip_record(r: &mut Reader<'_>) -> Result<(), String> {
// The ID and group ID.
r.take(8)?;
if r.u32()? == 1 {
r.take(4)?;
}
units(r)?;
// The type and the rectangle.
r.take(20)?;
for _ in 0..4 {
units(r)?;
}
r.take(1)?;
units(r)?;
// The alignments and the background color.
r.take(12)?;
Ok(())
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
@@ -221,12 +254,17 @@ fn text_len(n: usize) -> Result<usize, String> {
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let bytes = units(r)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A Unicode string's units, as bytes: a count of UTF-16 units, then the units.
fn units<'a>(r: &mut Reader<'a>) -> Result<&'a [u8], String> {
let n = text_len(r.u32()? as usize)?;
r.take(n.checked_mul(2).ok_or(TRUNCATED)?)
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
@@ -414,6 +414,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() {
assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}");
}
/// A square saved as "Square" and the clipping path naming it.
fn square_resources() -> Vec<u8> {
let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
[resource(2000, b"Square", &square), clipping_name(b"Square")].concat()
}
/// `bytes` written as `name` in `dir`, by its path.
fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String {
let p = dir.join(name);
std::fs::write(&p, bytes).unwrap();
p.to_string_lossy().into_owned()
}
/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping
/// path its new file names, take that clip group's clipping path away when the new file names
/// none, and give it back when a later file names one again.
#[test]
fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip");
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let square = write_file(&dir, "square.psd", &red_psd(&square_resources()));
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]];
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap());
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)));
s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path");
s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap();
let d = &s.doc().unwrap().doc;
match d.node(group).map(|n| &n.kind) {
Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::<Vec<_>>(), [image]),
other => panic!("a plain group of the image: {other:?}"),
}
s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again");
// The file is saved again with another clipping path.
std::fs::write(&cut, red_psd(&square_resources())).unwrap();
s.execute("links.update", &json!({"ids": [image]})).unwrap();
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a
/// text chunk within the size limit that reads as a path gives one back.
#[test]
fn the_kept_png_holds_the_clipping_path_within_bounds() {
let img = raster_image(&red_psd(&triangle_resources())).unwrap();
let (path, rule) = img.clip.clone().expect("the file's clipping path");
assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd);
assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path));
let plain = raster_image(&red_psd(&[])).unwrap();
assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none());
let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]);
assert_eq!(super::load::png_clip(&with("not a path".into())), None);
assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read");
}
/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that
/// path, under the even-odd rule; a clipping mask made in the document stays around it.
#[test]
fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() {
let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain");
let plain = write_file(&dir, "plain.psd", &red_psd(&[]));
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap();
let image = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let group = d.parent_of(image).expect("a clip group");
assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image));
// The clipping path's fill rule changed in the document makes it the document's own mask: a
// relink keeps it and puts the file's clip group inside it.
let clip = match d.node(group).map(|n| &n.kind) {
Some(NodeKind::Group { children, .. }) => children[0].id,
other => panic!("{other:?}"),
};
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) {
*rule = vectorcraft_geom::FillRule::NonZero;
}
s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap();
let d = &s.doc().unwrap().doc;
let inner = d.parent_of(image).unwrap();
assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group");
assert!(clip_group(d, inner).1, "the file's clip group is even-odd");
}
#[test]
fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() {
let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
@@ -262,6 +262,32 @@ fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
assert_eq!(names, ["a", "b"]);
}
#[test]
fn a_version_6_record_whose_id_is_16_is_a_slice_not_a_descriptor() {
// The 16th record has ID 16, group ID 0, origin 2, no name and the Image type: its first 18
// bytes also read as a descriptor of version 16 with no items.
let records: Vec<S> = (1..=17).map(|id| if id == 16 { user("", [1, 1, 4, 4]) } else { user("a", [0, 0, 5, 5]) }).collect();
let descriptor_after = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
for trailing in [vec![], descriptor_after] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 17, "{got:?}");
assert_eq!((got[15].0, got[15].1.name.as_str()), (Rect::new(1.0, 1.0, 4.0, 4.0), ""));
assert_eq!(got[16].1.name, "a");
}
// A descriptor after each record whose class ID is four zero bytes, with no items, followed by
// records with no strings: the records don't also read one after another.
let empty = [ustr(""), 0u32.to_be_bytes().to_vec(), vec![0; 4], 0u32.to_be_bytes().to_vec()].concat();
let trailing = [16u32.to_be_bytes().to_vec(), empty].concat();
for rect in [[0, 0, 0, 0], [0, 0, 5, 5]] {
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&[user("", rect), user("", rect), user("", rect)], &trailing)), json!({}));
let w = warnings(&r);
assert!(!w.iter().any(|w| w.starts_with("the slices can't be read")), "{w:?}");
assert_eq!(slices(&s).len(), if rect[2] > 0 { 3 } else { 0 }, "{w:?}");
}
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
@@ -475,8 +501,13 @@ fn damaged_slices_never_panic() {
let mut f = base.clone();
f[at] = v;
let mut s = Session::new();
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
// The engine's guard reports a panic as an internal error.
for r in [
s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})),
s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})),
] {
assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "byte {at} set to {v}: {r:?}");
}
}
}
}
@@ -1,7 +1,10 @@
//! SVG encodings, profiles and embedded fonts through the engine: the options reach the file,
//! files in each encoding open again, and `document.serialize` reads them as text.
use std::sync::Arc;
use serde_json::json;
use vectorcraft_doc::Document;
use super::*;
@@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() {
assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard");
}
/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its
/// artboard.
fn nib_doc() -> (Document, f64) {
let mut d = Document::new(100.0, 100.0);
let mut lib = vectorcraft_brush::library(&d);
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else {
panic!("the 3 pt. Round brush")
};
c.size = 20.0;
vectorcraft_brush::store(&mut d, &lib);
let x0 = d.artboards[0].rect.x0;
(d, x0)
}
/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of
/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line.
fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node {
let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0);
if brushed {
look.stroke_mut().unwrap().brush = Some("3 pt. Round".into());
}
let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into());
vectorcraft_doc::Node::path(d.alloc_id(), line, look)
}
fn black() -> vectorcraft_color::Paint {
vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK)
}
/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that
/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not.
#[test]
fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() {
let (mut d, x0) = nib_doc();
let layer = d.layers[0].id;
let near = nib_line(&mut d, x0 - 5.0, black(), true);
let far = nib_line(&mut d, x0 - 200.0, black(), true);
let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap());
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard");
assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard");
let mut s = Session::new();
s.add_document(d, None);
let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap();
let svg = svg["text"].as_str().unwrap().to_string();
assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}");
let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap();
let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap();
assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped");
}
/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed
/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art
/// inside it, and a compound path is painted with its own appearance, not its paths': those stay
/// out when only brush art could reach the artboard.
#[test]
fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() {
use vectorcraft_doc::{LayerColor, Node, NodeKind};
let (mut d, x0) = nib_doc();
let layer = d.layers[0].id;
let x = x0 - 5.0;
// A brushed line in a plain group on a sublayer.
let line = nib_line(&mut d, x, black(), true);
let nested = line.id;
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false });
let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1));
sublayer.children_mut().unwrap().push(Arc::new(group));
d.insert(Some(layer), 0, sublayer).unwrap();
// A brushed stroke without a paint.
let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true);
let unpainted = d.insert(Some(layer), 0, unpainted).unwrap();
// A clipping group whose clip, far left of the artboard, holds a brushed line just off it.
let mut clip = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)),
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0),
);
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let member = nib_line(&mut d, x, black(), true);
let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true });
let clipped = d.insert(Some(layer), 0, clipped).unwrap();
// Compound paths of a brushed line: plain itself, then brushed itself.
let mut compounds = vec![];
for own in [false, true] {
let member = nib_line(&mut d, x, black(), true);
let mut compound =
Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero });
compound.appearance = nib_line(&mut d, x, black(), own).appearance;
compounds.push(d.insert(Some(layer), 0, compound).unwrap());
}
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer");
assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint");
assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard");
assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself");
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
}
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
/// Document keep the document's.
+1 -1
View File
@@ -40,7 +40,7 @@ use vectorcraft_render::effects;
use super::edit::roots_of;
use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key};
use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node};
use super::pathops::{leaves, node_path, outline_strokes, separate, shape_node};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, targets, unique_name};
mod analysis;
+246 -41
View File
@@ -185,9 +185,12 @@ impl Sets {
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
/// only its part above the later box's top, so boxes staggered right and down each meet only the
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
/// a later box of its group overlaps and ends no further right than keeps only the part the later
/// box doesn't cover: its part above the later box's top when the later box starts lower and ends
/// no higher than it, and its part below the later box's bottom when the later box starts no lower
/// and ends higher than it. The open box's top then moves down in the tree, so boxes staggered right
/// and down, or right and up, each meet only the one before. Fails only when cancelled
/// ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
@@ -206,27 +209,25 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
};
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
let n = boxes.len();
// Each box's place in the tree: by top (then index).
let mut by_top: Vec<usize> = (0..n).collect();
by_top.sort_by(|&a, &b| boxes[a].1.y0.total_cmp(&boxes[b].1.y0).then(a.cmp(&b)));
let tops: Vec<f64> = by_top.iter().map(|&k| boxes[k].1.y0).collect();
let mut leaf = vec![0usize; n];
for (pos, &k) in by_top.iter().enumerate() {
leaf[k] = pos;
}
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
let size = n.next_power_of_two().max(1);
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let set = |low: &mut [f64], pos: usize, v: f64| {
let mut i = pos + size;
low[i] = v;
while i > 1 {
i /= 2;
low[i] = low[2 * i].max(low[2 * i + 1]);
}
// The places an open box's top can be at in the tree: a box's top, or just below a box's
// bottom, where a later box cuts it short (`-0.0` as `0.0`).
let mut places: Vec<f64> = boxes.iter().flat_map(|(_, b)| [b.y0 + 0.0, b.y1.next_up() + 0.0]).collect();
places.sort_by(f64::total_cmp);
places.dedup_by(|a, b| a.total_cmp(b).is_eq());
let place = |y: f64| {
let y = y + 0.0;
let p = places.partition_point(|t| t.total_cmp(&y).is_lt());
places.get(p).is_some_and(|t| t.total_cmp(&y).is_eq()).then_some(p)
};
// Each box's part still open, from its top to its bottom, and the place of its top while it
// is open.
let mut top: Vec<f64> = boxes.iter().map(|(_, b)| b.y0).collect();
let mut bottom: Vec<f64> = boxes.iter().map(|(_, b)| b.y1).collect();
let mut open: Vec<Option<usize>> = vec![None; n];
// The tree of the open boxes without transparency (every box without `see_through`) and the
// see-through boxes'.
let mut trees = [Open::new(places.len()), Open::new(if see_through.is_some() { places.len() } else { 0 })];
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
let mut by_left: Vec<usize> = (0..n).collect();
by_left.sort_by(|&a, &b| boxes[a].1.x0.total_cmp(&boxes[b].1.x0));
let mut by_right: Vec<usize> = (0..n).collect();
@@ -241,7 +242,9 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
while let Some(&c) = by_right.get(closing)
&& boxes[c].1.x1 < b.x0
{
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
if let Some(p) = open[c].take() {
trees[tree(c)].take(p, c, &bottom);
}
closing += 1;
}
// The open boxes it joins with their top at most this bottom and their bottom at least
@@ -253,21 +256,32 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
Some(_) if shadows => &[0, 1],
Some(_) => &[1],
};
let below = tops.partition_point(|t| *t <= b.y1);
let below = places.partition_point(|t| *t <= b.y1);
met.clear();
for &t in looks {
let tr = &trees[t];
stack.clear();
stack.push((1, 0, size));
stack.push((1, 0, tr.size));
while let Some((node, lo, hi)) = stack.pop() {
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
if lo >= below || low[t][node] < b.y0 {
if lo >= below || tr.low[node] < b.y0 {
continue;
}
if hi - lo == 1 {
met.push(by_top[lo]);
// The boxes with their top here, lowest bottom first.
for &(_, o) in tr.at[lo].iter().rev() {
if bottom[o] < b.y0 {
break;
}
work += 1;
if work.is_multiple_of(4096) {
vectorcraft_doc::cancel::check()?;
}
met.push(o);
}
continue;
}
let mid = (lo + hi) / 2;
@@ -286,30 +300,91 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
let ob = boxes[o].1;
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
});
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
// one's top, when that box ends no further right or lower than this one, overlaps this
// one: the open box then keeps only the part above this one's top.
let cut = b.y0.next_down();
// Whatever overlaps the open part of a box inside this one overlaps this one, and joins it
// when this one is see-through. Likewise, whatever later overlaps the part of an open box
// this one covers, when that box ends no further right than this one, overlaps this one:
// the open box then keeps only the part above this one's top, when this one reaches its
// bottom, or only the part below this one's bottom, when this one reaches its top.
for &o in &met {
sets.join(boxes[k].0, boxes[o].0);
let ob = boxes[o].1;
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
let Some(p) = open[o] else { continue };
if !shadows || Some(o) == holder || b.x1 < boxes[o].1.x1 {
continue;
}
if b.y0 <= ob.y0 {
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
set(&mut low[tree(o)], leaf[o], cut);
let (t, u) = (top[o], bottom[o]);
let tr = &mut trees[tree(o)];
if b.y0 <= t && u <= b.y1 {
tr.take(p, o, &bottom);
open[o] = None;
continue;
}
if holder.is_some() || (b.y1 < u && t < b.y0) {
continue;
}
let (t, u) = if u <= b.y1 { (t, b.y0.next_down()) } else { (b.y1.next_up(), u) };
// Every top it can get has a place; one without stays as it is.
let Some(q) = place(t) else { continue };
tr.take(p, o, &bottom);
(top[o], bottom[o]) = (t, u);
open[o] = (t <= u).then_some(q);
if t <= u {
tr.put(q, o, &bottom);
}
}
if holder.is_none() {
set(&mut low[tree(k)], leaf[k], b.y1);
if holder.is_none()
&& let Some(p) = place(b.y0)
{
open[k] = Some(p);
trees[tree(k)].put(p, k, &bottom);
}
}
Ok(sets)
}
/// The open boxes of [`sweep`] by the place of their tops, in a tree that knows the lowest bottom
/// below each of its branches.
struct Open {
size: usize,
/// The lowest bottom of the open boxes below each node (−∞: none open).
low: Vec<f64>,
/// The open boxes at each place, by bottom ([`order`]) and then index.
at: Vec<BTreeSet<(i64, usize)>>,
}
impl Open {
fn new(places: usize) -> Self {
let size = places.next_power_of_two().max(1);
Self { size, low: vec![f64::NEG_INFINITY; 2 * size], at: vec![BTreeSet::new(); places] }
}
/// Opens box `k` at place `p`, with its bottom `bottom[k]`.
fn put(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].insert((order(bottom[k]), k));
self.fix(p, bottom);
}
/// Closes box `k` at place `p`, while its bottom is still `bottom[k]`.
fn take(&mut self, p: usize, k: usize, bottom: &[f64]) {
self.at[p].remove(&(order(bottom[k]), k));
self.fix(p, bottom);
}
fn fix(&mut self, p: usize, bottom: &[f64]) {
let mut i = p + self.size;
self.low[i] = self.at[p].last().map_or(f64::NEG_INFINITY, |&(_, k)| bottom[k]);
while i > 1 {
i /= 2;
self.low[i] = self.low[2 * i].max(self.low[2 * i + 1]);
}
}
}
/// `v` as an integer in the same order as [`f64::total_cmp`].
fn order(v: f64) -> i64 {
let b = v.to_bits() as i64;
b ^ (((b >> 63) as u64) >> 1) as i64
}
/// Boxes in blocks of nearby ones, each block with the box around it, to find the boxes a box
/// touches.
struct Blocks {
@@ -775,6 +850,136 @@ mod tests {
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
}
/// `n` boxes of one size, each a little right of and above the one before, all overlapping and
/// none inside another.
fn staggered_up(n: usize) -> Vec<Option<Rect>> {
let w = 2.0 * n as f64;
(0..n).map(|i| Some(Rect::new(i as f64, -(i as f64), w + i as f64, w - i as f64))).collect()
}
/// Each box of a stagger right and up meets only the box before it, which keeps only its part
/// below the new box's bottom, not every box still open; so does each box of a stagger left and
/// down, which the sweep meets right and up.
#[test]
fn boxes_staggered_up_meet_only_the_box_before() {
let n = 512;
let bounds = staggered_up(n);
let all = vec![(0..n).collect::<Vec<_>>()];
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), every_pair(&bounds));
assert_eq!(sets.groups(), all);
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut reversed = bounds.clone();
reversed.reverse();
let mut sets = sweep(&reversed, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
let mut sets = sweep(&reversed, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), all);
}
/// An open box cut short from above keeps the part a later box would meet without meeting the
/// box that cut it: a part below that box, a part further right, or any part when that box is
/// opaque or held; a box cut from above and from below keeps its middle.
#[test]
fn a_box_is_cut_short_from_above_only_where_the_later_box_covers_it() {
let k = Rect::new(5.0, -5.0, 15.0, 10.0);
let cases = [
// Below `k`: the last box overlaps only the bottom of the first.
("below", vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 15.0, 9.0, 25.0))], vec![true, true, false]),
// Further right than `k`: `k` cuts nothing and the last box overlaps the first.
("right", vec![Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(k), Some(Rect::new(17.0, 2.0, 25.0, 4.0))], vec![true, true, false]),
// Just below `k`'s bottom, and touching it.
(
"edge",
vec![Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 10.0, 9.0, 12.0)), Some(Rect::new(8.0, 10.5, 9.0, 12.0))],
vec![false, true, false, false],
),
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
("opaque", vec![Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, -10.0, 7.0, 2.0))], vec![true, false, false]),
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
(
"held",
vec![
Some(Rect::new(0.0, -6.0, 30.0, 28.0)),
Some(Rect::new(1.0, 0.0, 10.0, 20.0)),
Some(k),
Some(Rect::new(6.0, 11.0, 7.0, 13.0)),
Some(Rect::new(6.0, 4.0, 7.0, 6.0)),
],
vec![true, false, true, false, false],
),
// Cut from above, then from below: a later box inside what is left joins the first.
(
"middle",
vec![
Some(Rect::new(0.0, 0.0, 10.0, 30.0)),
Some(Rect::new(2.0, -5.0, 12.0, 10.0)),
Some(Rect::new(3.0, 20.0, 13.0, 40.0)),
Some(Rect::new(5.0, 15.0, 6.0, 16.0)),
Some(Rect::new(5.0, 9.0, 6.0, 10.0)),
Some(Rect::new(5.0, 20.0, 6.0, 20.0)),
],
vec![false, true, true, false, false, false],
),
// Signed zeros, a point and a box that isn't finite.
(
"zeros",
vec![
Some(Rect::new(-0.0, -0.0, 4.0, 8.0)),
Some(Rect::new(0.0, -2.0, 6.0, -0.0)),
Some(Rect::new(1.0, 0.0, 1.0, 0.0)),
Some(Rect::new(2.0, f64::NEG_INFINITY, 3.0, 1.0)),
Some(Rect::new(3.0, f64::MAX, 3.0, f64::MAX)),
Some(Rect::new(3.5, 0.0, 3.5, 0.0)),
],
vec![false, true, false, true, true, false],
),
];
for (what, bounds, see) in cases {
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "{what}");
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "{what}, with transparency");
let mut sets = sweep(&bounds, Some(&vec![true; bounds.len()])).unwrap();
assert_eq!(sets.groups(), every_pair(&bounds), "{what}, all see-through");
}
}
/// Boxes stepping right and alternately up and down, so that open boxes are cut short from
/// above and from below, of mixed sizes, some see-through, group as comparing every pair groups
/// them.
#[test]
fn boxes_stepping_up_and_down_group_as_comparing_every_pair() {
let mut seed = 0x6a09_e667_f3bc_c908u64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..40 {
let n = 10 + round * 3;
let mut y = 0.0;
let bounds: Vec<Option<Rect>> = (0..n)
.map(|i| {
let up = if (i / (1 + round % 3)) % 2 == 0 { -1.0 } else { 1.0 };
y += up * (next(4.0).floor() + 1.0);
let x = i as f64 + next(2.0).floor();
let (w, h) = (next(12.0).floor() + 4.0, next(16.0).floor() + 2.0);
Some(Rect::new(x, y, x + w, y + h))
})
.collect();
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
let see: Vec<bool> = (0..n).map(|_| next(1.0) < if round % 2 == 0 { 0.5 } else { 0.9 }).collect();
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
}
}
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
/// a part lower than that box, a part further right, or any part when that box is opaque.
#[test]
+390 -50
View File
@@ -1,9 +1,11 @@
use std::collections::HashSet;
use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach};
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
use super::options::FlattenOptions;
use super::{
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po,
separate, shape_node, shapes, unique_key,
};
@@ -14,6 +16,8 @@ pub(super) struct Plan {
pub(super) flat: Vec<Flat>,
/// Objects without transparency (they stay, but for the outline options).
pub(super) kept: Vec<NodeId>,
/// What the outline and overprint options do to each of `kept`, in its order.
pub(super) work: Vec<Kept>,
/// The objects with transparency of their own.
pub(super) transparent: Vec<NodeId>,
}
@@ -112,7 +116,12 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
let reaches: Vec<Option<Rect>> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect();
let see_through: Vec<bool> = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect();
let cmyk = src.color_mode == ColorMode::Cmyk;
let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() };
let mut out = Plan {
flat: vec![],
kept: vec![],
work: vec![],
transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect(),
};
// Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing).
vectorcraft_doc::cancel::check()?;
let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?;
@@ -193,9 +202,101 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render:
};
out.flat.push(Flat { roots: ids, regions, area, raster, lines });
}
out.work = out.kept.iter().map(|id| Kept::of(src, *id, o)).collect();
Ok(out)
}
/// What the outline and overprint options do to one object without transparency, found in one
/// walk of it.
pub(super) struct Kept {
pub(super) id: NodeId,
/// Whether the options change it.
pub(super) changes: bool,
/// The type the text option outlines and the stroked paths the stroke option outlines, those
/// that show and are not pieces of a compound path: what the Flattener Preview highlights.
pub(super) shown_text: Vec<NodeId>,
pub(super) shown_strokes: Vec<NodeId>,
/// In paint order: the type the text option outlines and the leaf shapes ([`leaves`]) other
/// than type that the stroke option outlines.
steps: Vec<Step>,
/// The objects with overprints, each with the type or leaf shape that holds it (itself
/// included) when a step replaces that.
overprinted: Vec<(NodeId, Option<NodeId>)>,
}
/// One object [`apply`] outlines.
enum Step {
/// Type; `leaf`: only groups and layers hold it, so its outlines are leaf shapes for the
/// stroke option.
Text { id: NodeId, leaf: bool },
/// A leaf shape other than type.
Leaf(NodeId),
}
/// Where [`Kept::visit`] is in the object it walks.
#[derive(Clone, Copy)]
struct At {
/// Neither the node nor what holds it is hidden, and it is not a piece of a compound path.
shown: bool,
/// Only groups and layers hold the node.
leaf: bool,
/// The type or leaf shape holding the node that a step replaces.
holder: Option<NodeId>,
}
impl Kept {
/// What the options `o` do to `root` of `d`: nothing when `d` doesn't hold it.
fn of(d: &Document, root: NodeId, o: &FlattenOptions) -> Kept {
let mut k = Kept { id: root, changes: false, shown_text: vec![], shown_strokes: vec![], steps: vec![], overprinted: vec![] };
if let Some(n) = d.node(root) {
k.visit(n, o, At { shown: true, leaf: true, holder: None });
}
k
}
/// Note what the options `o` do to `n` and to everything under it.
fn visit(&mut self, n: &Node, o: &FlattenOptions, at: At) {
kept_seen(n);
let shown = at.shown && n.visible;
let mut holder = at.holder;
if matches!(n.kind, NodeKind::Text(_)) {
if o.text_to_outlines {
self.changes = true;
if shown {
self.shown_text.push(n.id);
}
self.steps.push(Step::Text { id: n.id, leaf: at.leaf });
holder = Some(n.id);
}
} else {
if o.strokes_to_outlines && stroked(n) {
self.changes = true;
if shown {
self.shown_strokes.push(n.id);
}
}
if o.strokes_to_outlines && at.leaf && matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
{
self.steps.push(Step::Leaf(n.id));
holder = Some(n.id);
}
}
if !o.preserve_overprints && overprints(n) {
self.changes = true;
self.overprinted.push((n.id, holder));
}
let Some(children) = n.children() else { return };
let inside = At {
shown: shown && !matches!(n.kind, NodeKind::Compound { .. }),
leaf: at.leaf && matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }),
holder,
};
for c in children {
self.visit(c, o, inside);
}
}
}
/// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the
/// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object.
/// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is
@@ -668,7 +769,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result<Opt
roots.extend(children.iter().skip(usize::from(l.clips())).filter(|c| c.visible && !c.is_ruler_guide()).map(|c| c.id));
}
let plan = plan(doc, &roots, o, true)?;
if plan.flat.is_empty() && !plan.kept.iter().any(|id| doc.node(*id).is_some_and(|n| kept_work(n, o))) {
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
return Ok(None);
}
let mut d = doc.clone();
@@ -753,19 +854,8 @@ pub(super) fn apply(d: &mut Document, sel: &mut vectorcraft_doc::Selection, plan
d.insert(Some(layer), usize::MAX, guide)?;
}
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
for mut id in plan.kept {
if o.text_to_outlines {
id = outline_texts_under(d, id)?;
}
if o.strokes_to_outlines {
id = outline_strokes_under(d, &brushes, id)?.0;
}
if !o.preserve_overprints
&& let Some(n) = d.node_mut(id)
{
drop_overprints(n);
}
ids.push(id);
for k in plan.work {
ids.push(outline_kept(d, &brushes, k, o)?);
}
ids.sort_by_key(|id| d.index_path(*id));
sel.set(ids.iter().copied());
@@ -838,6 +928,21 @@ fn guide_seen(n: &Node) {
#[cfg(not(test))]
fn guide_seen(_: &Node) {}
#[cfg(test)]
thread_local! {
/// The nodes that [`Kept::of`] has looked at on this thread, in order.
static KEPT_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Note that [`Kept::of`] looked at `n`.
#[cfg(test)]
fn kept_seen(n: &Node) {
KEPT_SEEN.with(|s| s.borrow_mut().push(n.id));
}
#[cfg(not(test))]
fn kept_seen(_: &Node) {}
/// An image of `r` (in a clip group when it is clipped).
fn raster_node(d: &mut Document, r: Raster) -> Node {
let key = unique_key(d, "flattened");
@@ -858,38 +963,65 @@ fn raster_node(d: &mut Document, r: Raster) -> Node {
crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image)
}
/// Replace the type under `root` by its outlines: → the id now standing for `root`.
fn outline_texts_under(d: &mut Document, root: NodeId) -> Result<NodeId> {
let mut texts = vec![];
if let Some(n) = d.node(root) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) {
texts.push(c.clone());
/// Do what [`Kept`] `k` found to its object of `d` (`brushes`: the document's brushes, for the
/// stroke option): its type outlined, then the strokes of its leaf shapes, the outlines of its
/// type included, then its overprints dropped. → the id now standing for the object.
fn outline_kept(d: &mut Document, brushes: &[vectorcraft_brush::Brush], k: Kept, o: &FlattenOptions) -> Result<NodeId> {
let mut root = k.id;
let mut replaced = HashSet::new();
let dropping = !o.preserve_overprints;
// Each replacement loses its overprints before it goes in: no new object is looked up.
let mut put = |d: &mut Document, old: NodeId, mut new: Node, root: &mut NodeId| -> Result<()> {
if dropping {
drop_overprints(&mut new);
}
let nid = new.id;
*d.node_mut(old).ok_or(EngineError::NoNode(old))? = new;
replaced.insert(old);
if old == *root {
*root = nid;
}
Ok(())
};
// The leaf shapes of each outlined type that only groups and layers hold, by step.
let mut outlined: Vec<Vec<Node>> = Vec::with_capacity(k.steps.len());
for step in &k.steps {
let mut lv = vec![];
if let Step::Text { id, leaf } = *step
&& let Some(out) = d.node(id).and_then(outlined_text)
{
let out = d.reid(&out);
if leaf && o.strokes_to_outlines {
leaves(&out, &mut lv);
}
});
put(d, id, out, &mut root)?;
}
outlined.push(lv);
}
let mut out = root;
for t in texts {
let Some(o) = outlined_text(&t) else { continue };
let o = d.reid(&o);
let nid = o.id;
*d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o;
if t.id == root {
out = nid;
if o.strokes_to_outlines {
for (step, lv) in k.steps.iter().zip(outlined) {
let shapes = match *step {
Step::Leaf(id) => d.node(id).cloned().into_iter().collect(),
Step::Text { .. } => lv,
};
for l in shapes.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) {
if let Some(new) = outline_strokes(d, brushes, l) {
put(d, l.id, new, &mut root)?;
}
}
}
}
Ok(out)
}
/// Whether the outline and overprint options change `n`, an object without transparency.
pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool {
let mut any = false;
n.walk(&mut |c| {
any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_)))
|| (o.strokes_to_outlines && stroked(c))
|| (!o.preserve_overprints && overprints(c));
});
any
if dropping {
for (id, holder) in k.overprinted {
if holder.is_some_and(|h| replaced.contains(&h)) {
continue;
}
if let Some(n) = d.node_mut(id) {
drop_own_overprints(n);
}
}
}
Ok(root)
}
/// Whether `n` is a path with a visible stroke (outlining turns it into a fill).
@@ -898,12 +1030,8 @@ pub(super) fn stroked(n: &Node) -> bool {
&& n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0))
}
fn overprints(n: &Node) -> bool {
n.appearance.items.iter().any(AppearanceItem::overprint)
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
}
fn drop_overprints(n: &mut Node) {
/// Drop the overprints of `n` itself.
fn drop_own_overprints(n: &mut Node) {
if overprints(n) {
for i in &mut n.appearance.items {
*i.overprint_mut() = false;
@@ -914,6 +1042,16 @@ fn drop_overprints(n: &mut Node) {
}
}
}
}
fn overprints(n: &Node) -> bool {
n.appearance.items.iter().any(AppearanceItem::overprint)
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
}
/// Drop the overprints of `n` and of everything under it.
fn drop_overprints(n: &mut Node) {
drop_own_overprints(n);
if let Some(ch) = n.children_mut() {
for c in ch {
drop_overprints(Arc::make_mut(c));
@@ -994,6 +1132,208 @@ mod tests {
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
}
/// The objects [`kept_session`] makes.
struct KeptArt {
/// Each group with its stroked rectangle (its fill overprints) and its stroked type.
groups: Vec<(NodeId, NodeId, NodeId)>,
/// A stroked rectangle and stroked type with an overprint, on their own.
rect: NodeId,
text: NodeId,
/// A stroked compound path and its pieces.
compound: NodeId,
pieces: Vec<NodeId>,
/// A group holding an unstroked rectangle and a hidden stroked rectangle.
hidden_group: NodeId,
hidden: NodeId,
/// An unstroked rectangle.
plain: NodeId,
}
/// A document without transparency: `n` groups, then the other objects of [`KeptArt`].
fn kept_session(n: usize) -> (Session, KeptArt) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
let rect = |s: &mut Session, x: f64| id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
let text = |s: &mut Session, x: f64| {
let t = id(s.execute("text.create", &json!({"x": x, "y": 80, "text": "Hi", "size": 24})).unwrap());
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [t.0]})).unwrap();
t
};
let select = |s: &mut Session, ids: &[NodeId]| {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
};
let overprint = |s: &mut Session, on: NodeId| {
s.execute("attributes.set", &json!({"ids": [on.0], "overprintFill": true})).unwrap();
};
let unstroked = |s: &mut Session, on: NodeId| {
s.execute("paint.setStroke", &json!({"none": true, "ids": [on.0]})).unwrap();
};
let mut groups = vec![];
for i in 0..n {
let x = (i % 10) as f64 * 30.0;
let (r, t) = (rect(&mut s, x), text(&mut s, x));
overprint(&mut s, r);
select(&mut s, &[r, t]);
groups.push((id(s.execute("object.group", &json!({})).unwrap()), r, t));
}
let (r, t) = (rect(&mut s, 0.0), text(&mut s, 100.0));
overprint(&mut s, t);
let (a, b) = (rect(&mut s, 200.0), rect(&mut s, 210.0));
select(&mut s, &[a, b]);
let compound = id(s.execute("object.compoundPath.make", &json!({})).unwrap());
s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [compound.0]})).unwrap();
let pieces = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|c| c.id).collect();
let (shown, hidden) = (rect(&mut s, 300.0), rect(&mut s, 310.0));
unstroked(&mut s, shown);
select(&mut s, &[shown, hidden]);
let hidden_group = id(s.execute("object.group", &json!({})).unwrap());
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
let plain = rect(&mut s, 350.0);
unstroked(&mut s, plain);
(s, KeptArt { groups, rect: r, text: t, compound, pieces, hidden_group, hidden, plain })
}
/// Every option on: type and strokes outlined, overprints dropped.
fn outlining() -> FlattenOptions {
FlattenOptions { text_to_outlines: true, strokes_to_outlines: true, preserve_overprints: false, ..FlattenOptions::default() }
}
/// The top-level objects of `d`'s first layer, in paint order.
fn top_level(d: &Document) -> Vec<NodeId> {
d.layers[0].children().unwrap().iter().map(|c| c.id).collect()
}
fn sorted(mut ids: Vec<NodeId>) -> Vec<NodeId> {
ids.sort();
ids
}
/// The nodes [`Kept::of`] looked at while `f` ran, sorted.
fn kept_seen_by(f: impl FnOnce()) -> Vec<NodeId> {
KEPT_SEEN.with(|v| v.borrow_mut().clear());
f();
sorted(KEPT_SEEN.with(|v| v.take()))
}
/// The Flattener Preview, `object.flattenTransparency` and flattening a whole document each look
/// at every node of the objects without transparency once, with type and strokes outlined and
/// overprints dropped, an object they leave as it is included.
#[test]
fn kept_objects_are_looked_at_once() {
let (mut s, _) = kept_session(100);
let o = outlining();
let doc = s.doc().unwrap().doc.clone();
let roots = top_level(&doc);
let mut nodes = vec![];
for r in &roots {
doc.node(*r).unwrap().walk(&mut |c| nodes.push(c.id));
}
nodes.sort();
assert_eq!(nodes.len(), 309);
let preview = kept_seen_by(|| drop(super::super::report::report(&doc, &roots, &o).unwrap()));
assert!(preview == nodes, "the preview looked at {} nodes of {}", preview.len(), nodes.len());
let whole = kept_seen_by(|| drop(flatten_document(&doc, &o).unwrap().unwrap()));
assert!(whole == nodes, "flattening the document looked at {} nodes of {}", whole.len(), nodes.len());
let ids: Vec<u64> = roots.iter().map(|r| r.0).collect();
let command = kept_seen_by(|| {
s.execute(
"object.flattenTransparency",
&json!({"ids": ids, "textToOutlines": true, "strokesToOutlines": true, "preserveOverprints": false}),
)
.unwrap();
});
assert!(command == nodes, "object.flattenTransparency looked at {} nodes of {}", command.len(), nodes.len());
}
/// [`apply`]'s outlining of `kept` (objects of `d` without transparency) with `o`, done as a
/// walk of each object for each option: → the ids standing for them, in paint order.
fn outlined_walk_by_walk(d: &mut Document, kept: &[NodeId], o: &FlattenOptions) -> Vec<NodeId> {
let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] };
let mut ids = vec![];
for &root in kept {
let mut id = root;
if o.text_to_outlines {
let mut texts = vec![];
d.node(id).unwrap().walk(&mut |c| {
if matches!(c.kind, NodeKind::Text(_)) {
texts.push(c.clone());
}
});
for t in texts {
let Some(out) = outlined_text(&t) else { continue };
let out = d.reid(&out);
if t.id == root {
id = out.id;
}
*d.node_mut(t.id).unwrap() = out;
}
}
if o.strokes_to_outlines {
id = crate::cmd::pathops::outline_strokes_under(d, &brushes, id).unwrap().0;
}
if !o.preserve_overprints {
drop_overprints(d.node_mut(id).unwrap());
}
ids.push(id);
}
ids.sort_by_key(|id| d.index_path(*id));
ids
}
/// With each mix of the text, stroke and overprint options, the objects without transparency
/// end as a walk of each of them for each option leaves them: the same art, ids and selection.
#[test]
fn kept_objects_change_as_a_walk_per_option_changes_them() {
let (s, _) = kept_session(3);
let doc = Document::clone(&s.doc().unwrap().doc);
let roots = top_level(&doc);
for bits in 0..8u8 {
let o = FlattenOptions {
text_to_outlines: bits & 1 != 0,
strokes_to_outlines: bits & 2 != 0,
preserve_overprints: bits & 4 != 0,
..FlattenOptions::default()
};
let p = plan(&doc, &roots, &o, true).unwrap();
assert!(p.flat.is_empty(), "{o:?}");
// In the order the plan's groups come in.
let kept = p.kept.clone();
assert_eq!(sorted(kept.clone()), sorted(roots.clone()), "{o:?}");
let mut once = doc.clone();
let mut sel = vectorcraft_doc::Selection::default();
let (ids, ..) = apply(&mut once, &mut sel, p, &o).unwrap();
let mut walked = doc.clone();
let want = outlined_walk_by_walk(&mut walked, &kept, &o);
assert_eq!(ids, want, "{o:?}");
assert!(once == walked, "{o:?}");
assert_eq!(once == doc, bits == 4, "{o:?}: only with every option off does nothing change");
}
}
/// The Flattener Preview lists the kept objects the options change, and of those the type and
/// the stroked paths that show and are not pieces of a compound path.
#[test]
fn the_preview_lists_what_the_options_change_in_kept_objects() {
let (s, a) = kept_session(2);
let doc = &s.doc().unwrap().doc;
let roots = top_level(doc);
let r = super::super::report::report(doc, &roots, &outlining()).unwrap();
let (g, rects, texts): (Vec<_>, Vec<_>, Vec<_>) =
(a.groups.iter().map(|g| g.0).collect(), a.groups.iter().map(|g| g.1).collect(), a.groups.iter().map(|g| g.2).collect());
assert_eq!(r.affected, [g.clone(), vec![a.rect, a.text, a.compound, a.hidden_group]].concat());
// Both lists come in the order the plan's groups do.
assert_eq!(sorted(r.text.clone()), sorted([texts, vec![a.text]].concat()));
assert_eq!(sorted(r.strokes.clone()), sorted([rects, vec![a.rect, a.compound]].concat()));
assert!(!r.strokes.contains(&a.hidden) && !r.strokes.iter().any(|id| a.pieces.contains(id)) && !r.affected.contains(&a.plain));
// Dropping overprints alone changes the objects that overprint.
let o = FlattenOptions { preserve_overprints: false, ..FlattenOptions::default() };
let r = super::super::report::report(doc, &roots, &o).unwrap();
assert_eq!((r.affected, r.text, r.strokes), ([g, vec![a.text]].concat(), vec![], vec![]));
// With every option off, nothing.
assert!(super::super::report::report(doc, &roots, &FlattenOptions::default()).unwrap().affected.is_empty());
}
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
/// image within one of its pixels joins the group, also where a long image is made at a lower
/// resolution and its pixels are wider than at the preset's.
+2 -2
View File
@@ -1,5 +1,5 @@
use super::analysis::draws_image;
use super::apply::{apply, kept_work, plan};
use super::apply::{apply, plan};
use super::presets::{FlattenerPreset, saved_preset};
use super::report::target_roots;
use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param};
@@ -194,7 +194,7 @@ pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
let plan = plan(&src, &roots, &o, true)?;
let warning = crate::cmd::rasterfx::undecoded_warning(failed);
let options = serde_json::to_value(&o).unwrap_or_default();
if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) {
if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) {
return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>(), "rasterized": 0, "vector": 0, "options": options }));
}
let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| {
+5 -10
View File
@@ -1,4 +1,4 @@
use super::apply::{kept_work, opaque, plan, stroked};
use super::apply::{opaque, plan, stroked};
use super::options::FlattenOptions;
use super::{
Appearance, Color, Deserialize, Document, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Serialize, Session, Value, bad, isolated_doc,
@@ -263,15 +263,10 @@ pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result<Fl
r.rasterized.push(a.outline());
}
}
for root in plan.kept.iter().filter_map(|id| doc.node(*id)).filter(|n| kept_work(n, o)) {
r.affected.push(root.id);
visit(root, &mut |n| {
if o.text_to_outlines && matches!(n.kind, NodeKind::Text(_)) {
r.text.push(n.id);
} else if o.strokes_to_outlines && stroked(n) {
r.strokes.push(n.id);
}
});
for k in plan.work.iter().filter(|k| k.changes) {
r.affected.push(k.id);
r.text.extend(&k.shown_text);
r.strokes.extend(&k.shown_strokes);
}
r.affected.sort_by_key(|id| doc.index_path(*id));
Ok(r)
+47
View File
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
font_list
),
cmd!(
query "text.glyphCategories",
"Glyph Categories",
[],
None,
"{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)",
always,
glyph_categories
),
cmd!(
"text.rescanFonts",
"Refresh Font List",
@@ -1137,6 +1146,44 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
}
}
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.glyphCategories";
let text = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.as_str())),
Some(_) => Err(bad(C, format!("`{key}` must be a string"))),
};
let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?;
let db = vectorcraft_text::FontDb::global();
if !db.has_family(family) {
return Err(bad(C, format!("font family `{family}` is not available")));
}
let styles = db.styles(family);
let style = match text("style")? {
Some(style) => styles
.iter()
.find(|s| s.eq_ignore_ascii_case(style))
.cloned()
.ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?,
None => styles.first().cloned().unwrap_or_else(|| "Regular".into()),
};
let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?;
let categories: Vec<Value> = face
.glyph_categories()
.iter()
.map(|c| {
let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs});
if let Some(name) = &c.name {
v["name"] = json!(name);
}
v
})
.collect();
Ok(json!({"family": face.family, "style": face.style, "categories": categories}))
}
pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result<Value> {
let db = vectorcraft_text::FontDb::global();
#[cfg(not(target_arch = "wasm32"))]
+11 -5
View File
@@ -534,7 +534,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
// not one for new art.
let selected = !ids.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?;
// How the gradient lies on a stroke (the panel's Stroke buttons).
let mode = match str_param(p, "strokeMode") {
None => None,
@@ -558,7 +558,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
_ => None,
});
let for_default = match p.get("aspect").and_then(Value::as_f64) {
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
Some(a) if a < 0.0 && selected && default_kind != Some(GradientKind::Conic) => {
let mut q = p.clone();
q["aspect"] = json!(-a);
std::borrow::Cow::Owned(q)
@@ -568,7 +568,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
let for_default = match for_default {
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
q if spreads && selected && default_kind == Some(GradientKind::Freeform) => {
let mut q = q.into_owned();
if let Some(o) = q.as_object_mut() {
o.remove("spread");
@@ -579,8 +579,14 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
};
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
.map_err(|e| bad(C, e))?;
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let of = super::appearance::reference_of(s, p, item, C)?;
// Only design art was given or selected: nothing changes, the defaults and the remembered paint included.
if selected && ids.is_empty() {
// An aligned `item` of the art alone is still checked: a row the art lacks, or that no other object has, is an error.
edit_items(s, &ids, item, of, C, "Gradient", !stroke, |_, _| Ok(()))?;
return Ok(json!({"ids": []}));
}
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
let shown_at = super::appearance::first_edited(s, item, of, &ids);
// The objects returned: with a design's art, those with a row equal to the art's.
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
@@ -770,7 +776,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
let targets = super::appearance::drop_design_art_rows(s, targets, item, !stroke, C)?;
let model = super::paint::new_color_model(s, &Value::Null);
let of = super::appearance::reference_of(s, p, item, C)?;
// The objects returned: with a design's art, those with a row equal to the art's.
+3 -3
View File
@@ -49,9 +49,9 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among,
series_marks_in, series_object_opacity_differs, shown_paint,
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades,
is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where,
series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades,
};
#[cfg(test)]
+19 -5
View File
@@ -393,6 +393,16 @@ impl<'a> Plot<'a> {
series_marks(self.g, i, series_fill, stroke, width)
}
/// The stroke paint and width series `s`'s filled marks and its legend swatch get when the series keeps no stroke
/// of its own: a white line between stacked segments, area bands and pie wedges, none on other marks.
fn mark_stroke(&self, s: usize) -> (Paint, f64) {
match self.kind(s) {
GraphKind::StackedColumn | GraphKind::StackedBar | GraphKind::Area => (Paint::solid(Color::WHITE), 0.25),
GraphKind::Pie => (Paint::solid(Color::WHITE), 0.5),
_ => (Paint::None, 0.0),
}
}
fn series_label(&self, i: usize) -> String {
self.g.series.get(i).cloned().unwrap_or_default()
}
@@ -471,7 +481,8 @@ impl<'a> Plot<'a> {
}
let sweep = v / total * std::f64::consts::TAU;
let bp = wedge_path(ring, a0, sweep);
let (fill, stroke, sw) = self.mark(s, true, Paint::solid(Color::WHITE), 0.5);
let (stroke, width) = self.mark_stroke(s);
let (fill, stroke, sw) = self.mark(s, true, stroke, width);
let dark = is_dark(&fill);
let n = self.b.path(PathData::from_bezpath(&bp), fill, stroke, sw);
self.push_shadowed(s, n);
@@ -887,7 +898,8 @@ impl<'a> Plot<'a> {
let Some(base) = (if v >= 0.0 { pos.get_mut(ax) } else { neg.get_mut(ax) }) else { continue };
let (v0, v1) = (geo.vpos(ax, *base), geo.vpos(ax, *base + v));
*base += v;
let paint = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
let (stroke, width) = self.mark_stroke(s);
let paint = self.mark(s, true, stroke, width);
let rect = bar_rect(geo.horizontal, a, w, v0, v1);
// A segment of 0 has no area to shade.
let n = self.bar_node(Bar { s, rect, value: v, down: v1 < v0, per_unit: geo.per_unit(ax) }, paint, v != 0.0);
@@ -907,7 +919,8 @@ impl<'a> Plot<'a> {
let at = |c: usize, v: &[f64]| Point::new(geo.cat_mid(c), geo.vpos(a, v.get(c).copied().unwrap_or(0.0)));
let mut pts: Vec<Point> = (0..ncat).map(|c| at(c, &above)).collect();
pts.extend((0..ncat).rev().map(|c| at(c, below)));
let (fill, stroke, w) = self.mark(s, true, Paint::solid(Color::WHITE), 0.25);
let (stroke, width) = self.mark_stroke(s);
let (fill, stroke, w) = self.mark(s, true, stroke, width);
let n = self.b.path(polyline(&pts, true), fill, stroke, w);
self.push_series(s, n);
*below = above;
@@ -951,10 +964,11 @@ impl<'a> Plot<'a> {
}
/// The swatch of series `s` at `(x, y)`: series drawn with markers show their marker design in the legend, and
/// series drawn with a column design that design.
/// series drawn with a column design that design. A default swatch has the stroke of its series' marks.
fn legend_swatch(&mut self, s: usize, (x, y): (f64, f64)) {
let marked = matches!(self.g.kind, GraphKind::Scatter | GraphKind::Radar) || self.kind(s) == GraphKind::Line;
let paint = self.mark(s, true, Paint::None, 0.0);
let (stroke, width) = self.mark_stroke(s);
let paint = self.mark(s, true, stroke, width);
let column = nth(self.column_looks, s).filter(|_| self.columnar(s));
let swatch = self.b.swatch(column, nth(&self.designs, s).filter(|_| marked), Rect::new(x, y, x + 8.0, y + 8.0), paint);
self.push_series(s, swatch);
+63
View File
@@ -1,4 +1,5 @@
use vectorcraft_color::BlendMode;
use vectorcraft_doc::swatches::walk_with_masks;
use vectorcraft_geom::Shape;
use super::axis::radar_axis;
@@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap<NodeId, bool>) {
}
}
/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included)
/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a
/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`].
pub(crate) fn wedge_shades(n: &Node) -> HashMap<NodeId, Vec<bool>> {
let mut out = HashMap::new();
walk_with_masks(n, &mut |m| {
if let Some(g) = m.extras().graph.as_deref()
&& g.kind == GraphKind::Pie
&& g.legend
&& g.pie_legend_in_wedges
&& !g.label_styles.legend_fill_is_own()
{
out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect());
}
});
out
}
/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a
/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept
/// their darkness keep their labels as they are.
pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap<NodeId, Vec<bool>>) {
let mut changed = vec![];
walk_with_masks(n, &mut |m| {
if let Some(before) = was.get(&m.id)
&& pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied())
{
changed.push(m.id);
}
});
if !changed.is_empty() {
restore_contrast(n, &changed);
}
}
/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw
/// sets them on their wedges.
fn restore_contrast(n: &mut Node, ids: &[NodeId]) {
if ids.contains(&n.id) {
let on_dark = match n.extras().graph.as_deref() {
Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)),
None => HashMap::new(),
};
set_legend_fills(n, &on_dark);
}
let holds = |c: &Node| {
let mut found = false;
walk_with_masks(c, &mut |m| found |= ids.contains(&m.id));
found
};
if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
&& let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
{
restore_contrast(Arc::make_mut(&mut m.art), ids);
}
for c in n.children_mut().into_iter().flatten() {
if holds(c) {
restore_contrast(Arc::make_mut(c), ids);
}
}
}
/// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them.
fn legend_labels(n: &Node) -> Vec<&Node> {
legend_in(n.children().map_or(&[], |c| c.as_slice()))
+354 -2
View File
@@ -454,7 +454,7 @@ fn an_edit_of_a_graph_designs_art_is_lost_when_the_graph_is_drawn_again() {
/// it, and edit the other objects they are given.
#[test]
fn paint_commands_leave_a_graph_designs_art_out() {
let (mut s, _, copy, art, mark) = design_art();
let (mut s, graph, copy, art, mark) = design_art();
let fill = top_row(&s, art, true);
let commands = [
("stroke.set", json!({"weight": 5})),
@@ -466,6 +466,7 @@ fn paint_commands_leave_a_graph_designs_art_out() {
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
];
let (copy_was, art_was) = (look(&s, copy), look(&s, art));
for (cmd, p) in &commands {
@@ -489,6 +490,11 @@ fn paint_commands_leave_a_graph_designs_art_out() {
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
assert_eq!(look(&s, art), art_was);
// Given the whole graph, Invert recolors the marks and leaves the art.
let mark_was = look(&s, mark);
s.execute("paint.invert", &json!({"ids": [graph.0]})).unwrap();
assert_eq!(look(&s, art), art_was);
assert_ne!(look(&s, mark), mark_was);
// A freeform gradient point is refused on the art alone.
refused_on_design_art(&mut s, "paint.freeform.addPoint", json!({"ids": [art.0], "at": [0, 0]}));
}
@@ -517,6 +523,182 @@ fn stroke_edits_of_selected_design_art_leave_the_new_art_stroke() {
assert_eq!(s.new_art_stroke().gradient_mode, mode, "paint.editGradient");
}
/// With only the art of a graph design given or selected, the gradient, swap, default and recolor commands leave the
/// paint for new art and the remembered colors as they are.
#[test]
fn paint_edits_of_design_art_alone_leave_the_defaults() {
let (mut s, _, _, art, _) = design_art();
let fill = top_row(&s, art, true);
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("stroke.set", &json!({"weight": 3})).unwrap();
let defaults = |s: &Session| format!("{:?}", (&s.paint, s.last_solid, &s.last_gradient, &s.recent_colors));
let commands = [
("paint.editGradient", json!({"kind": "linear"})),
("paint.editGradient", json!({"kind": "radial", "stroke": true})),
("paint.swap", json!({})),
("paint.default", json!({})),
("paint.invert", json!({"item": fill, "stroke": false})),
("paint.complement", json!({"item": fill, "stroke": false})),
("paint.invert", json!({})),
("paint.complement", json!({"stroke": true})),
("stroke.set", json!({"weight": 7})),
("stroke.weightUp", json!({})),
];
for (cmd, p) in &commands {
let was = defaults(&s);
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute(cmd, &q).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, given");
// Selecting the art makes the defaults take its paint.
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
let was = defaults(&s);
s.execute(cmd, p).unwrap();
assert_eq!(defaults(&s), was, "{cmd}, selected");
s.execute("select.set", &json!({"ids": []})).unwrap();
}
// A bad `item`, `aligned` or `target` is still an error with only design art given.
for bad in [
json!({"ids": [art.0], "item": "top"}),
json!({"ids": [art.0], "item": fill, "aligned": "yes"}),
json!({"ids": [art.0], "item": fill, "target": "nowhere"}),
json!({"ids": [art.0], "target": "nowhere"}),
] {
assert!(s.execute("paint.invert", &bad).is_err(), "{bad}");
assert!(s.execute("paint.complement", &bad).is_err(), "{bad}");
}
// So is an `item` the art has no row for, in each command that leaves the art out.
let steps = s.doc().unwrap().history.undo.len();
for (cmd, p) in [
("paint.invert", json!({})),
("stroke.set", json!({"weight": 2})),
("stroke.weightUp", json!({})),
("stroke.setAdvanced", json!({"swapArrows": true})),
("paint.editGradient", json!({"kind": "linear"})),
("paint.setGradientGeom", json!({"start": [0, 0], "end": [50, 50]})),
("object.setOverprint", json!({"fill": true})),
] {
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(99);
assert!(s.execute(cmd, &q).is_err(), "{cmd}");
}
// The art's stroke row named without `stroke` is a stroke row: the gradient commands succeed and change nothing.
let stroke_row = top_row(&s, art, false);
for p in [json!({"kind": "linear"}), json!({"start": [0, 0], "end": [50, 50]})] {
let cmd = if p.get("kind").is_some() { "paint.editGradient" } else { "paint.setGradientGeom" };
let mut q = p.clone();
q["ids"] = json!([art.0]);
q["item"] = json!(stroke_row);
s.execute(cmd, &q).unwrap();
}
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// With nothing selected, the swap still swaps the defaults.
let was = defaults(&s);
s.execute("paint.swap", &json!({})).unwrap();
assert_ne!(defaults(&s), was);
}
/// A spread or a negative aspect for the art of a graph design alone changes nothing, whatever kind of gradient the
/// default fill is; a bad value is still an error.
#[test]
fn gradient_edits_of_design_art_alone_skip_the_default_kind_checks() {
let (mut s, _, _, art, _) = design_art();
for (default, p) in [("freeform", json!({"spread": "repeat"})), ("linear", json!({"aspect": -50}))] {
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.editGradient", &json!({"kind": default})).unwrap();
let (was, art_was, steps) = (format!("{:?}", s.paint), look(&s, art), s.doc().unwrap().history.undo.len());
let mut q = p.clone();
q["ids"] = json!([art.0]);
s.execute("paint.editGradient", &q).unwrap_or_else(|e| panic!("{q}: {e}"));
assert_eq!(format!("{:?}", s.paint), was, "{default}");
assert_eq!(look(&s, art), art_was, "{default}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{default}");
}
assert!(s.execute("paint.editGradient", &json!({"ids": [art.0], "spread": "sideways"})).is_err());
}
/// Invert given a group around a graph recolors the group's own fill and the series marks, and leaves the art of a
/// graph design as it is. With `target: "contents"` the group's own fill stays as it is.
#[test]
fn invert_of_a_group_recolors_its_own_fill_and_leaves_design_art() {
let (mut s, graph, _, art, mark) = design_art();
s.execute("select.set", &json!({"ids": [graph.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let row = top_row(&s, group, true);
s.execute("paint.setFill", &json!({"ids": [group.0], "item": row, "color": "#ff0000"})).unwrap();
let own = |s: &Session| format!("{:?}", s.doc().unwrap().doc.node(group).unwrap().appearance.items);
let (own_was, art_was, mark_was) = (own(&s), look(&s, art), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0]})).unwrap();
assert_ne!(own(&s), own_was, "the group's own fill");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
// The color remembered is the group's own new fill, which the Fill proxy shows.
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
let (own_was, mark_was) = (own(&s), look(&s, mark));
s.execute("paint.invert", &json!({"ids": [group.0], "target": "contents"})).unwrap();
assert_eq!(own(&s), own_was, "target: contents");
assert_ne!(look(&s, mark), mark_was);
assert_eq!(look(&s, art), art_was);
}
/// Invert and Complement given a series group that holds only a graph design's art recolor the group's own fill and
/// remember that color, as the last color and the newest recent color. With several such groups the color remembered
/// is that of the first group whose fill changed.
#[test]
fn recoloring_a_group_of_design_art_alone_remembers_its_own_fill() {
// A fill of its own for `group`, painted `hex` (the color of a rectangle painted with it).
let paint_own = |s: &mut Session, group: NodeId, hex: &str| {
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
let t = NodeId(s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 5, "height": 5})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [t.0], "color": hex})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let paint = d.node(t).unwrap().proxy_paint_only(false, None).unwrap().clone();
d.node_mut(group).unwrap().appearance.fill_at_mut(None).unwrap().paint = paint;
};
// Series 0's group with its own fill painted `hex`.
let painted_series = |hex: &str| {
let (mut s, graph, _, art, _) = design_art();
let group = series(s.doc().unwrap().doc.node(graph).unwrap(), 0).id;
paint_own(&mut s, group, hex);
(s, group, art)
};
for cmd in ["paint.invert", "paint.complement"] {
let (mut s, group, art) = painted_series("#ff0000");
let fill = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().proxy_paint_only(false, None).unwrap().clone();
let (art_was, fill_was) = (look(&s, art), fill(&s));
s.execute(cmd, &json!({"ids": [group.0]})).unwrap();
assert_eq!(look(&s, art), art_was, "{cmd}");
assert_ne!(fill(&s), fill_was, "{cmd}: the group's fill is recolored");
let Paint::Solid { color, .. } = fill(&s) else { panic!("{cmd}: the group's fill is not a solid color") };
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)), "{cmd}");
}
// A gray fill is its own complement: nothing changes, and the remembered colors stay as they were.
let (mut s, group, _) = painted_series("#808080");
s.execute("select.set", &json!({"ids": []})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
let remembered = |s: &Session| format!("{:?}", (s.last_solid, &s.recent_colors));
let was = remembered(&s);
assert_eq!(s.execute("paint.complement", &json!({"ids": [group.0]})).unwrap()["changed"], json!(0));
assert_eq!(remembered(&s), was);
// Both series groups hold only the design's art: a gray one first and a red one, given together.
let (mut s, graph, _, _, _) = design_art();
s.execute("graph.column", &json!({"id": graph.0, "seriesIndexes": [1], "design": "Square"})).unwrap();
let groups = [0, 1].map(|i| series(s.doc().unwrap().doc.node(graph).unwrap(), i).id);
paint_own(&mut s, groups[0], "#808080");
paint_own(&mut s, groups[1], "#ff0000");
s.execute("paint.complement", &json!({"ids": [groups[0].0, groups[1].0]})).unwrap();
let Some(Paint::Solid { color, .. }) = s.doc().unwrap().doc.node(groups[1]).unwrap().proxy_paint_only(false, None).cloned() else {
panic!("the red group's fill is not a solid color")
};
assert_eq!((s.last_solid, s.recent_colors.first().copied()), (color, Some(color)));
}
/// `transparency.set` without `item` refuses the art of a graph design in a series, and given it with other objects
/// sets only theirs.
#[test]
@@ -596,6 +778,81 @@ fn expand_appearance_leaves_a_graph_designs_art() {
assert!(s.doc().unwrap().doc.node(NodeId(other)).is_none_or(|m| m.appearance.effects.is_empty()));
}
/// `effect` with `params`, as `effect.apply` gives it to an object.
fn an_effect(s: &mut Session, effect: &str, params: serde_json::Value) -> vectorcraft_doc::Effect {
let r = s.execute("shape.rectangle", &json!({"x": 700, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": effect, "ids": [r], "params": params})).unwrap();
s.doc().unwrap().doc.node(NodeId(r)).unwrap().appearance.effects[0].clone()
}
/// Expand Appearance of a graph neither lists the art of a design in a series whose own effect it leaves, nor adds an
/// image of that effect to the document.
#[test]
fn expand_appearance_lists_no_design_art_and_rasterizes_none() {
let (mut s, id, copy, _, mark) = design_art();
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(copy).unwrap().appearance.effects.push(shadow);
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0]})).unwrap();
let copy_was = look(&s, copy);
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
s.execute("select.set", &json!({"ids": [mark.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let per_mark = images(&s) - before;
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let expanded = s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(expanded["ids"], json!([mark.0]));
assert_eq!(look(&s, copy), copy_was);
assert_eq!(images(&s) - before, per_mark, "only the mark's shadow becomes an image");
}
/// A geometry effect of a series group that Expand Appearance bakes moves the art of a design in that series with the
/// marks.
#[test]
fn expand_appearance_moves_design_art_with_its_series_groups_effect() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shift = an_effect(&mut s, "distort.transform", json!({"moveH": 50}));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().appearance.effects.push(shift);
let left = |s: &Session| {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
series(&n, 0).children().unwrap()[0].geometric_bounds().unwrap().x0
};
let was = left(&s);
assert_eq!(series(&n, 0).children().unwrap()[0].id, copy);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert!((left(&s) - was - 50.0).abs() < 1e-6, "{} then {}", was, left(&s));
}
/// The copies that a Transform effect of a series group makes of a design's art keep their own effects when Expand
/// Appearance bakes the series group's effect, as the art they copy does.
#[test]
fn expand_appearance_leaves_the_effects_of_design_art_copies() {
let (mut s, id, copy, _, _) = design_art();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let group = series(&n, 0).id;
let shadow = an_effect(&mut s, "stylize.dropShadow", json!({}));
let copies = an_effect(&mut s, "distort.transform", json!({"moveH": 50, "copies": 2}));
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.node_mut(copy).unwrap().appearance.effects.push(shadow);
doc.node_mut(group).unwrap().appearance.effects.push(copies);
let shadows = |s: &Session| {
let mut count = 0;
s.doc().unwrap().doc.node(id).unwrap().walk(&mut |m| count += m.appearance.effects.iter().filter(|e| e.id == "stylize.dropShadow").count());
count
};
let images = |s: &Session| s.doc().unwrap().doc.images.len();
let before = images(&s);
assert_eq!(shadows(&s), 1);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
assert_eq!(shadows(&s), 3, "the art and its two copies keep their shadows");
assert_eq!(images(&s), before, "no shadow becomes an image");
}
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
#[test]
@@ -8192,7 +8449,102 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() {
}
}
}
assert!(live.contains(&"column v7.ai".to_string()) && live.contains(&"column pdf.ai".to_string()), "{live:?}");
for ty in ["column", "stackedColumn", "area"] {
assert!(live.contains(&format!("{ty} v7.ai")) && live.contains(&format!("{ty} pdf.ai")), "{ty}: {live:?}");
}
}
/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the
/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept
/// on the series, with or without a weight of its own, is on the swatch too.
#[test]
fn a_legend_swatch_has_the_stroke_of_its_series_marks() {
let white = |w: f64| (Paint::solid(vectorcraft_color::Color::WHITE), w);
let cases = [
("stackedColumn", white(0.25)),
("stackedBar", white(0.25)),
("area", white(0.25)),
("pie", white(0.5)),
("column", (Paint::None, 0.0)),
("bar", (Paint::None, 0.0)),
];
for (ty, stroke) in cases {
for across_top in [false, true] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
let id = NodeId(
s.execute("graph.create", &json!({"type": ty, "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute("graph.setType", &json!({"id": id.0, "legendAcrossTop": across_top})).unwrap();
for i in 0..2 {
let marks = marks_of(&s, id, i);
assert!(marks.len() > 1, "{ty} {i}: marks and a swatch");
assert!(marks.iter().all(|m| (m.1.clone(), m.2) == stroke), "{ty} across top {across_top}, series {i}: {marks:?}");
}
// A stroke color kept on series 0 without a weight keeps the default weight, then with one.
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
let row = bar.appearance.items.iter().rposition(|it| !it.is_fill());
let Some(row) = row else { continue };
s.execute("appearance.setItem", &json!({"ids": [bar.id.0], "index": row, "color": "#ff0000"})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let marks = marks_of(&s, id, 0);
assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].1 != stroke.0, "{ty} across top {across_top}, red: {marks:?}");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("appearance.setItem", &json!({"ids": [bar.0], "index": row, "weight": 3})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap();
let marks = marks_of(&s, id, 0);
assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].2 == 3.0, "{ty} across top {across_top}, 3 pt: {marks:?}");
}
}
}
/// A stacked column graph the graph tools draw, saved as `.ai` in either form, opens again as the same graph without a
/// warning, and its data can be edited there.
#[test]
fn a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data() {
let dir = vectorcraft_testkit::temp_dir("graph-ai-stacked");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6";
let id = s.execute("graph.create", &json!({"type": "stackedColumn", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap();
let written = spec(&s, NodeId(id));
for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] {
let path = dir.join(name);
let mut p = json!({"path": path, "format": "ai"});
if let Some(v) = version {
p["aiVersion"] = json!(v);
}
let r = s.execute("file.saveAs", &p).unwrap();
let notes = r["warnings"].as_array().cloned().unwrap_or_default();
assert!(!notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}");
let mut again = Session::new();
again.execute("document.open", &json!({"path": path})).unwrap();
let mut found = vec![];
again.doc().unwrap().doc.walk(|n| {
if n.extras().graph.is_some() {
found.push(n.id);
}
});
assert_eq!(found.len(), 1, "{name}");
let g = spec(&again, found[0]);
assert_eq!((g.kind, g.cells()), (written.kind, written.cells()), "{name}");
assert_eq!((g.series.as_slice(), g.categories.as_slice()), (&written.series[..], &written.categories[..]), "{name}");
again.execute("select.set", &json!({"ids": [found[0].0]})).unwrap();
again.execute("graph.setData", &json!({"id": found[0].0, "csv": ",2024,2025\nQ1,8,1\nQ2,2,7"})).unwrap();
let after = spec(&again, found[0]);
assert_eq!((after.kind, after.rows.as_slice()), (written.kind, &[vec![8.0, 1.0], vec![2.0, 7.0]][..]), "{name}");
// Each series keeps one fill and the thin white stroke on its marks and its swatch.
for i in 0..2 {
let marks = marks_of(&again, found[0], i);
let white = Paint::solid(vectorcraft_color::Color::WHITE);
assert!(marks.len() > 1 && marks.iter().all(|m| *m == marks[0] && (&m.1, m.2) == (&white, 0.25)), "{name} series {i}: {marks:?}");
}
}
}
/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own
+135 -82
View File
@@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData {
shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame)
}
/// The clipping path an image's file draws it through, with the fill rule its clip group takes:
/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd).
type FileClip = (PathData, FillRule);
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
/// file's ([`fileio::png_clip`]).
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
if let Some(path) = blob.separated_clip() {
return Some((path, FillRule::NonZero));
}
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
}
/// What happens to the clip of an object a link update remakes.
enum ClipTo {
/// It stays as it is.
@@ -705,25 +719,25 @@ enum ClipTo {
/// It is clipped to this path (Placement Options' clip): the clipping path of the clip group
/// holding just it changes, else it goes into a new clip group.
Path(PathData),
/// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`],
/// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group
/// again.
File(PathData),
/// It is clipped to this path, the clipping path its file draws it through, under its fill
/// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`]
/// leaves one) becomes a clip group again.
File(FileClip),
/// It goes into a new clip group of this path, inside the clip group that holds it.
Nest(PathData),
/// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is
Nest(FileClip),
/// Placement Options clip it to `placement` while its file draws it through `file`: it is
/// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to
/// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the
/// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it,
/// clipped to `placement`.
Both { file: Option<PathData>, placement: PathData },
/// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the
Both { file: Option<FileClip>, placement: PathData },
/// Placement Options clip it to `placement` while its file draws it through `file`, and the
/// clip group holding just it is not its old file's: that clip group's clipping path becomes
/// `placement`, and it goes into a new clip group of `file` inside it.
BothInside { file: PathData, placement: PathData },
/// The clipping path of the clip group holding just it goes (a DCS file's clipping path that
/// its new file lacks): the group stays as a plain group of it, with its id, name, visibility
/// and transparency.
BothInside { file: FileClip, placement: PathData },
/// The clipping path of the clip group holding just it goes (its old file's clipping path,
/// which its new file lacks): the group stays as a plain group of it, with its id, name,
/// visibility and transparency.
Off,
}
@@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool {
}
/// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file
/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip
/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old
/// pixels, under the nonzero rule its clip groups get) goes.
/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file
/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When
/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's
/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes.
fn clip_to(
old_xf: Affine,
old_clip: Option<&PathData>,
old_clip: Option<&FileClip>,
clip: Option<Clip>,
img: &RasterImage,
new_xf: Affine,
held: Option<(&PathData, FillRule)>,
) -> ClipTo {
// Whether the clip group holding just the image is the old DCS file's: a clipping path whose
// fill rule was changed in the document is not.
// Whether the clip group holding just the image is the old file's: a clipping path whose fill
// rule was changed in the document is not.
let file_held = match (old_clip, held) {
(Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held),
(Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held),
_ => false,
};
let file = img.clip.as_ref().map(|path| path.transformed(new_xf));
let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule));
if let Some(clip) = clip {
let placement = clip_shape(clip);
return match file {
@@ -831,7 +845,7 @@ impl Nested<'_> {
fn root(&mut self, n: &mut Arc<Node>) {
if !(self.pick)(n) {
if let Some(placement) = self.update(n, true) {
*n = Arc::new(self.clip_group(Arc::clone(n), placement));
*n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero)));
}
return;
}
@@ -839,7 +853,8 @@ impl Nested<'_> {
let mut new = Arc::new(new);
let _ = self.update(&mut new, true);
*n = match clip {
ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)),
ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))),
ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)),
ClipTo::Both { file, placement } => self.clip_both(new, file, placement),
ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement),
ClipTo::Keep | ClipTo::Off => new,
@@ -848,8 +863,8 @@ impl Nested<'_> {
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
/// the same node when none is there, and only the nodes on the way to one are copied. The
/// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's
/// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
/// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping
/// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes:
/// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new
/// clip group of it.
#[must_use]
@@ -880,8 +895,8 @@ impl Nested<'_> {
match (self.update(&mut new, nested), clip_path) {
(None, _) if Arc::ptr_eq(&new, c) => {}
(None, _) => slots.push((i, new)),
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]),
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))),
(Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]),
(Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))),
}
continue;
}
@@ -894,17 +909,22 @@ impl Nested<'_> {
let _ = self.update(&mut new, true);
match (clip, clip_path) {
(ClipTo::Keep, _) => slots.push((i, new)),
(ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]),
(ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]),
(ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]),
(ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)),
(ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
(ClipTo::Path(clip), _) => {
let group = self.clip_group(new, (clip, FillRule::NonZero));
slots.push((i, Arc::new(group)));
}
(ClipTo::File(clip) | ClipTo::Nest(clip), _) => {
let group = self.clip_group(new, clip);
slots.push((i, Arc::new(group)));
}
(ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new),
(ClipTo::Off, _) => slots.push((i, new)),
// The file's clip group stays `n`, and the placement's clip goes around it.
(ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => {
slots.extend([(0, with_clip(path, file)), (1, new)]);
(ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => {
slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]);
around = Some(placement);
}
(ClipTo::Both { file: Some(file), placement }, None) if plain => {
@@ -917,7 +937,7 @@ impl Nested<'_> {
}
(ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => {
let group = self.clip_group(new, file);
slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]);
slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]);
}
(ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))),
(ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))),
@@ -958,27 +978,28 @@ impl Nested<'_> {
/// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a
/// `file` ([`ClipTo::Both`] for an object no clip group holds yet).
fn clip_both(&mut self, object: Arc<Node>, file: Option<PathData>, placement: PathData) -> Arc<Node> {
fn clip_both(&mut self, object: Arc<Node>, file: Option<FileClip>, placement: PathData) -> Arc<Node> {
let object = match file {
Some(file) => Arc::new(self.clip_group(object, file)),
None => object,
};
Arc::new(self.clip_group(object, placement))
Arc::new(self.clip_group(object, (placement, FillRule::NonZero)))
}
/// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers.
fn clip_group(&mut self, object: Arc<Node>, clip: PathData) -> Node {
/// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes
/// one in the layers.
fn clip_group(&mut self, object: Arc<Node>, clip: FileClip) -> Node {
let path = self.clipping_path(clip);
let group_id = NodeId(self.next);
self.next += 1;
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
}
/// A clipping path of `clip`, with the next node id.
fn clipping_path(&mut self, clip: PathData) -> Node {
/// A clipping path of `clip` under its fill rule, with the next node id.
fn clipping_path(&mut self, (clip, rule): FileClip) -> Node {
let id = NodeId(self.next);
self.next += 1;
clipping_path(id, clip)
clipping_path(id, clip, rule)
}
}
@@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n
(frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room)))
}
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when
/// no such clip group holds it.
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill
/// rule `rule` when one is given; false when no such clip group holds it.
fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option<FillRule>) -> bool {
let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind {
NodeKind::Group { children, clip: true } => match &children[..] {
[c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id),
@@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool {
_ => None,
});
let Some(c) = clip_path else { return false };
if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) {
if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) {
*p = path;
*r = rule.unwrap_or(*r);
}
true
}
@@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> {
/// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes,
/// else it goes into a new clip group.
fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
if set_clip_path(d, id, path.clone()) {
if set_clip_path(d, id, path.clone(), None) {
return Ok(());
}
new_clip_group(d, id, path)
new_clip_group(d, id, (path, FillRule::NonZero))
}
/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping
/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`]
/// leaves one) becomes a clip group again, else it goes into a new clip group.
fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
if set_clip_path(d, id, path.clone()) {
/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill
/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it
/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group.
fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
if set_clip_path(d, id, path.clone(), Some(rule)) {
return Ok(());
}
let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) {
Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id),
_ => false,
});
let Some(g) = plain else { return new_clip_group(d, id, path) };
let clip = clipping_path(d.alloc_id(), path);
let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) };
let clip = clipping_path(d.alloc_id(), path, rule);
d.insert(Some(g), 0, clip)?;
if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) {
*clip = true;
@@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
Ok(())
}
/// Clipping path `path` (a node) with its path changed to `clip`.
fn with_clip(path: &Node, clip: PathData) -> Arc<Node> {
/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when
/// one is given.
fn with_clip(path: &Node, clip: PathData, rule: Option<FillRule>) -> Arc<Node> {
let mut path = Node::clone(path);
if let NodeKind::Path { path: p, .. } = &mut path.kind {
if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind {
*p = clip;
*r = rule.unwrap_or(*r);
}
Arc::new(path)
}
/// A clipping path `id` of `path`, unpainted.
fn clipping_path(id: NodeId, path: PathData) -> Node {
/// A clipping path `id` of `path` under fill rule `rule`, unpainted.
fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node {
let none = vectorcraft_color::Paint::None;
let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0));
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind {
*clipping = true;
*r = rule;
}
clip
}
/// Put object `id` of `d` into a new clip group of `path`, where it is.
fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> {
/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is.
fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> {
let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
let image = d.remove(id)?;
let clip = clipping_path(d.alloc_id(), path);
let clip = clipping_path(d.alloc_id(), path, rule);
let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true });
d.insert(par, index, group)?;
Ok(())
@@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let nested = nested_ids(d, ids);
if also.is_some() || !nested.is_empty() {
let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false)));
// The resolution of each content the images picked show, and the clipping path its DCS file
// The resolution of each content the images picked show, and the clipping path its file
// drew it through, looked up once each.
let mut old: BTreeMap<String, ((f64, f64), Option<PathData>)> = BTreeMap::new();
let mut old: BTreeMap<String, ((f64, f64), Option<FileClip>)> = BTreeMap::new();
d.visit_stored(|n, _| {
if let NodeKind::Image(im) = &n.kind
&& pick(n)
&& !old.contains_key(&im.key)
{
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip)));
old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip)));
}
});
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
@@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o);
// Placement Options' clip, else a DCS file's clipping path, read again with its plates.
let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip);
// Placement Options' clip, else the clipping path of a DCS file (read again with its
// plates) or of a PSD or PSB file.
let old_clip = d.images.get(&im.key).and_then(file_clip);
clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id))));
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
@@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
clips.into_iter().try_for_each(|(id, clip)| match clip {
ClipTo::Keep => Ok(()),
ClipTo::Path(path) => clip_image_to(d, id, path),
ClipTo::File(path) => clip_file_to(d, id, path),
ClipTo::Nest(path) => new_clip_group(d, id, path),
ClipTo::File(file) => clip_file_to(d, id, file),
ClipTo::Nest(file) => new_clip_group(d, id, file),
ClipTo::Off => unclip(d, id),
ClipTo::Both { file, placement } => {
match file {
@@ -1314,27 +1340,54 @@ pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
/// no other resource. Hidden layers and objects are written only with
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
/// Always `false` without read roots in force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
/// no other resource. A placed document's images are those of the art the SVG draws for it. Hidden
/// layers and objects are written only with SVG Options › hidden layers kept (`hidden`), in the
/// layers and in the symbols, patterns and graph designs alike, and template layers never. SVG Tiny
/// 1.2 (`tiny`) writes no opacity masks ([`svg_written`]). Always `false` without read roots in
/// force.
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool, tiny: bool) -> bool {
if crate::file_access::current().is_none() {
return false;
}
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
if !d.has_placed() && !names_hidden_image(d, base, link) {
return false;
}
// The writer draws placed documents' art with the pixels their files hold.
let placed = d.with_placed_art();
let d = &*placed;
let art = d.layers.iter().filter_map(|l| svg_written(d, l, hidden, tiny)).collect();
let mut out = super::clipboard::Clipboard::gather(d, art).to_document();
let written = |n: &std::sync::Arc<Node>| {
let empty = || Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
std::sync::Arc::new(svg_written(d, n, hidden, tiny).unwrap_or_else(empty))
};
for s in &mut out.symbols {
s.art = written(&s.art);
}
for g in &mut out.graph_designs {
g.art = written(&g.art);
}
for p in &mut out.patterns {
p.art = p.art.iter().filter_map(|n| svg_written(d, n, hidden, tiny)).map(std::sync::Arc::new).collect();
}
names_hidden_image(&out, base, link)
}
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
/// Only layers and groups lose members; other objects keep theirs as they are.
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
/// `n` (an object of `d`) as the SVG writer writes it, or `None` when it writes none of it: a
/// hidden layer or object is left out unless `hidden`, a template layer's art always, a disabled
/// opacity mask's art, and with SVG Tiny 1.2 (`tiny`) every opacity mask's art. A placed document
/// is the art the writer draws for it. Only layers and groups lose members; other objects keep
/// theirs as they are.
fn svg_written(d: &Document, n: &Node, hidden: bool, tiny: bool) -> Option<Node> {
if !(n.visible || hidden) {
return None;
}
if matches!(n.kind, NodeKind::PlacedDocument(_)) {
return svg_written(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n), hidden, tiny);
}
let mut n = n.clone();
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
let art = svg_written(&m.art, hidden)?;
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled && !tiny).and_then(|m| {
let art = svg_written(d, &m.art, hidden, tiny)?;
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
});
if n.extras().mask.is_some() {
@@ -1343,7 +1396,7 @@ fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
match &mut n.kind {
NodeKind::Layer { template: true, children, .. } => children.clear(),
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
*children = children.iter().filter_map(|c| svg_written(d, c, hidden, tiny)).map(std::sync::Arc::new).collect();
}
_ => {}
}
+1 -1
View File
@@ -38,7 +38,7 @@ pub use commands::specs;
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
pub(crate) use pixelgrid::{
align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap,
snap_if_aligned,
snap_if_aligned, snap_symbol_art,
};
pub(super) use shape::recut;
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
+241 -2
View File
@@ -1,6 +1,9 @@
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>),
//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid.
use std::collections::HashMap;
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
@@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) {
keep_pixel_aligned(n, Scaling::default());
}
}
refresh_symbols(before, doc);
}
/// How far the linear part of an instance's transform may be from its symbol's natural size, as a
/// fraction of that size, for the instance to count as placed at actual size.
const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to
/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes
/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
/// A document without pixel-aligned symbols is not walked.
fn refresh_symbols(before: &Document, doc: &mut Document) {
let aligned = doc.pixel_aligned_symbols();
if aligned.is_empty() {
return;
}
let was = before.pixel_aligned_symbols();
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
let mut every = false;
for name in &aligned {
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
let art_changed = match (art_before, art_now) {
(Some(b), Some(a)) => !Arc::ptr_eq(b, a),
_ => true,
};
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
snap_symbol_art(doc, name);
every = true;
}
}
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
if every {
for layer in doc.layers.iter_mut() {
if holds_instance(layer, &natural) {
snap_instances_in(Arc::make_mut(layer), &natural);
}
}
return;
}
let (mut ids, mut masked) = (vec![], vec![]);
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
for id in ids {
if let Some(n) = doc.node_mut(id) {
snap_instance(n, &natural);
}
}
for id in masked {
if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) {
snap_instances_in(Arc::make_mut(&mut m.art), &natural);
}
}
}
/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
/// mask art holds such instances (`masked`).
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
for (i, a) in after.iter().enumerate() {
let b = match before.get(i) {
Some(b) if b.id == a.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
};
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
continue;
}
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
masked.push(a.id);
}
if let NodeKind::SymbolInstance { symbol, .. } = &a.kind {
if natural.contains_key(symbol) {
ids.push(a.id);
}
} else if let Some(children) = a.children() {
changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked);
}
}
}
/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in
/// `natural`.
fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool {
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol))
|| n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural))
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural)))
}
/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity
/// masks included. Only what holds such an instance is copied for editing.
fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) {
snap_instance(n, natural);
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& holds_instance(&m.art, natural)
{
snap_instances_in(Arc::make_mut(&mut m.art), natural);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if holds_instance(c, natural) {
snap_instances_in(Arc::make_mut(c), natural);
}
}
}
}
/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's
/// natural size: each path and compound path in it snaps as a pixel-aligned object does
/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when
/// something in it moved, and the answer says whether it did.
pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool {
let natural = doc.symbol_natural_xf(name);
let det = natural.determinant();
if !det.is_finite() || det.abs() < 1e-18 {
return false;
}
let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false };
// Instances draw the art's strokes at their stored width, and the art of unlinked opacity
// masks, which `Node::transform` leaves alone, at the natural size too.
let mut art = (*sym.art).clone();
art.transform(natural, false);
transform_unlinked_masks(&mut art, natural);
if !snap_art(&mut art) {
return false;
}
let inverse = natural.inverse();
art.transform(inverse, false);
transform_unlinked_masks(&mut art, inverse);
sym.art = Arc::new(art);
true
}
/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks
/// too. Only what holds such a mask is copied for editing.
fn transform_unlinked_masks(n: &mut Node, xf: Affine) {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& holds_unlinked_mask(&m.art, !m.linked)
{
let linked = m.linked;
let art = Arc::make_mut(&mut m.art);
if !linked {
art.transform(xf, false);
}
transform_unlinked_masks(art, xf);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if holds_unlinked_mask(c, false) {
transform_unlinked_masks(Arc::make_mut(c), xf);
}
}
}
}
/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of
/// its masks too, has an unlinked opacity mask.
fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool {
unlinked
|| n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked))
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false)))
}
/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of
/// opacity masks included (those of a compound path's paths too). Returns whether anything
/// changed.
fn snap_art(n: &mut Node) -> bool {
let mut moved = false;
if can_align(n) {
let was = n.clone();
snap_object(n, Scaling::default());
moved = *n != was;
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
if c.extras().mask.is_some() {
moved |= snap_mask(Arc::make_mut(c));
}
}
}
} else if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
moved |= snap_art(Arc::make_mut(c));
}
}
// After the object itself, which a linked mask follows.
snap_mask(n) || moved
}
/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed.
fn snap_mask(n: &mut Node) -> bool {
let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false };
let mut art = (*m.art).clone();
if !snap_art(&mut art) {
return false;
}
m.art = Arc::new(art);
true
}
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
/// rotated (a half turn included) or sheared instance stays where it is.
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
let Some(nat) = natural.get(symbol.as_str()) else { return };
let [a, b, c, d, e, f] = xf.as_coeffs();
let [na, _, _, nd, _, _] = nat.as_coeffs();
let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0);
let actual =
near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0);
// Flipped along both axes is a half turn, which counts as rotated.
let half_turn = a * na < 0.0 && d * nd < 0.0;
if !actual || half_turn || !e.is_finite() || !f.is_finite() {
return;
}
let (x, y) = (e.round(), f.round());
if x != e || y != f {
*xf = Affine::new([a, b, c, d, x, y]);
}
}
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
/// pixel-aligned objects in them to the pixel grid again.
/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid
/// again.
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
for id in ids {
if doc.node(*id).is_some_and(holds_aligned)
@@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
keep_pixel_aligned(n, Scaling::default());
}
}
let aligned = doc.pixel_aligned_symbols();
if aligned.is_empty() {
return;
}
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
for id in ids {
if doc.node(*id).is_some_and(|n| holds_instance(n, &natural))
&& let Some(n) = doc.node_mut(*id)
{
snap_instances_in(n, &natural);
}
}
}
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
+9 -10
View File
@@ -126,14 +126,18 @@ fn kinds(p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<(bool, bool)>> {
.collect()
}
/// Each kind's item target and objects: (fill?, item, ids).
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
/// Each kind's item target and objects: (fill?, item, ids). With `edit`, the art of graph designs drawn in graph series
/// is left out, and an explicit item that the art left out has no row of that kind for is an error, as when the edit
/// resolves it on the other objects. Without it, the art is read with the other objects.
fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>, edit: bool) -> Result<Vec<(bool, ItemTarget, Vec<NodeId>)>> {
let item = item_target(s, p, cmd)?;
kinds
.into_iter()
.map(|fill| {
let it = item.of_kind(s, fill);
Ok((fill, it, it.targets(s, p)?))
let ids = it.targets(s, p)?;
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
Ok((fill, it, ids))
})
.collect()
}
@@ -159,12 +163,7 @@ pub(super) type OverprintJob = ((bool, ItemTarget, Vec<NodeId>), bool);
/// `object.setOverprint` aims, leaving out the art of graph designs drawn in graph series.
pub(super) fn overprint_jobs(s: &Session, p: &Value, cmd: &str, keys: [&str; 2]) -> Result<Vec<OverprintJob>> {
let kinds = kinds(p, cmd, keys)?;
let d = &s.doc()?.doc;
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0))?
.into_iter()
.map(|(fill, it, ids)| (fill, it, super::appearance::drop_design_art(d, ids)))
.zip(kinds.iter().map(|k| k.1))
.collect())
Ok(aims(s, p, cmd, kinds.iter().map(|k| k.0), true)?.into_iter().zip(kinds.iter().map(|k| k.1)).collect())
}
/// Apply `jobs` to `d`, adding the objects changed to `changed`.
@@ -203,7 +202,7 @@ fn attributes(s: &Session, p: &Value) -> Result<AttributesInfo> {
let d = &s.doc()?.doc;
let mut info = AttributesInfo { ids: targets(s, p)?, recent_urls: s.recent_urls.clone(), ..Default::default() };
super::attributes::fill_info(d, &mut info);
for (fill, item, ids) in aims(s, p, C, [true, false])? {
for (fill, item, ids) in aims(s, p, C, [true, false], false)? {
let mut all =
ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| Some(flags(n, fill, item.resolve(&n.appearance, fill, C).ok()?))).flatten();
let same = all.next().and_then(|first| all.all(|b| b == first).then_some(first));
+82 -7
View File
@@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -982,7 +982,13 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option<usize>
}
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1017,7 +1023,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
}
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::drop_design_art(&s.doc()?.doc, paint_targets(s, p)?);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
// Only design art was given or selected: nothing changes, the defaults included.
if given && ids.is_empty() {
return ok();
}
if !ids.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
@@ -1086,10 +1098,26 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
return Ok(json!({ "changed": changed as usize }));
}
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
// no row for) is still an error.
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
let of = match item {
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
ItemTarget::Top => None,
};
// Read before the check below too: `targets` reads no `target` for the topmost fill or stroke.
let contents = super::appearance::targets_contents(p)?;
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
// Only design art was given or selected: nothing changes, the defaults and remembered colors included.
if ids.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let (r, shown_at) = match item {
ItemTarget::Item { .. } => {
let targets = super::appearance::drop_design_art(&s.doc()?.doc, item.targets(s, p)?);
let of = super::appearance::reference_of(s, p, item, cmd)?;
// Only design art was given or selected: nothing changes, the remembered colors included.
if targets.is_empty() {
return Ok(json!({ "changed": 0 }));
}
// The row shown is the one edited in the first object that has it: an aligned row maps to each object's equal row.
let shown_at = super::appearance::first_edited(s, item, of, &targets).and_then(|(id, it)| match it {
ItemTarget::Item { index, .. } => Some((id, Some(index))),
@@ -1105,9 +1133,56 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
(json!({ "changed": changed }), shown_at)
}
// The proxy recolors its paints, including a colorized image's fill, without changing image pixels or pattern tiles.
// A given group's own fills and strokes change with the objects inside it, except with `target: "contents"`; other
// objects change as their paint targets do (a compound path's member stands for the compound path). Design art
// inside a given graph or series group is left out.
ItemTarget::Top => {
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
(super::colorcmds::recolor(s, &q, cmd, label, f)?, leaf_targets(s, &ids)?.first().map(|id| (*id, None)))
let mut roots = vec![];
for id in &ids {
let n = s.doc()?.doc.node(*id);
let group =
!contents && n.is_some_and(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape());
if group {
roots.push(*id);
} else {
roots.extend(leaf_targets(s, &[*id])?);
}
}
let d = &s.doc()?.doc;
let mut seen = std::collections::HashSet::new();
roots.retain(|id| seen.insert(*id));
let roots = super::appearance::drop_design_art(d, roots);
if roots.is_empty() {
return Ok(json!({ "changed": 0 }));
}
let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
// The fill or stroke the proxy shows of each group among the roots, before the edit.
let own = |d: &Document, id: NodeId| {
d.node(id)
.filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
.and_then(|n| n.proxy_paint_only(stroke, None))
.cloned()
};
let own_before: std::collections::HashMap<NodeId, Paint> = roots.iter().filter_map(|id| Some((*id, own(d, *id)?))).collect();
let q = json!({"fill": !stroke, "stroke": stroke, "includeImages": false, "includePatterns": false, "ids": roots.iter().map(|i| i.0).collect::<Vec<_>>()});
let r = super::colorcmds::recolor_except(s, &q, cmd, label, f, art)?;
// As the proxy shows a group: its own fill or stroke when the edit changed it, else the first object inside it
// that is not design art (which keeps its paint). The first object given that has either shows it.
let d = &s.doc()?.doc;
let mut shown_at = None;
for id in &ids {
if let Some(was) = own_before.get(id)
&& own(d, *id).as_ref() != Some(was)
{
shown_at = Some((*id, None));
break;
}
if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
shown_at = Some((*leaf, None));
break;
}
}
(r, shown_at)
}
};
// The paint remembered is one the edit recolored: a graph design's art that the item edit leaves out gives none.
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -318,7 +318,7 @@ pub(crate) fn style_of(n: &Node) -> Style {
/// Leaf shapes (paths, compound paths, text) of a subtree in paint order; guides and clipping
/// paths are skipped.
fn leaves(n: &Node, out: &mut Vec<Node>) {
pub(crate) fn leaves(n: &Node, out: &mut Vec<Node>) {
each_leaf(n, &mut |l| out.push(l.clone()));
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result<DcsArt> {
};
let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref())
.ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?;
let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero));
let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip };
let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect();
Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings })
+55 -101
View File
@@ -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");
@@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[
"text.fonts",
"text.getRange",
"text.glyphAlternates",
"text.glyphCategories",
"text.insertInline",
"text.missingFonts",
"text.replaceFont",
+7 -4
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Colors",
[],
None,
"{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
"{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}",
always,
randomize
),
@@ -1746,8 +1746,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?);
let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?);
// Each new color with its row's tint and model: a tint moves with its color, and goes when
// the color changes; a model moves with its color.
let mut news: Vec<(Color, f32, Option<ModelRule>)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
// the color changes; a model moves with its color. A row with no current colors recolors
// nothing, so it keeps its new color and takes no other row's.
let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some();
let mut news: Vec<(Color, f32, Option<ModelRule>)> =
rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect();
if order {
rng.shuffle(&mut news);
}
@@ -1765,7 +1768,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|r| {
let (to, tint, model) =
if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) };
let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::<Vec<_>>(), "to": to.as_ref().map(key_str)});
if r.exclude {
row["exclude"] = json!(true);
+9 -4
View File
@@ -234,8 +234,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
let item = item_target(s, p, C)?.of_kind(s, false);
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
let new_art = no_targets(&ids, p);
let given = !ids.is_empty();
// The art of a graph design in a series keeps the design's stroke.
ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
// With only design art, the weight for new art stays as it is too.
let only_design_art = given && ids.is_empty();
if item == ItemTarget::Top {
// Images and symbol instances take no stroke from the panel.
let d = &s.doc()?.doc;
@@ -329,7 +332,9 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
})?;
// Commit the new-art template only after the complete request is validated
// and the selected artwork edit has succeeded.
if let Some(w) = change.weight {
if let Some(w) = change.weight
&& !only_design_art
{
s.paint.stroke_width = w;
}
if new_art && let Some(st) = s.new_art_stroke_mut() {
@@ -372,7 +377,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
}
return Ok(json!({"objects": 0}));
}
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, c)?;
let label = if up { "Stroke Weight Up" } else { "Stroke Weight Down" };
edit_items(s, &ids, item, None, c, label, false, |n, index| {
if index.is_none()
@@ -517,7 +522,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result<Value> {
let ids = item.targets(s, p)?;
let new_art = no_targets(&ids, p);
// The art of a graph design in a series keeps the design's stroke.
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
let arrows_and_profile = |st: &mut StrokeLayer| {
if let Some(sc) = scale {
st.arrow_scale = sc;
+18
View File
@@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
};
d.symbols[index].art = Arc::new(new_art);
follow_objects(d, &se.symbol, (&old, old_group), (&art, group));
// A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the
// editing layer shows the snapped art.
if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) {
let stored = &d.symbols[index].art;
let snapped: Vec<Arc<Node>> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] };
let mut snapped = snapped.into_iter().map(|n| {
let mut n = (*n).clone();
n.transform(se.xf, false);
Arc::new(n)
});
if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) {
for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) {
if let Some(n) = snapped.next() {
*c = n;
}
}
}
}
if let Some(e) = d.symbol_edit.as_mut() {
e.changed = true;
e.group = group;
+2 -1
View File
@@ -499,12 +499,13 @@ fn instance(name: &str) -> Node {
}
/// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice
/// guides) given to symbol `to` of `d`.
/// guides, Align to Pixel Grid) given to symbol `to` of `d`.
fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) {
set_natural_size(d, to, Some(natural_size(src, from)));
d.set_symbol_registration(to, src.symbol_registration(from));
d.set_symbol_export_type(to, src.symbol_export_type(from));
d.set_symbol_nine_slice(to, src.symbol_nine_slice(from));
d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from));
}
fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo {
File diff suppressed because one or more lines are too long
+1
View File
@@ -255,6 +255,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
("kinsoku", json!(v.kinsoku)),
("kinsoku_type", json!(v.kinsoku_type)),
("bunri_kinshi", json!(v.bunri_kinshi)),
("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)),
("roman_hanging", json!(v.roman_hanging)),
("kashida", json!(v.kashida)),
("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)),
+40 -3
View File
@@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
.collect();
let refs: Vec<&TextObject> = frames.iter().collect();
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, &paras);
for (id, part) in live.iter().zip(parts) {
let texts: Vec<String> = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect();
let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::<Vec<_>>());
for ((id, part), lead) in live.iter().zip(parts).zip(leads) {
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) {
let mut next = (**t).clone();
next.runs = part.runs;
@@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|| part.list_count != t.list_count
|| part.list_level_counts != t.list_level_counts
|| continues != t.first_para_continues
|| lead != t.first_para_lead
{
t.runs = next.runs;
t.para = next.para;
@@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
t.list_count = part.list_count;
t.list_level_counts = part.list_level_counts;
t.first_para_continues = continues;
t.first_para_lead = lead;
refresh_bounds(t);
}
}
@@ -384,17 +388,42 @@ pub(crate) fn mark_continued(doc: &mut Document) {
let live: Vec<NodeId> = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect();
let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect();
let marks = vectorcraft_text::thread::continued(&frames);
for (id, on) in live.iter().zip(marks) {
let texts: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
let leads = first_para_leads(&texts, &marks);
for ((id, on), lead) in live.iter().zip(marks).zip(leads) {
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
&& t.first_para_continues != on
&& (t.first_para_continues != on || t.first_para_lead != lead)
{
t.first_para_continues = on;
t.first_para_lead = lead;
refresh_bounds(t);
}
}
}
}
/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and
/// whether each one's first paragraph `continues` from the frame before: the last character of
/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over
/// the frames: each frame's lead is carried forward to the next.
fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec<Option<char>> {
// The lead the next frame takes when its first paragraph continues from this one.
let mut carry = None;
texts
.iter()
.enumerate()
.map(|(k, text)| {
#[cfg(test)]
LEAD_SCANS.with(|c| c.set(c.get() + 1));
let lead = carry.filter(|_| continues.get(k) == Some(&true));
let tail = text.rsplit('\n').next().unwrap_or(text);
// A paragraph break in this frame ends the paragraph the lead came from.
carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len()));
lead
})
.collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's
@@ -402,6 +431,8 @@ thread_local! {
static THREAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`story_in`] went through a thread's frames on this thread.
static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many frame texts [`first_para_leads`] went through on this thread.
static LEAD_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's
@@ -417,6 +448,12 @@ pub(crate) fn story_builds() -> usize {
STORY_BUILDS.with(std::cell::Cell::get)
}
/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread.
#[cfg(test)]
pub(crate) fn lead_scans() -> usize {
LEAD_SCANS.with(std::cell::Cell::get)
}
/// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a
/// path; empty when `id` is in no thread or the thread has fewer than two such frames.
pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec<NodeId> {
+54
View File
@@ -2226,3 +2226,57 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing()
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0);
}
/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of
/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that
/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph
/// carries none. Flowing the story and opening a file both set it.
#[test]
fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() {
let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::<Vec<_>>(), continues);
assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]);
assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]);
assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]);
assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]);
assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]);
assert_eq!(leads(&[], &[]), Vec::<Option<char>>::new());
// Opening a file marks the frames as they were saved.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
let mut ids = Vec::new();
for (x, text) in [(10, "日時"), (200, "々す")] {
let id =
s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
ids.push(NodeId(id));
}
let mut d = (*s.doc().unwrap().doc).clone();
d.text_threads = vec![ids.clone()];
mark_continued(&mut d);
let tb = text_of(&d, ids[1]).unwrap();
assert!(tb.first_para_continues);
assert_eq!(tb.first_para_lead, Some('時'));
// Flowing the story through the frames sets it from the text each frame now holds.
reflow(&d.clone(), &mut d);
let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap());
assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す");
assert!(tb.first_para_continues);
assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text()));
}
/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one
/// pass over the frames, each frame's text gone through once, not once for every frame after it.
#[test]
fn continued_frame_leads_go_through_each_frame_once() {
let n = 2000;
let mut texts = vec!["時".to_string()];
texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1));
let continues: Vec<bool> = (0..n).map(|k| k > 0).collect();
let before = lead_scans();
let leads = first_para_leads(&texts, &continues);
assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before);
assert_eq!(leads.first(), Some(&None));
assert!(leads.iter().skip(1).all(|l| *l == Some('時')));
// A paragraph break stops the carry, and a frame that starts a paragraph carries nothing.
let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]);
assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]);
}

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