#4943: keep upstream parity notes with the language-list rows

Conflicts were only the status lines and revision history in the type and UI parity docs. Both sides are kept. Language entries, catalogs and tests merged cleanly, so local CI was not rerun.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ruchirguitarandCursor committed 2026-11-09 12:09:49 +05:30
commit 6fd8385bf4
536 files changed
+50671 -3609

No files matched your search

Generated
+195 -14
View File
@@ -1059,7 +1059,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -2844,6 +2844,182 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "jxl-bitstream"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-coding"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
dependencies = [
"jxl-bitstream",
"tracing",
]
[[package]]
name = "jxl-color"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-frame"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-grid"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-image"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
dependencies = [
"jxl-bitstream",
"jxl-grid",
"jxl-oxide-common",
"tracing",
]
[[package]]
name = "jxl-jbr"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-modular"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-jbr",
"jxl-oxide-common",
"jxl-render",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "jxl-oxide-common"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
dependencies = [
"jxl-bitstream",
]
[[package]]
name = "jxl-render"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
dependencies = [
"bytemuck",
"jxl-bitstream",
"jxl-coding",
"jxl-color",
"jxl-frame",
"jxl-grid",
"jxl-image",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"jxl-vardct",
"tracing",
]
[[package]]
name = "jxl-threadpool"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
dependencies = [
"tracing",
]
[[package]]
name = "jxl-vardct"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
dependencies = [
"jxl-bitstream",
"jxl-coding",
"jxl-grid",
"jxl-modular",
"jxl-oxide-common",
"jxl-threadpool",
"tracing",
]
[[package]]
name = "keyboard-types"
version = "0.8.3"
@@ -6292,6 +6468,9 @@ dependencies = [
"hayro-jpeg2000",
"heic-rs",
"image",
"jxl-color",
"jxl-grid",
"jxl-oxide",
"kurbo 0.13.1",
"log",
"proptest",
@@ -6323,6 +6502,8 @@ dependencies = [
"vectorcraft-tools",
"vectorcraft-trace",
"wat",
"zune-core 0.5.3",
"zune-jpegxl",
]
[[package]]
@@ -6330,6 +6511,7 @@ name = "vectorcraft-eps"
version = "0.21.0"
dependencies = [
"craft-pdf",
"encoding_rs",
"fax",
"flate2",
"hayro-ccitt",
@@ -6384,6 +6566,7 @@ dependencies = [
name = "vectorcraft-js"
version = "0.21.0"
dependencies = [
"chrono",
"proptest",
"unicode-general-category",
]
@@ -6469,6 +6652,8 @@ dependencies = [
name = "vectorcraft-plugins"
version = "0.21.0"
dependencies = [
"craft-vectorcraft-format",
"image",
"log",
"serde",
"serde_json",
@@ -8039,7 +8224,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -8054,18 +8238,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
@@ -8096,6 +8268,15 @@ dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zune-jpegxl"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
]
[[package]]
name = "zvariant"
version = "5.15.1"
+14 -1
View File
@@ -22,7 +22,7 @@ craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63
# 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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -99,12 +99,25 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
# decoders, read directly (the image crate converts CMYK to RGB).
tiff = "0.11"
zune-jpeg = "0.5"
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
# built without its default `rayon` feature and decodes on one thread.
jxl-oxide = { version = "0.12.6", default-features = false }
# jxl-oxide's color conversions, run on colors after their alpha is divided out.
jxl-color = "0.11.0"
# jxl-oxide's buffer allocation error, told apart from other decoding errors.
jxl-grid = "0.6.2"
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
zune-core = "0.5"
# ui
egui = "0.37"
+1 -1
View File
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, Print, Package).
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package).
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
+1
View File
@@ -4,6 +4,7 @@
- Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged.
- Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged.
- UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged.
- PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document.
- PDF.W1: PDF export and print composition use the shared optional writer for configuration, metadata, font preparation and guarded finalization; drawing and output policy remain app-owned.
+34 -7
View File
@@ -5,7 +5,7 @@
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -101,7 +101,7 @@ USAGE:
vectorcraft-cli commands
Print the command catalogue as JSON.
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects
resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
@@ -114,7 +114,10 @@ USAGE:
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
even where that draws differently from its PDF part or page (which can be older), as long as
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
it can be read. --legacy-name-encoding reads the names in a .ai's or an EPS's editing data
that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles,
swatches, brushes, symbols, variables and data sets, and data sets' text values) in
windows-1252 (the default), macintosh, windows-949, shift_jis, gbk or big5. A PDF OUT omits the embedded native document unless --preserve-editing is
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
attachment is written the result's warnings say so (it is left out, with its own warning, for
--artboard or a --range without every artboard).
@@ -302,8 +305,20 @@ fn commands() -> Result<(), String> {
}
fn convert(args: &[String]) -> Result<(), String> {
let valued =
["--scale", "-s", "--ppi", "--artboard", "-a", "--range", "-r", "--decimals", "--ai-version", "--hidden-objects", "--transparent-images"];
let valued = [
"--scale",
"-s",
"--ppi",
"--artboard",
"-a",
"--range",
"-r",
"--decimals",
"--ai-version",
"--hidden-objects",
"--transparent-images",
"--legacy-name-encoding",
];
if help_requested(args, &valued) {
return help();
}
@@ -312,6 +327,9 @@ fn convert(args: &[String]) -> Result<(), String> {
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
let mut ppi = None::<f64>;
let mut decimals = None::<u64>;
// The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s
// `legacyNameEncoding`; the engine checks it.
let mut legacy_names = None::<String>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
let mut legacy: Vec<(&str, String)> = vec![];
@@ -334,6 +352,9 @@ fn convert(args: &[String]) -> Result<(), String> {
"--replace-lossy" => replace_lossy = true,
"--editing-data" => editing_data = true,
"--preserve-editing" => preserve_editing = true,
"--legacy-name-encoding" => {
legacy_names = Some(it.next().cloned().ok_or("--legacy-name-encoding needs an encoding such as windows-949")?);
}
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
@@ -346,8 +367,14 @@ fn convert(args: &[String]) -> Result<(), String> {
return Err("a .ait template holds every artboard: --artboard and --range don't apply".into());
}
let mut h = Headless::new();
let opened = if editing_data {
let params = json!({"path": input, "editingData": "always"});
let opened = if editing_data || legacy_names.is_some() {
let mut params = json!({"path": input});
if editing_data {
params["editingData"] = json!("always");
}
if let Some(e) = &legacy_names {
params["legacyNameEncoding"] = json!(e);
}
h.call("engine.execute", json!({"command": "document.open", "params": params})).map_err(|e| format!("open {input}: {e}"))?
} else {
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?
+3
View File
@@ -92,6 +92,9 @@ impl eframe::App for App {
}
fn on_exit(&mut self) {
file_access::unconfined(|| save_prefs(&self.app));
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.app.start_pending_update();
end_before_teardown(self.frames);
}
}
+1 -1
View File
@@ -97,7 +97,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame};
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
+26
View File
@@ -168,6 +168,11 @@ fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
}
}
/// Fields that a read fills in from other fields when the file lacks them
/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them
/// whenever the file lacks them, so the next read does not fill them in again from a changed field.
const DERIVED: &[&str] = &["help_bar"];
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
/// different settings keep both. A field both changed takes this window's value (it saves last).
@@ -219,6 +224,13 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
}
}
}
for key in DERIVED {
if !out.contains_key(*key)
&& let Some(v) = mine.get(*key)
{
out.insert((*key).to_string(), v.clone());
}
}
if use_mine {
match mine.get("action_set") {
Some(v) => {
@@ -383,6 +395,20 @@ mod tests {
assert!(!same_lasting(&base, &mine));
}
/// A file from before the Help Bar setting: the read shows the Help Bar with the status bar.
/// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`,
/// so the next read does not hide it with the status bar. A value on disk is kept.
#[test]
fn a_help_bar_setting_the_file_lacks_is_saved() {
let base = json!({"status_bar": true, "help_bar": true});
let mine = json!({"status_bar": false, "help_bar": true});
let on_disk = json!({"status_bar": true});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true}));
// Another window saved its own Help Bar setting: it stays.
let on_disk = json!({"status_bar": true, "help_bar": false});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false}));
}
/// One window deleted the first Actions set and saved; this one made the second set current.
/// The saved index follows that set to its place in the merged list.
#[test]
+75 -1
View File
@@ -193,7 +193,8 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
/// decides, and `VECTORCRAFT_TITLEBAR` takes precedence over both.
/// decides, and `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` takes precedence over
/// both.
#[test]
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
@@ -245,6 +246,79 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
use craft_window::Frame;
assert!(super::system_title_bar_applies(true, false));
assert!(!super::system_title_bar_applies(true, true));
assert!(!super::system_title_bar_applies(false, false));
assert!(!super::system_title_bar_applies(false, true));
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
}
}
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
/// The variable is process-wide and read once, so each value runs in a separate test process.
#[test]
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
if std::env::var_os(CHILD).is_none() {
for value in ["app", "system", "desktop", "unknown"] {
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let spawning = super::spawning();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
.env(CHILD, "1")
.env("VECTORCRAFT_TITLEBAR", value)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
drop(spawning);
let output = child.unwrap().wait_with_output().unwrap();
assert!(
output.status.success(),
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
return;
}
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
"system" | "desktop" => false,
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// The file extensions the macOS bundle declares: its document types and its own exported type.
fn plist_extensions(plist: &str) -> Vec<&str> {
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
+21 -10
View File
@@ -41,7 +41,8 @@ pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
/// `false` (the default). This preference forces the desktop/native frame back on.
/// `false` (the default). This preference forces the desktop/native frame back on unless
/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]).
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
}
@@ -55,8 +56,8 @@ pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiSta
/// Whether the app draws the frame on this start, before the System Title Bar preference is
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when it is
/// set; VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when the
/// variable is set to `app`, `system` or `desktop`;VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
/// decides.
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
@@ -87,12 +88,19 @@ fn probed_choice() -> &'static craft_window::Choice {
}
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
/// User Interface › VectorCraft Title Bar on Every Desktop does not apply while it is set. Always
/// `false` on macOS and Windows.
/// User Interface › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while
/// it is set to `app`, `system` or `desktop`. Always `false` on macOS and Windows.
pub(crate) fn titlebar_from_env() -> bool {
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
}
/// Whether System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR`
/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is
/// set in.
pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool {
opted_into_system && !from_env
}
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
/// decided and the user's System Title Bar preference.
///
@@ -100,9 +108,10 @@ pub(crate) fn titlebar_from_env() -> bool {
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
/// title bar; the preference always forces the native frame back on.
/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set
/// to one of those values ([`system_title_bar_applies`]).
///
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
@@ -124,16 +133,18 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference. Call once at startup, before [`native_options`].
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
/// before [`native_options`].
///
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins,
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
let choice = probed_choice();
let opted_into_system = opted_into_system_title_bar(saved);
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
// ignores the frame there).
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
+3 -3
View File
@@ -1227,10 +1227,10 @@ impl<'a> Scene<'a> {
let Some(&first) = run.first() else { continue };
let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte);
let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo);
// A right-to-left paragraph's marker is drawn with its tab first and its number's
// period at the number's left; the TEXT entity holds the characters in that order.
// A right-to-left paragraph's marker is drawn with its number's period at the
// number's left; the TEXT entity holds the characters in that order.
let marker = chunk.first().and_then(|(_, _, m)| *m).map(|m| match m.text.strip_suffix('.') {
Some(number) if m.tab == m.glyphs.start => format!(".{number}"),
Some(number) if layout.glyphs.get(m.tab).is_some_and(|g| g.rtl) => format!(".{number}"),
_ => m.text.clone(),
});
let Some(s) = marker.as_deref().or_else(|| plain.get(lo..hi).map(str::trim_end)).filter(|s| !s.trim().is_empty()) else { continue };
+21 -4
View File
@@ -1076,15 +1076,15 @@ fn a_bullet_is_text_of_its_own_before_its_paragraph() {
/// A numbered list paragraph's number and period are a TEXT entity of their own where they are
/// drawn, in the order they are drawn: in a right-to-left paragraph the period comes first, at the
/// number's left.
/// number's left, with the marker aligned left or right.
#[test]
fn a_number_is_text_of_its_own_before_its_paragraph() {
use vectorcraft_doc::text::{NumberStyle, ParaList};
let numbered = |text: &str, count: u32| {
use vectorcraft_doc::text::{ListAlign, NumberStyle, ParaList};
let numbered_aligned = |text: &str, count: u32, align: ListAlign| {
let mut d = text_doc(text, 20.0);
let id = d.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic));
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic).aligned(align));
t.para.left_indent = 30.0;
t.para.first_line_indent = -30.0;
t.list_count = count;
@@ -1092,10 +1092,27 @@ fn a_number_is_text_of_its_own_before_its_paragraph() {
let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap();
entities(&out).iter().map(|e| (get(e, 1).map(str::to_string), all(e, 10)[0])).collect::<Vec<_>>()
};
let numbered = |text: &str, count: u32| numbered_aligned(text, count, ListAlign::Left);
assert_eq!(numbered("Item", 11), [(Some("12.".to_string()), 10.0), (Some("Item".to_string()), 40.0)]);
let rtl = numbered("שלום", 11);
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
assert!(rtl[1].1 > rtl[0].1, "the number right of the text: {rtl:?}");
// Aligned right, the number keeps its order and moves right, against the text.
let right = numbered_aligned("Item", 11, ListAlign::Right);
assert_eq!((right[0].0.as_deref(), right[1].clone()), (Some("12."), (Some("Item".to_string()), 40.0)));
assert!(right[0].1 > 10.0 && right[0].1 < 40.0, "{right:?}");
let rtl = numbered_aligned("שלום", 11, ListAlign::Right);
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
// A mixed paragraph: the period follows the paragraph's direction, not the script of the
// words it holds, with either alignment.
let marker = |text: &str, align: ListAlign| {
let out = numbered_aligned(text, 11, align);
out.into_iter().filter_map(|(s, _)| s).find(|s| s.contains("12")).unwrap_or_default()
};
for align in [ListAlign::Left, ListAlign::Right] {
assert_eq!(marker("Item שלום", align), "12.", "{align:?}");
assert_eq!(marker("שלום Item", align), ".12", "{align:?}");
}
}
/// Area type that Shrink Text to Fit scales down is written at the height it draws at.
+176 -102
View File
@@ -1,19 +1,26 @@
//! "VectorCraft Generic CMYK (SWOP-like)": our own parametric press model.
//!
//! We can't redistribute Adobe's or ECI's characterisation profiles, so the built-in CMYK space is
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*: the numbers
//! are rounded, typical values for coated web offset, not a measured dataset.
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*. Two of its
//! figures are published values for SWOP printing: the tone value increase of each ink at 40% and
//! 50% from CGATS TR 001 (<https://registry.color.org/cmyk-registry/cgats_tr_001>), and the 300%
//! total ink limit (<https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications>).
//! The paper, solid and overprint colors and the black-generation curve are VectorCraft's own values.
//!
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area is widened by a parabolic dot-gain
//! curve (`a + 4·g·a·(1−a)`, i.e. `g` gain at 50%); the effective areas mix the eight CMY
//! Neugebauer primaries with Demichel weights; black is mixed in the same way against
//! "primary + K" colours whose optical densities add but saturate towards a maximum density
//! (normalised so K on paper is exact), so rich blacks don't multiply to an unrealistic depth.
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area `a` is widened by a tone curve
//! `a + 4·g·a·(1−a)·(1 + s·(2a−1))` that passes through the TR 001 tone value increase at 50%
//! (`g`) and 40% (which sets `s`). The effective areas mix the 16 Neugebauer primaries (paper and
//! every solid and overprint of C, M, Y and K, media-relative) with Demichel weights, linearly in
//! XYZ, so a single ink's colorimetric tone value increase (Murray–Davies) is the TR 001 value.
//! * **Inverse (Lab → CMYK):** damped, bounded Gauss–Newton on the forward model solves CMY for a
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the grey component
//! `min(C, M, Y)`, map it through the black-generation curve to K, re-solve CMY. Under-colour
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the gray component
//! `min(C, M, Y)`, add [`BlackGeneration::shortfall`] for each L* point by which that solve stays
//! lighter than the target, map the sum through the black curve to K, re-solve CMY. Under-color
//! removal enforces the total area coverage (TAC) limit by adding K and re-solving, then scaling
//! CMY as a last resort.
//! CMY as a last resort. The black point, which source black separates to and which displays as
//! black with black-point compensation, is [`BlackGeneration::black_point_k`] black with neutral
//! CMY filling the TAC. With compensation, a build darker than it in every XYZ channel also
//! displays as black (see [`GenericCmyk::display_xyz`]).
//! * **Rendering intents:** colorimetric intents map the source white to paper (relative) or not
//! (absolute) and clip; perceptual applies black-point compensation plus soft chroma compression
//! against a gamut boundary descriptor (segment maxima of the forward model); saturation keeps
@@ -24,50 +31,82 @@ use std::sync::OnceLock;
use super::Intent;
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
/// Black generation strength.
/// Black generation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlackGeneration {
/// Grey component below which no black is generated.
pub start: f32,
/// Maximum black.
pub max_k: f32,
/// Curve exponent (>1 = lighter black in the midtones).
pub gamma: f32,
/// The black curve as `(x, K)` knots with rising `x`, read by linear interpolation. `x` is the
/// gray component of the solve without black plus [`Self::shortfall`] per L* point by which
/// that solve stays lighter than the target.
pub curve: [(f32, f32); 13],
/// Added to the gray component for each L* point the black-free solve stays too light.
pub shortfall: f32,
/// Black of the black point, whose CMY is neutral and fills the TAC.
pub black_point_k: f32,
}
/// Parameters of the parametric press model.
#[derive(Clone, Debug)]
pub struct GenericCmykParams {
pub name: &'static str,
/// Paper color (absolute Lab, D50).
pub paper: Lab,
/// Solid overprints, Demichel order: C, M, CM, Y, CY, MY, CMY.
pub solids: [Lab; 7],
pub black: Lab,
/// Dot gain at 50% per ink (C, M, Y, K).
pub dot_gain: [f32; 4],
/// Media-relative Lab of the solids and overprints, Demichel order (index `c | m<<1 | y<<2 |
/// k<<3`, paper left out): C, M, CM, Y, CY, MY, CMY, then K, CK, MK, CMK, YK, CYK, MYK, CMYK.
pub primaries: [Lab; 15],
/// Tone value increase at 50% per ink (C, M, Y, K).
pub tvi50: [f32; 4],
/// Tone value increase at 40% per ink (C, M, Y, K).
pub tvi40: [f32; 4],
/// Total area coverage limit (sum of inks, 1.0 = 100%).
pub tac: f32,
pub bg: BlackGeneration,
}
/// Rounded, typical SWOP-like values (not measured data).
/// The built-in SWOP-like press: TR 001 tone value increase, a 300% ink limit, and VectorCraft's
/// own paper, primaries and black curve.
pub fn swop_like() -> GenericCmykParams {
GenericCmykParams {
name: super::GENERIC_CMYK,
paper: Lab::new(93.0, -0.5, 2.5),
solids: [
Lab::new(55.0, -37.0, -50.0), // C
Lab::new(48.0, 74.0, -3.0), // M
Lab::new(24.0, 22.0, -46.0), // CM (blue)
Lab::new(89.0, -5.0, 93.0), // Y
Lab::new(50.0, -65.0, 27.0), // CY (green)
Lab::new(47.0, 68.0, 48.0), // MY (red)
Lab::new(24.0, 1.0, 0.0), // CMY
primaries: [
Lab::new(65.7, -42.6, -47.2), // C
Lab::new(55.5, 76.2, -9.4), // M
Lab::new(31.1, 20.3, -49.7), // CM (blue)
Lab::new(96.2, -7.0, 90.1), // Y
Lab::new(61.0, -68.4, 30.1), // CY (green)
Lab::new(55.0, 69.8, 45.0), // MY (red)
Lab::new(28.3, 0.7, -0.5), // CMY
Lab::new(21.5, 0.8, -0.9), // K
Lab::new(15.9, -8.4, -10.0), // CK
Lab::new(14.7, 15.4, -1.0), // MK
Lab::new(11.2, 8.9, -6.6), // CMK
Lab::new(20.2, -2.4, 12.0), // YK
Lab::new(15.7, -14.6, 4.6), // CYK
Lab::new(14.5, 11.2, 5.7), // MYK
Lab::new(11.0, -0.7, 0.1), // CMYK
],
black: Lab::new(19.0, 0.5, 0.5),
dot_gain: [0.20, 0.20, 0.20, 0.22],
tvi50: [0.200, 0.176, 0.168, 0.216],
tvi40: [0.200, 0.173, 0.167, 0.219],
tac: 3.0,
bg: BlackGeneration { start: 0.1, max_k: 0.95, gamma: 1.25 },
bg: BlackGeneration {
curve: [
(0.0, 0.0),
(0.25, 0.0),
(0.35, 0.006),
(0.45, 0.059),
(0.55, 0.139),
(0.65, 0.23),
(0.75, 0.322),
(0.85, 0.41),
(0.95, 0.511),
(1.05, 0.6),
(1.2, 0.733),
(1.35, 0.858),
(1.5, 1.0),
],
shortfall: 0.03,
black_point_k: 0.9,
},
}
}
@@ -83,11 +122,12 @@ const GBD_H: usize = 72; // 5° bins
pub struct GenericCmyk {
pub params: GenericCmykParams,
/// XYZ of the 8 CMY primaries (index = c | m<<1 | y<<2), without and with K.
prim: [[f32; 3]; 8],
prim_k: [[f32; 3]; 8],
/// Media-relative XYZ of the 16 primaries (index = c | m<<1 | y<<2 | k<<3; 0 is paper).
prim: [[f32; 3]; 16],
/// Shape `s` of each ink's tone curve, from its 40% and 50% tone value increase.
skew: [f32; 4],
paper_xyz: [f32; 3],
/// Media-relative XYZ of the darkest printable black (for black-point compensation).
/// Media-relative XYZ of the black point (for black-point compensation).
black_rel: [f32; 3],
gbd: OnceLock<Gbd>,
}
@@ -95,37 +135,17 @@ pub struct GenericCmyk {
impl GenericCmyk {
pub fn new(params: GenericCmykParams) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [[0.0f32; 3]; 8];
prim[0] = paper_xyz;
for (p, lab) in prim[1..].iter_mut().zip(params.solids.iter()) {
*p = lab_to_xyz(*lab);
let mut prim = [D50; 16];
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
*p = lab_to_xyz(*lab).map(|v| v.max(1e-6));
}
let k_xyz = lab_to_xyz(params.black);
// Black over other inks: optical densities add, but saturate towards a maximum density
// (ink trapping / surface reflection), normalised so that K on paper is exact.
const D_MAX: f32 = 2.0;
let sat = |d: f32| D_MAX * (1.0 - (-d / D_MAX).exp());
let mut prim_k = [[0.0f32; 3]; 8];
for i in 0..8 {
for ch in 0..3 {
let di = -(prim[i][ch] / paper_xyz[ch]).max(1e-6).log10();
let dk = -(k_xyz[ch] / paper_xyz[ch]).max(1e-6).log10();
let d = sat(di + dk) * dk / sat(dk).max(1e-6);
prim_k[i][ch] = paper_xyz[ch] * 10f32.powf(-d.max(di));
}
}
let mut g = Self { params, prim, prim_k, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
// Darkest black within TAC: search a few rich blacks.
let mut best = [1.0f32; 3];
for k in [0.8f32, 0.9, 1.0] {
let rest = (g.params.tac - k).max(0.0) / 3.0;
let cmy = rest.min(1.0);
let x = g.to_xyz_rel([cmy, cmy, cmy, k]);
if x[1] < best[1] {
best = x;
}
}
g.black_rel = best;
// The curve's increase at 40% is 0.96·g·(1 − 0.2·s), so `s` follows from the 40% value.
let skew = [0, 1, 2, 3].map(|i| {
let g = params.tvi50[i];
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
});
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
g.black_rel = g.to_xyz_rel(g.black_point_build());
g
}
@@ -133,35 +153,81 @@ impl GenericCmyk {
self.params.name
}
fn gain(a: f32, g: f32) -> f32 {
let a = a.clamp(0.0, 1.0);
(a + 4.0 * g * a * (1.0 - a)).clamp(0.0, 1.0)
/// The black point: [`BlackGeneration::black_point_k`] black, with C, M and Y
/// chosen so that they fill the TAC and the color is neutral (a* = b* = 0).
pub fn black_point_build(&self) -> [f32; 4] {
let k = self.params.bg.black_point_k.clamp(0.0, 1.0);
let rest = (self.params.tac - k).clamp(0.0, 3.0);
let build = |c: f32, m: f32| [c, m, (rest - c - m).clamp(0.0, 1.0), k];
let ab = |c: f32, m: f32| {
let l = self.to_lab_rel(build(c, m));
[l.a, l.b]
};
let lo = (rest - 2.0).max(0.0);
let hi = rest.min(1.0);
let (mut c, mut m) = ((rest / 3.0).clamp(lo, hi), (rest / 3.0).clamp(lo, hi));
for _ in 0..30 {
let r = ab(c, m);
if r[0].abs() + r[1].abs() < 1e-4 {
break;
}
let h = 1e-3;
let rc = ab(c - h, m);
let rm = ab(c, m - h);
let j = [[(r[0] - rc[0]) / h, (r[0] - rm[0]) / h], [(r[1] - rc[1]) / h, (r[1] - rm[1]) / h]];
let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
if det.abs() < 1e-9 {
break;
}
let dc = (-r[0] * j[1][1] + r[1] * j[0][1]) / det;
let dm = (-r[1] * j[0][0] + r[0] * j[1][0]) / det;
c = (c + dc.clamp(-0.1, 0.1)).clamp(lo, hi);
m = (m + dm.clamp(-0.1, 0.1)).clamp(lo, hi);
// Yellow takes the rest, so keep it within 0..1 as well.
let y = rest - c - m;
if y > 1.0 {
c += (y - 1.0) / 2.0;
m += (y - 1.0) / 2.0;
} else if y < 0.0 {
c += y / 2.0;
m += y / 2.0;
}
c = c.clamp(lo, hi);
m = m.clamp(lo, hi);
}
build(c.clamp(lo, hi), m.clamp(lo, hi))
}
/// Effective dot area of ink `i` at nominal area `a`: the TR 001-style tone curve.
fn gain(&self, i: usize, a: f32) -> f32 {
let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 0.0 };
let g = self.params.tvi50[i];
(a + 4.0 * g * a * (1.0 - a) * (1.0 + self.skew[i] * (2.0 * a - 1.0))).clamp(0.0, 1.0)
}
/// CMYK (0..1) → absolute XYZ (D50).
pub fn to_xyz(&self, cmyk: [f32; 4]) -> [f32; 3] {
let dg = self.params.dot_gain;
let c = Self::gain(cmyk[0], dg[0]);
let m = Self::gain(cmyk[1], dg[1]);
let y = Self::gain(cmyk[2], dg[2]);
let k = Self::gain(cmyk[3], dg[3]);
let mut out = [0.0f32; 3];
for i in 0..8 {
let w = (if i & 1 != 0 { c } else { 1.0 - c }) * (if i & 2 != 0 { m } else { 1.0 - m }) * (if i & 4 != 0 { y } else { 1.0 - y });
if w == 0.0 {
continue;
}
for (ch, o) in out.iter_mut().enumerate() {
*o += w * ((1.0 - k) * self.prim[i][ch] + k * self.prim_k[i][ch]);
}
}
out
let x = self.to_xyz_rel(cmyk);
[x[0] * self.paper_xyz[0] / D50[0], x[1] * self.paper_xyz[1] / D50[1], x[2] * self.paper_xyz[2] / D50[2]]
}
/// Media-relative XYZ (paper = D50 white).
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
let x = self.to_xyz(cmyk);
[x[0] * D50[0] / self.paper_xyz[0], x[1] * D50[1] / self.paper_xyz[1], x[2] * D50[2] / self.paper_xyz[2]]
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
let mut out = [0.0f32; 3];
for (i, p) in self.prim.iter().enumerate() {
let mut w = 1.0;
for (bit, a) in e.iter().enumerate() {
w *= if i & (1 << bit) != 0 { *a } else { 1.0 - a };
}
if w == 0.0 {
continue;
}
for (o, v) in out.iter_mut().zip(p) {
*o += w * v;
}
}
out
}
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
@@ -174,7 +240,9 @@ impl GenericCmyk {
/// Display XYZ: media-relative (paper shows as white) or absolute (simulate paper colour).
/// With `bpc` (media-relative only) the press black displays as black, undoing the
/// compensation [`Self::gamut_map`] applies on the way in, so sRGB black separated to the
/// darkest rich black shows as black again.
/// black point shows as black again. Each XYZ channel is clamped at 0 on its own, so a build
/// darker than the black point in every channel shows as black, and one darker in only some
/// channels shows as a colored near-black.
pub fn display_xyz(&self, cmyk: [f32; 4], absolute: bool, bpc: bool) -> [f32; 3] {
if absolute {
return self.to_xyz(cmyk);
@@ -192,7 +260,7 @@ impl GenericCmyk {
xyz_to_srgb(self.display_xyz(cmyk, absolute, bpc))
}
/// Lab of the darkest printable black (media-relative).
/// Lab of the black point (media-relative), see [`Self::black_point_build`].
pub fn black_point(&self) -> Lab {
xyz_to_lab(self.black_rel)
}
@@ -283,12 +351,21 @@ impl GenericCmyk {
rgb.map(|v| ((1.0 - v - k) / d).clamp(0.0, 1.0))
}
fn black_for_grey(&self, grey: f32) -> f32 {
let bg = self.params.bg;
if grey <= bg.start {
return 0.0;
/// Black for `x` on the black curve (see [`BlackGeneration::curve`]).
fn black_for(&self, x: f32) -> f32 {
let curve = &self.params.bg.curve;
let mut prev = curve[0];
if x <= prev.0 {
return prev.1.clamp(0.0, 1.0);
}
(((grey - bg.start) / (1.0 - bg.start)).clamp(0.0, 1.0).powf(bg.gamma) * bg.max_k).clamp(0.0, 1.0)
for &(kx, kk) in &curve[1..] {
if x <= kx {
let t = if kx > prev.0 { (x - prev.0) / (kx - prev.0) } else { 1.0 };
return (prev.1 + (kk - prev.1) * t).clamp(0.0, 1.0);
}
prev = (kx, kk);
}
prev.1.clamp(0.0, 1.0)
}
/// Separate a media-relative Lab (already gamut-mapped) into CMYK with GCR/UCR and the TAC limit.
@@ -297,13 +374,10 @@ impl GenericCmyk {
return [0.0; 4];
}
let cmy0 = self.solve_cmy(target, 0.0, Self::initial_cmy(target, 0.0));
let grey = cmy0[0].min(cmy0[1]).min(cmy0[2]);
let mut k = self.black_for_grey(grey);
// If CMY alone can't get dark enough, black must carry the rest.
let gray = cmy0[0].min(cmy0[1]).min(cmy0[2]);
// When CMY alone can't get dark enough, black carries the rest.
let l0 = self.to_lab_rel([cmy0[0], cmy0[1], cmy0[2], 0.0]).l;
if l0 > target.l + 1.0 {
k = k.max(((l0 - target.l) / l0.max(1.0)).clamp(0.0, 1.0));
}
let mut k = self.black_for(gray + self.params.bg.shortfall * (l0 - target.l).max(0.0));
let mut cmy = if k > 0.0 { self.solve_cmy(target, k, Self::initial_cmy(target, k)) } else { cmy0 };
// UCR: trade CMY for K until within the TAC limit.
for _ in 0..6 {
+94 -15
View File
@@ -245,8 +245,8 @@ fn loads_system_cmyk_icc() {
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
}
/// With black-point compensation, sRGB black separates to the press's darkest black and that black
/// displays as black again (hex 000000 -> C67 M67 Y67 K100 -> 000000, not a dark grey).
/// With black-point compensation, sRGB black separates to the press's black point and that black
/// displays as black again (hex 000000 -> C75 M68 Y67 K90 -> 000000, not a dark gray).
#[test]
fn generic_cmyk_black_round_trips_with_bpc() {
let c = cms();
@@ -259,25 +259,104 @@ fn generic_cmyk_black_round_trips_with_bpc() {
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
}
/// A color whose solve holds cyan at 0 separates to the same inks when its values change by a few
/// float steps: hex ed1e79 with its red stepped one `f32` at a time over 4,001 values (about 0.00024
/// in all) stays within 0.001 on every ink.
/// Each ink's 40% and 50% tints gain like CGATS TR 001 (SWOP): the colorimetric tone value increase
/// (Murray–Davies on X for cyan, Y for magenta and black, Z for yellow) is C 20.0, M 17.6, Y 16.8 and
/// K 21.6 points at 50%, and C 20.0, M 17.3, Y 16.7 and K 21.9 points at 40%.
#[test]
fn generic_cmyk_tints_gain_like_tr001() {
let g = generic();
let tvi = |ink: usize, a: f32| {
let ch = [0, 1, 2, 1][ink];
let mut cmyk = [0.0f32; 4];
cmyk[ink] = a;
let tint = g.to_xyz_rel(cmyk)[ch];
cmyk[ink] = 1.0;
let solid = g.to_xyz_rel(cmyk)[ch];
let paper = g.to_xyz_rel([0.0; 4])[ch];
(paper - tint) / (paper - solid) - a
};
for (ink, (at50, at40)) in [(0.200, 0.200), (0.176, 0.173), (0.168, 0.167), (0.216, 0.219)].into_iter().enumerate() {
assert!((tvi(ink, 0.5) - at50).abs() < 0.002, "ink {ink} at 50%: {}", tvi(ink, 0.5));
assert!((tvi(ink, 0.4) - at40).abs() < 0.002, "ink {ink} at 40%: {}", tvi(ink, 0.4));
}
}
/// More of any ink never makes a Generic CMYK color lighter, in any XYZ channel: on a 10% grid of
/// builds within the 300% ink limit, adding 10% of one ink keeps X, Y and Z or lowers them.
#[test]
fn generic_cmyk_more_ink_is_never_lighter() {
let g = generic();
let steps = (0..=10).map(|i| i as f32 / 10.0);
for c in steps.clone() {
for m in steps.clone() {
for y in steps.clone() {
for k in steps.clone() {
let base = [c, m, y, k];
if base.iter().sum::<f32>() > 3.0 - 0.1 + 1e-4 {
continue;
}
let x0 = g.to_xyz_rel(base);
for ink in 0..4 {
if base[ink] >= 1.0 {
continue;
}
let mut more = base;
more[ink] += 0.1;
let x1 = g.to_xyz_rel(more);
assert!((0..3).all(|ch| x1[ch] <= x0[ch] + 1e-5), "{base:?} plus ink {ink}: {x0:?} to {x1:?}");
}
}
}
}
}
}
/// sRGB black separates to 90% black under neutral CMY that fills the 300% ink limit, light grays
/// carry no black, and black rises steadily from the light end of the gray ramp to the dark end.
#[test]
fn generic_cmyk_black_generation_follows_the_black_curve() {
let c = cms();
let black = c.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
assert!((black[3] - 0.9).abs() < 0.005, "{black:?}");
assert!((black.iter().sum::<f32>() - 3.0).abs() < 0.01, "{black:?}");
let lab = c.cmyk_to_lab(black);
assert!(lab.a.abs() < 0.05 && lab.b.abs() < 0.05, "neutral: {lab:?}");
let light = c.srgb_to_cmyk([0.7; 3], Intent::RelativeColorimetric);
assert_eq!(light[3], 0.0, "{light:?}");
let mut prev = 0.0;
for v in (0..=50).rev().map(|i| i as f32 / 50.0) {
let k = c.srgb_to_cmyk([v; 3], Intent::RelativeColorimetric)[3];
assert!(k >= prev - 1e-4, "gray {v}: K {k} after {prev}");
prev = k;
}
}
/// A color whose solve holds an ink at a bound separates to the same inks when its values change by
/// a few float steps: hex f01482 (cyan held at 0) and hex ed1e79 (magenta held at 100%), each with
/// its red stepped one `f32` at a time over 4,001 values (about 0.00024 in all), stay within 0.001
/// on every ink.
#[test]
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
let c = cms();
let pink = [237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0];
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -2000i32..=2000 {
let mut rgb = pink;
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
let spread = |pink: [f32; 3]| {
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
for step in -2000i32..=2000 {
let mut rgb = pink;
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
for i in 0..4 {
lo[i] = lo[i].min(ink[i]);
hi[i] = hi[i].max(ink[i]);
}
}
}
(lo, hi)
};
let (lo, hi) = spread([240.0f32 / 255.0, 20.0 / 255.0, 130.0 / 255.0]);
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!(lo[0], 0.0, "{lo:?}");
let (lo, hi) = spread([237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0]);
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
assert_eq!(hi[1], 1.0, "{hi:?}");
}
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
+47 -5
View File
@@ -395,6 +395,15 @@ impl Source {
}
}
/// The centers of a `cols` × `rows` grid of cells over `b`, row by row.
fn cell_centers(b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = Point> {
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
(0..rows as usize * cols as usize).map(move |k| {
let (i, j) = (k % cols as usize, k / cols as usize);
Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch)
})
}
/// A freeform gradient ready to sample ([`Freeform::field`]).
#[derive(Clone, Debug)]
pub struct Field {
@@ -429,11 +438,7 @@ impl Field {
/// Samples at the centres of a `cols` × `rows` grid of cells over `b`, row by row: RGB and
/// opacity (as [`Self::sample`]).
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
let (cw, ch) = (b.width() / cols as f64, b.height() / rows as f64);
(0..rows as usize * cols as usize).map(move |k| {
let (i, j) = (k % cols as usize, k / cols as usize);
self.sample(Point::new(b.x0 + (i as f64 + 0.5) * cw, b.y0 + (j as f64 + 0.5) * ch))
})
cell_centers(b, cols, rows).map(move |p| self.sample(p))
}
/// Display RGB and opacity at `p`.
@@ -503,6 +508,27 @@ impl ModelField {
};
(c, a)
}
/// [`Self::sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by row.
pub fn grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = (Color, f32)> + '_ {
cell_centers(b, cols, rows).map(move |p| self.sample(p))
}
/// Display RGB and opacity at `p`: the display color of [`Self::sample`], or the display RGB
/// the points mix in when their models differ.
pub fn display_sample(&self, p: Point) -> ([f32; 3], f32) {
if self.model.is_none() {
return self.first.sample(p);
}
let (c, a) = self.sample(p);
(c.to_rgb(), a)
}
/// [`Self::display_sample`] at the centers of a `cols` × `rows` grid of cells over `b`, row by
/// row.
pub fn display_grid(&self, b: Rect, cols: u16, rows: u16) -> impl Iterator<Item = ([f32; 3], f32)> + '_ {
cell_centers(b, cols, rows).map(move |p| self.display_sample(p))
}
}
#[cfg(test)]
@@ -530,6 +556,22 @@ mod tests {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4)
}
#[test]
fn the_model_field_grid_and_display_samples_match_its_sample() {
let mut f = two(0.0);
(f.points[0].color, f.points[1].color) = (Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0));
let field = f.model_field(50.0);
let b = Rect::new(0.0, 0.0, 100.0, 20.0);
let (cells, shown): (Vec<_>, Vec<_>) = (field.grid(b, 5, 1).collect(), field.display_grid(b, 5, 1).collect());
let (mid, a) = field.sample(Point::new(50.0, 10.0));
assert_eq!(cells[2], (mid, a));
assert_eq!(shown[2], (mid.to_rgb(), a));
// Points in different models give their display mix.
(f.points[0].color, f.points[1].color) = (red(), Color::gray(0.5));
let (rgb, _) = f.model_field(50.0).display_sample(Point::new(50.0, 0.0));
assert!(close(rgb, [0.75, 0.25, 0.25]), "{rgb:?}");
}
#[test]
fn the_sample_at_a_point_is_its_colour() {
let f = two(0.0);
+42 -30
View File
@@ -143,38 +143,11 @@ impl Color {
}
/// HSB with hue in degrees 0..360, saturation and brightness 0..1.
pub fn to_hsb(&self) -> [f32; 3] {
let [r, g, b] = self.to_rgb();
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
rgb_to_hsb(self.to_rgb())
}
pub fn from_hsb(h: f32, s: f32, v: f32) -> Self {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
Color::Rgb { r: r + m, g: g + m, b: b + m }
let [r, g, b] = hsb_to_rgb([h, s, v]);
Color::Rgb { r, g, b }
}
/// `#rrggbb` (display RGB).
pub fn to_hex(&self) -> String {
@@ -327,6 +300,45 @@ impl Color {
}
}
/// HSB (hue in degrees 0..360, saturation and brightness 0..1) of RGB numbers 0..1, with no color
/// conversion ([`Color::to_hsb`] reads the display color first).
pub fn rgb_to_hsb([r, g, b]: [f32; 3]) -> [f32; 3] {
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let h = if d <= 0.0 {
0.0
} else if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
// f32 rounding in rem_euclid can yield exactly 360; wrap back to 0.
let h = if h >= 360.0 { 0.0 } else { h };
let s = if max <= 0.0 { 0.0 } else { d / max };
[h, s, max]
}
/// RGB numbers 0..1 of HSB `[h, s, v]` (hue in degrees, saturation and brightness 0..1): the inverse
/// of [`rgb_to_hsb`].
pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
let h = h.rem_euclid(360.0) / 60.0;
let c = v * s;
let x = c * (1.0 - (h % 2.0 - 1.0).abs());
let (r, g, b) = match h as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = v - c;
[r + m, g + m, b + m]
}
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
+5
View File
@@ -376,6 +376,11 @@ impl Appearance {
pub fn has_placed_gradient(&self) -> bool {
self.has_gradient(true)
}
/// Does a fill or stroke carry a gradient that is drawn at a place in document space: a placed
/// one, or a freeform gradient with points of its own whose vector is fitted to the bounds?
pub fn has_positioned_gradient(&self) -> bool {
self.gradients().any(|g| g.is_placed() || g.has_freeform_points())
}
/// Fix unplaced gradients to their fit on `bounds` (the object's geometric bounds; strokes fit
/// the stroke-inflated box), so they can follow transforms that refitting wouldn't reproduce.
pub fn pin_gradients(&mut self, bounds: vectorcraft_geom::Rect) {
+69 -14
View File
@@ -19,7 +19,7 @@ use std::f64::consts::PI;
use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::kurbo::ParamCurveArclen;
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
@@ -904,9 +904,12 @@ pub struct Spine {
cum: Vec<f64>,
anchors: Vec<f64>,
closed: bool,
path: PathData,
}
impl Spine {
/// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative
/// arc lengths, and the arc length at each anchor.
pub fn new(path: &PathData) -> Option<Self> {
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
@@ -943,8 +946,9 @@ impl Spine {
if pts.len() < 2 {
return None;
}
Some(Self { pts, cum, anchors, closed: sp.closed })
Some(Self { pts, cum, anchors, closed: sp.closed, path: path.clone() })
}
/// The spine's flattened length in arc length.
pub fn length(&self) -> f64 {
*self.cum.last().unwrap_or(&0.0)
}
@@ -1002,20 +1006,32 @@ impl Spine {
pub fn at(&self, f: f64) -> (Point, f64) {
self.at_length(f.clamp(0.0, 1.0) * self.length())
}
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine).
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine). The point and
/// tangent come from the original curve at that arc length, not from the flattened polyline: a
/// flattened chord's direction is piecewise constant, so steps oriented to a curved spine with
/// `Align to Path` jump between chords instead of following the curve smoothly.
pub fn at_length(&self, s: f64) -> (Point, f64) {
let last = self.pts.len().saturating_sub(2);
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
Ok(i) => i.min(last),
Err(i) => i.saturating_sub(1).min(last),
};
let (Some(p0), Some(p1), Some(c0), Some(c1)) = (self.pts.get(i), self.pts.get(i + 1), self.cum.get(i), self.cum.get(i + 1)) else {
return (self.pts.first().copied().unwrap_or_default(), 0.0);
};
let u = ((s - c0) / (c1 - c0).max(1e-12)).clamp(0.0, 1.0);
let d = *p1 - *p0;
(p0.lerp(*p1, u), d.y.atan2(d.x))
let Some(sp) = self.path.subpaths.first() else { return (self.pts.first().copied().unwrap_or_default(), 0.0) };
let n = sp.segment_count();
let mut start = 0.0;
for i in 0..n {
let c = sp.segment(i);
let end = self.anchor_length(i + 1).unwrap_or(self.length());
if s <= end || i + 1 == n {
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
let e = c.eval(t);
let tv = c.deriv().eval(t).to_vec2();
// Where a handle sits on its anchor the derivative vanishes there: take the
// direction between points a little before and after instead.
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
}
start = end;
}
// Only a spine without segments gets here: the loop returns at the last one.
(self.pts.first().copied().unwrap_or_default(), 0.0)
}
}
@@ -1446,6 +1462,45 @@ mod tests {
assert_eq!(out[0].geometric_bounds().unwrap().center(), Point::new(5.0, 5.0), "keys stay put");
}
#[test]
fn orientations_follow_a_curved_spine_smoothly() {
// A curved spine: from (0, 0) with handles (+50, +50) / (-50, -50) to (100, 0) with handles
// (+50, -50) / (-50, +50) — the classic up-bow arc.
let spine = PathData::single(SubPath::new(
vec![Anchor::smooth(Point::new(0.0, 0.0), Point::new(50.0, 50.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(50.0, -50.0))],
false,
));
let sp = Spine::new(&spine).unwrap();
// Many steps along the bow: each step's tangent comes from the curve at its arc length,
// not from a flattened chord — so the orientations must sweep the true angle, smoothly.
let len = sp.length();
let mut prev: Option<f64> = None;
for i in 1..=200 {
let (pt, ang) = sp.at_length(len * i as f64 / 201.0);
if let Some(p) = prev {
let step = (ang - p).abs().min(2.0 * std::f64::consts::PI - (ang - p).abs());
assert!(step < 0.1, "tangent step {} is too big at {} ({}, {})", step, i, pt.x, pt.y);
}
prev = Some(ang);
}
}
/// Where the spine starts at an anchor whose handle sits on it, the first step still faces along
/// the curve (towards the next handle), not along a direction of zero length.
#[test]
fn a_handle_on_its_anchor_still_gives_the_curve_direction() {
let spine = PathData::single(SubPath::new(
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(150.0, -50.0))],
false,
));
let sp = Spine::new(&spine).unwrap();
let (p, angle) = sp.at_length(0.0);
assert!(p.x.abs() < 1e-6 && p.y.abs() < 1e-6, "{p:?}");
assert!((angle - std::f64::consts::FRAC_PI_4).abs() < 0.05, "faces the in handle at (50, 50): {angle}");
let (_, end) = sp.at_length(sp.length());
assert!(end.is_finite(), "{end}");
}
#[test]
fn easing_keeps_the_ends_and_stays_monotone() {
use crate::live::{BlendEase, BlendEaseType as K};
+3
View File
@@ -34,6 +34,7 @@ impl Document {
graphic_styles,
char_styles,
para_styles,
composite_fonts,
text_threads,
symbols,
graph_designs,
@@ -90,6 +91,7 @@ impl Document {
&& *graphic_styles == other.graphic_styles
&& *char_styles == other.char_styles
&& *para_styles == other.para_styles
&& *composite_fonts == other.composite_fonts
&& *text_threads == other.text_threads
&& symbols.len() == other.symbols.len()
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
@@ -213,6 +215,7 @@ impl Document {
graphic_styles: default_graphic_styles().into(),
char_styles: Default::default(),
para_styles: Default::default(),
composite_fonts: Default::default(),
text_threads: vec![],
symbols: vec![],
graph_designs: vec![],
+14
View File
@@ -321,6 +321,20 @@ pub struct SeriesPaint {
/// Opacity (0..1) of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`].
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke_opacity: Option<f32>,
/// Blend mode of the topmost fill of each path directly in the series group, as [`Self::fill_opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub fill_blend: Option<vectorcraft_color::BlendMode>,
/// Blend mode of the topmost stroke of each path directly in the series group, as [`Self::fill_opacity`]. Absent:
/// Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub stroke_blend: Option<vectorcraft_color::BlendMode>,
/// Object opacity (0..1) of each path directly in the series group, taken from the object opacity set on one of them.
/// Absent: fully opaque.
#[serde(skip_serializing_if = "Option::is_none")]
pub opacity: Option<f32>,
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
#[serde(skip_serializing_if = "Option::is_none")]
pub blend: Option<vectorcraft_color::BlendMode>,
}
/// Graph data and options. `rows` are categories (one per row of the Graph Data window), each
+46 -19
View File
@@ -84,8 +84,9 @@ impl Default for HitOptions {
/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or
/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated
/// above this crate, so the engine registers one with [`set_image_paint`].
pub type ImagePaint = fn(&Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
/// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and
/// patterns in the document it is given.
pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>;
static IMAGE_PAINT: OnceLock<ImagePaint> = OnceLock::new();
@@ -98,8 +99,8 @@ pub fn set_image_paint(f: ImagePaint) {
/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while
/// nothing is registered.
pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n))
pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n))
}
/// One level of evaluation of a live object in a document, as the canvas draws it: type in an
@@ -127,11 +128,14 @@ fn live_inputs() -> u64 {
}
/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by
/// name and art) and patterns and the [`LiveInputs`] as they were, the art and its [`art_size`].
/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art
/// and its [`art_size`].
struct EvaluatedLive {
node: Node,
symbols: Vec<(String, Arc<Node>)>,
patterns: Vec<crate::PatternDef>,
swatches: crate::Shared<Vec<vectorcraft_color::Swatch>>,
swatch_groups: crate::Shared<Vec<vectorcraft_color::SwatchGroup>>,
inputs: u64,
art: Rc<Vec<Node>>,
size: usize,
@@ -145,6 +149,8 @@ impl EvaluatedLive {
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| *name == s.name && Arc::ptr_eq(art, &s.art))
&& self.node == *n
&& self.patterns == doc.patterns
&& self.swatches == doc.swatches
&& self.swatch_groups == doc.swatch_groups
}
}
@@ -183,8 +189,8 @@ thread_local! {
/// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while
/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of
/// `doc` or the [`LiveInputs`] have changed since, and on every click while it or the document's
/// symbols or patterns hold a placed document ([`holds_placed`]).
/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every
/// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]).
fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
let inputs = live_inputs();
let kept = EVALUATED.with_borrow_mut(|kept| {
@@ -205,7 +211,16 @@ fn live_art(doc: &Document, n: &Node) -> Rc<Vec<Node>> {
return art;
}
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect();
let e = EvaluatedLive { node: n.clone(), symbols, patterns: doc.patterns.clone(), inputs, art: art.clone(), size };
let e = EvaluatedLive {
node: n.clone(),
symbols,
patterns: doc.patterns.clone(),
swatches: doc.swatches.clone(),
swatch_groups: doc.swatch_groups.clone(),
inputs,
art: art.clone(),
size,
};
EVALUATED.with_borrow_mut(|kept| {
kept.insert(0, e);
kept.truncate(LIVE_KEPT);
@@ -437,7 +452,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
let Some(children) = parent.children() else { return };
if parent.clips() && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
return;
}
for i in hit_order(parent, children, p) {
@@ -653,6 +668,15 @@ fn clip_outline_hit(parent: &Node, clip: &Node, p: Point, opt: HitOptions, symbo
clip_outline(clip, p, opt)
}
/// Does isolation mode (`scope`) edit what `parent` holds: is `parent` the isolated container, or
/// the parent of the single object isolated? Then the selection tools hit the art that the
/// clipping mask of `parent` hides, and the Unlock submenu lists it (#3748). The reference
/// app's help says that the parts outside a clipping mask can still be edited
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html>).
fn edits_inside(parent: &Node, scope: Option<NodeId>) -> bool {
scope.is_some_and(|s| s == parent.id || parent.children().is_some_and(|c| c.iter().any(|c| c.id == s)))
}
fn hit_children(
parent: &Node,
p: Point,
@@ -670,8 +694,10 @@ fn hit_children(
chain.push(clip.id);
return Some(Hit { leaf: clip.id, ancestry: chain.clone(), kind, contents_of: None, layers: 1 });
}
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it.
if !clip_contains(clip, p) {
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
// the selection tools in isolation mode within it.
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
if !edited && !clip_contains(clip, p) {
return None;
}
}
@@ -860,7 +886,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
if opt.outline {
return None;
}
image_paint(n).iter().rev().find_map(|(bp, rule, item)| match item {
image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item {
AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke),
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
})
@@ -1205,7 +1231,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
/// only within that region's bounds.
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
/// the selection tools' clicks.
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
marquee_with(doc, r, scope, leaves, false)
}
@@ -1223,16 +1251,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
// marquee touches none of it, as clicks don't (#5309).
Some(s) if !doc.is_editable(s.id) => vec![],
Some(s) => match (s.children(), marquee_in(s, r)) {
(Some(c), Some(r)) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
(Some(_), None) => vec![],
Some(s) => match s.children() {
Some(c) => c.iter().enumerate().filter(|(i, _)| !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
// A single object isolated: only it.
(None, _) => doc
None => doc
.parent_of(s.id)
.and_then(|p| doc.node(p))
.and_then(|p| Some((p.children()?, marquee_in(p, r)?)))
.and_then(|p| p.children())
.into_iter()
.flat_map(|(c, r)| c.iter().filter(|c| c.id == s.id).map(move |c| (c, r)))
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
.collect(),
},
// The objects of the layers, looking through sublayers (hidden, locked and template ones
+113 -4
View File
@@ -255,7 +255,9 @@ fn a_selected_objects_hidden_art_on_a_preview_off_layer_counts_on_its_outline()
/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away
/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it
/// takes that rectangle alone; reaching into the mask takes the group. The same holds for
/// Group Selection's leaves and in isolation mode.
/// Group Selection's leaves. In isolation mode (#3748) the isolated group's own mask does not
/// limit the marquee, as it does not limit clicks: with the group or the art isolated, the
/// marquee takes the hidden art.
#[test]
fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
let mut d = Document::new(300.0, 200.0);
@@ -270,8 +272,9 @@ fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
let hidden = Rect::new(150.0, -10.0, 210.0, 50.0);
assert!(marquee(&d, hidden, None, false).is_empty());
assert!(marquee(&d, hidden, None, true).is_empty());
assert!(marquee(&d, hidden, Some(g), false).is_empty());
assert!(marquee(&d, hidden, Some(art_id), false).is_empty());
assert_eq!(marquee(&d, hidden, Some(g), false), vec![art_id]);
assert_eq!(marquee(&d, hidden, Some(g), true), vec![art_id]);
assert_eq!(marquee(&d, hidden, Some(art_id), false), vec![art_id]);
// This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge.
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]);
// This marquee crosses the shown half's top edge and goes on into the hidden half.
@@ -602,11 +605,41 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
let d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = EvaluatedLive { node: n.clone(), symbols: vec![], patterns: vec![], inputs: 7, art: std::rc::Rc::new(vec![]), size: 0 };
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
assert!(!e.is_of(&d, &n, 8));
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
fn a_kept_evaluation_is_stale_after_a_swatch_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.swatches.first_mut().unwrap().name = "Renamed".into();
assert!(!e.is_of(&d, &n, 7));
let mut d = Document::new(100.0, 100.0);
let e = kept_evaluation(&d, &n);
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Added".into(), swatches: vec![] });
assert!(!e.is_of(&d, &n, 7));
}
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
/// clipping path and the art.
@@ -682,6 +715,82 @@ fn select_behind_takes_a_layer_masks_outline_first() {
assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]);
}
/// #3748: in isolation mode the selection tools hit the art that the isolated clip group (or
/// the isolated layer with a clipping mask) hides outside its mask, and the art when it is the
/// single object isolated; the mask's outline is still hit first. Outside isolation mode, and
/// for the tools that act on what is drawn, the hidden art is not hit. The Unlock submenu
/// lists the hidden art when it is locked.
#[test]
fn isolation_reaches_the_art_a_clipping_mask_hides() {
let hidden = Point::new(170.0, 90.0);
for layer in [false, true] {
let (mut d, g, clip, art) = masked_square(layer);
let isolated = HitOptions { scope: Some(g), ..SELECTING };
assert!(hit_test(&d, hidden, SELECTING).is_none(), "layer {layer}: not isolated");
let h = hit_test(&d, hidden, isolated);
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(g)))), Some((art, art)), "layer {layer}");
assert_eq!(objects_at(&d, hidden, SELECTING, Some(g)), vec![art], "layer {layer}");
assert_eq!(hit_test(&d, Point::new(140.0, 90.0), isolated).map(|h| h.leaf), Some(clip), "layer {layer}: the outline first");
let one = HitOptions { scope: Some(art), ..SELECTING };
assert_eq!(hit_test(&d, hidden, one).map(|h| h.leaf), Some(art), "layer {layer}: the art isolated");
assert!(hit_test(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }).is_none(), "layer {layer}: drawn art only");
assert!(hit_test_visible(&d, hidden, isolated).is_none(), "layer {layer}: sampling");
d.node_mut(art).unwrap().locked = true;
assert_eq!(locked_objects_at(&d, hidden, HitOptions { scope: Some(g), ..HitOptions::default() }), vec![art], "layer {layer}");
assert!(locked_objects_at(&d, hidden, HitOptions::default()).is_empty(), "layer {layer}: not isolated");
}
}
/// #3748, nested clip groups: with the outer clip group isolated, a click or a marquee takes
/// the art its own mask hides, while the mask of a clip group inside it still limits that
/// group's art. With the inner clip group isolated, or its art, the inner mask does not.
#[test]
fn isolation_reaches_hidden_art_only_for_the_isolated_clip_group() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (outer, outer_clip, outer_art, inner, inner_clip, inner_art) =
(d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id());
let mask = |id, r| {
let mut path = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::None, Paint::None, 0.0));
if let NodeKind::Path { clipping, .. } = &mut path.kind {
*clipping = true;
}
Arc::new(path)
};
let art = |id, r| Arc::new(Node::path(id, shapes::rectangle(r), Appearance::default_art()));
let inner_group = Node::new(
inner,
NodeKind::Group {
children: vec![mask(inner_clip, Rect::new(60.0, 60.0, 120.0, 120.0)), art(inner_art, Rect::new(40.0, 40.0, 160.0, 160.0))],
clip: true,
},
);
let children =
vec![mask(outer_clip, Rect::new(20.0, 20.0, 180.0, 180.0)), art(outer_art, Rect::new(190.0, 20.0, 260.0, 180.0)), Arc::new(inner_group)];
d.insert(Some(l), 0, Node::new(outer, NodeKind::Group { children, clip: true })).unwrap();
// `outer_hidden` is outside the outer mask, on the outer group's own art; `inner_hidden` is
// inside the outer mask and outside the inner one, on the inner group's art.
let (outer_hidden, inner_hidden, shown) = (Point::new(220.0, 100.0), Point::new(150.0, 100.0), Point::new(90.0, 90.0));
let leaf = |p, scope| hit_test(&d, p, HitOptions { scope, ..SELECTING }).map(|h| h.leaf);
assert_eq!((leaf(outer_hidden, None), leaf(inner_hidden, None)), (None, None), "not isolated");
assert_eq!(leaf(outer_hidden, Some(outer)), Some(outer_art), "outer isolated: its own hidden art");
assert_eq!(leaf(inner_hidden, Some(outer)), None, "outer isolated: the inner mask still clips");
let h = hit_test(&d, shown, HitOptions { scope: Some(outer), ..SELECTING });
assert_eq!(h.map(|h| (h.leaf, h.top_object(Some(outer)))), Some((inner_art, inner)), "outer isolated: shown art");
assert_eq!(leaf(inner_hidden, Some(inner)), Some(inner_art), "inner isolated");
assert_eq!(leaf(outer_hidden, Some(inner)), None, "inner isolated: the outer group's art");
assert_eq!(leaf(inner_hidden, Some(inner_art)), Some(inner_art), "the inner art isolated");
// These marquees cross the right edge of the outer art (outside the outer mask) and of the
// inner art (inside the outer mask, outside the inner one).
let (outer_edge, inner_edge) = (Rect::new(255.0, 95.0, 265.0, 105.0), Rect::new(155.0, 95.0, 165.0, 105.0));
assert_eq!(marquee(&d, outer_edge, Some(outer), false), vec![outer_art]);
assert!(marquee(&d, inner_edge, Some(outer), false).is_empty());
assert!(marquee(&d, inner_edge, Some(outer), true).is_empty());
assert_eq!(marquee(&d, inner_edge, Some(inner), false), vec![inner_art]);
assert!(marquee(&d, inner_edge, None, false).is_empty());
assert!(marquee(&d, outer_edge, None, false).is_empty());
}
/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the
/// sublayer; hidden, locked and template sublayers block both.
#[test]
+7 -3
View File
@@ -117,10 +117,11 @@ pub use text::FontHeightReference;
pub use text::GlyphChoice;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition,
RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign,
WrapShape,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
pub use trace::TraceView;
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
pub use vectorcraft_color as color;
@@ -195,6 +196,9 @@ pub struct Document {
/// Paragraph styles (besides the built-in [Normal Paragraph Style]).
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
pub para_styles: Shared<Vec<TextStyleDef>>,
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
pub composite_fonts: Shared<Vec<CompositeFont>>,
/// Threaded text: area-type frames one story flows through, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub text_threads: Vec<Vec<NodeId>>,
+5
View File
@@ -103,6 +103,11 @@ impl Document {
let styles = |s: &Vec<TextStyleDef>| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::<usize>();
n += shared(&self.char_styles, &newer.char_styles, styles);
n += shared(&self.para_styles, &newer.para_styles, styles);
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
vec_bytes(c)
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
});
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
});
+1
View File
@@ -31,6 +31,7 @@ pub use ids::{LAYER_COLORS, LayerColor, NodeId};
pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_budget};
pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
use wire::NodeWire;
pub use wire::{MAX_READ_NODES, with_node_budget};
+4
View File
@@ -329,6 +329,10 @@ pub struct Scaling {
/// Pattern fills and strokes move with the art (Transform Patterns; General › Transform
/// Pattern Tiles is its default): their tiles transform too, instead of staying put.
pub patterns: bool,
/// Gradients fitted to the object stay fitted under a transform that flattens it to a line or
/// a point (no area left), as a Transform effect leaves them, instead of being fixed to their
/// fit and flattened to one color with the object.
pub keep_fit_when_flat: bool,
}
impl Scaling {
+20 -7
View File
@@ -239,10 +239,12 @@ impl Node {
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
// the farthest it can reach from its shape.
NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
}),
NodeKind::Image(_) => {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -431,7 +433,7 @@ impl Node {
// Type and symbols in perspective keep looking the same, moved by `a`.
self.transform_projection(a);
// Refitting an unplaced gradient only reproduces moves and uniform scales.
if !keeps_gradient_fit(a) {
if !keeps_gradient_fit(a) && !(sc.keep_fit_when_flat && flattens(a)) {
self.pin_gradients();
}
let k = Scaling::factor(a);
@@ -770,13 +772,24 @@ impl Node {
}
}
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
fn keeps_gradient_fit(a: Affine) -> bool {
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)? The
/// terms are compared within 1e-12 of the scale (at least of 1). A scale of 0 or less, a turn, a
/// reflection and an uneven scale give false, and so does a map that flattens the object
/// ([`flattens`]), which callers that keep a fitted gradient there check apart.
pub fn keeps_gradient_fit(a: Affine) -> bool {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let eps = 1e-12 * m0.abs().max(1.0);
m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
}
/// Does `a` flatten what it maps to a line or a point (its determinant 0, within 1e-12 of the
/// squares of its terms), or is it not finite?
pub fn flattens(a: Affine) -> bool {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let norm = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
!a.is_finite() || a.determinant().abs() <= 1e-12 * norm
}
impl Node {
/// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true
/// everywhere for objects without them, such as type, whose boxes stand in).
+2 -1
View File
@@ -221,7 +221,8 @@ fn assert_round_corners(n: &Node, back: Affine, r: f64) {
}
}
const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false };
const KEEP_CORNERS: Scaling =
Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false, keep_fit_when_flat: false };
#[test]
fn uneven_scales_keep_live_corners_circular() {
+2 -1
View File
@@ -572,7 +572,8 @@ mod tests {
place(&mut g, &symbols);
g.transform(Affine::new([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]), false);
let rec = g.extras().objects_on_path.as_deref().cloned().unwrap();
assert_eq!((rec.spacing, rec.start), (Some(40.0), 20.0));
// The spine measures arc length along the curve, so within rounding of the exact values.
assert!(rec.spacing.is_some_and(|d| (d - 40.0).abs() < 1e-9) && (rec.start - 20.0).abs() < 1e-9, "{rec:?}");
place(&mut g, &symbols);
let x = |id| g.children().and_then(|c| c.iter().find(|c| c.id == id).cloned()).unwrap().geometric_bounds().unwrap().center().x;
assert!((x(NodeId(2)) - 20.0).abs() < 1e-9 && (x(NodeId(3)) - 60.0).abs() < 1e-9, "{} {}", x(NodeId(2)), x(NodeId(3)));
+22 -4
View File
@@ -8,6 +8,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
mod area;
mod char_style;
mod composite;
mod object;
mod para_style;
mod runs;
@@ -17,12 +18,19 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
};
pub use para_style::{
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, SingleWordJustify,
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
};
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
};
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef};
pub use tabs_lists::{Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, NumberStyle, ParaList, TabAlign, TabStop};
pub use wrap::{resolve_wrap, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
@@ -78,6 +86,11 @@ pub struct TextObject {
/// Off for new type and for documents from before it, and saved only when on.
#[serde(default, rename = "opticalMarginAlignment", skip_serializing_if = "crate::skip::is_default")]
pub optical_margin: bool,
/// Character panel › Anti-aliasing Method: how the type's edges are drawn as pixels. Each
/// frame of a thread keeps its own method. Sharp for new type and for documents from before it,
/// and saved only when it is another method.
#[serde(default, rename = "antiAlias", skip_serializing_if = "crate::skip::is_default")]
pub anti_alias: TypeAntiAlias,
/// Character panel menu › System Layout, copied from the document: when on, each character
/// that takes space advances by a whole number of points. Off by default, and saved only when
/// on. The document setting is [`crate::DocSetup::system_layout`].
@@ -96,6 +109,11 @@ pub struct TextObject {
/// file saves the count only when it is not 0.
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
pub list_count: u32,
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
#[serde(default, rename = "listLevelCounts", skip_serializing_if = "Vec::is_empty", deserialize_with = "tabs_lists::read_level_counts")]
pub list_level_counts: Vec<u32>,
/// Cached layout bounds in text space, filled in by the layout engine (not serialized).
#[serde(skip)]
pub cached_bounds: Option<Rect>,
+13 -4
View File
@@ -101,15 +101,24 @@ impl PathEffect {
}
}
/// Type on a Path Options › Align to Path: which height of the type runs along the path.
/// Type on a Path Options › Align to Path: which height of the type runs along the path. Each
/// character is measured by its own font, size and vertical scale, and in vertical type by its own
/// size and horizontal scale. An inline graphic moves as a character of its run would, by its
/// run's vertical scale in vertical type too. These distances are VectorCraft's own values.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PathAlign {
/// The font's top edge: the type hangs below the path.
/// The top of the font's em box: the type hangs below the path. The em box is the font's
/// ideographic em box (from its `BASE` table, its typographic or `hhea` box, or its
/// ideographs), else an em box centered on the cap height, else a box whose top is 0.88 em
/// above the baseline. In vertical type the characters move half an em.
Ascender,
/// The font's bottom edge: the type stands above the path.
/// The bottom of the font's bounding box, else the font's descent: the type stands above the
/// path. In vertical type the characters move half an em the other way.
Descender,
/// Halfway between the ascender and the descender.
/// A line at half the height of the top of the font's H above the baseline, else at half its
/// cap height, else at the middle of its em box. In vertical type the characters stay on the
/// path.
Center,
/// The baseline (the default).
#[default]
+344
View File
@@ -0,0 +1,344 @@
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
//! family; the layout sets each character in its class's font.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
use serde::{Deserialize, Serialize};
/// A class of characters a composite font gives a font of its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CharClass {
/// The base font: ideographs, full-width letters and digits, and every character no other
/// class takes.
Kanji,
/// Hiragana and katakana, full-width and half-width.
Kana,
/// East Asian and full-width punctuation, and typographic quotes and dashes.
Punctuation,
/// Arrows, math, shapes, enclosed and other symbols.
Symbols,
/// Half-width Roman letters, their punctuation and spaces.
Roman,
/// The half-width digits 0 to 9.
Numerals,
}
impl CharClass {
/// Every class, in the order the Composite Fonts dialog lists them.
pub const ALL: [CharClass; 6] = [Self::Kanji, Self::Kana, Self::Punctuation, Self::Symbols, Self::Roman, Self::Numerals];
/// The name commands and files use (`kanji`, `kana`, …).
pub fn key(self) -> &'static str {
match self {
Self::Kanji => "kanji",
Self::Kana => "kana",
Self::Punctuation => "punctuation",
Self::Symbols => "symbols",
Self::Roman => "roman",
Self::Numerals => "numerals",
}
}
/// The class named `key` ([`Self::key`], any case).
pub fn named(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.key().eq_ignore_ascii_case(key))
}
/// Whether the class's characters can be scaled across and up (Kana, Roman and Numerals).
pub fn scales(self) -> bool {
matches!(self, Self::Kana | Self::Roman | Self::Numerals)
}
/// The class of character `c`.
pub fn of(c: char) -> Self {
let u = c as u32;
match u {
0x30..=0x39 => Self::Numerals,
// Basic Latin, Latin-1, Latin Extended, IPA, spacing and combining marks, and Latin
// Extended Additional.
0x00..=0x036F | 0x1E00..=0x1EFF => Self::Roman,
// The other Latin blocks: combining marks extended, phonetic extensions and their
// supplement, combining marks supplement, Latin Extended-C, -D, -E, -F and -G, and the
// Latin ligatures of the alphabetic presentation forms.
0x1AB0..=0x1AFF
| 0x1D00..=0x1DFF
| 0x2C60..=0x2C7F
| 0xA720..=0xA7FF
| 0xAB30..=0xAB6F
| 0xFB00..=0xFB06
| 0x10780..=0x107BF
| 0x1DF00..=0x1DFFF => Self::Roman,
// ・ and ゠ sit in the katakana block but are punctuation.
0x30A0 | 0x30FB => Self::Punctuation,
// Hiragana, katakana, katakana phonetic extensions, half-width katakana (with its
// prolonged sound and voicing marks) and the kana supplements.
0x3041..=0x309F | 0x30A1..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9F | 0x1B000..=0x1B16F => Self::Kana,
// CJK symbols: 〄 〒 〓 〠 〶; ideographic space, 々 〆 〇 and the like stay with the base.
0x3004 | 0x3012 | 0x3013 | 0x3020 | 0x3036 => Self::Symbols,
0x3000 | 0x3005..=0x3007 | 0x3021..=0x302F | 0x3031..=0x3035 | 0x3038..=0x303C => Self::Kanji,
0x3001..=0x303F => Self::Punctuation,
// ※ is a symbol; the rest of General Punctuation (dashes, quotes, leaders) punctuation.
0x203B => Self::Symbols,
0x2010..=0x205E => Self::Punctuation,
// Letterlike symbols, number forms, arrows, math, technical, enclosed alphanumerics, box
// drawing, shapes, miscellaneous symbols and dingbats; enclosed CJK and CJK
// compatibility; full-width signs.
0x2100..=0x2BFF | 0x3200..=0x33FF | 0xFFE0..=0xFFEE => Self::Symbols,
// Full-width forms of the ASCII signs.
0xFF03..=0xFF06 | 0xFF0A | 0xFF0B | 0xFF1C..=0xFF1E | 0xFF20 | 0xFF3C | 0xFF3E | 0xFF5C | 0xFF5E => Self::Symbols,
// Full-width forms of the other ASCII punctuation, and the half-width CJK punctuation.
0xFF01..=0xFF0F | 0xFF1A..=0xFF1F | 0xFF3B..=0xFF40 | 0xFF5B..=0xFF65 => Self::Punctuation,
_ => Self::Kanji,
}
}
}
/// The font a composite font sets one class of characters in, and how.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompositePart {
/// The font family and style.
pub font: String,
#[serde(default = "regular")]
pub style: String,
/// The size, in percent of the type's size.
#[serde(default = "hundred")]
pub size: f64,
/// How far the characters are raised from the baseline, in percent of the type's size
/// (negative lowers them).
#[serde(default)]
pub baseline: f64,
/// Horizontal and vertical scale, in percent (Kana, Roman and Numerals only).
#[serde(default = "hundred")]
pub h_scale: f64,
#[serde(default = "hundred")]
pub v_scale: f64,
/// Kana only: the characters are scaled from the center of the em box rather than from the
/// baseline.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub scale_at_center: bool,
}
fn hundred() -> f64 {
100.0
}
fn regular() -> String {
"Regular".into()
}
impl CompositePart {
/// The part a new composite font gives every class: `font` in `style` at full size, on the
/// baseline, unscaled.
pub fn new(font: impl Into<String>, style: impl Into<String>) -> Self {
Self { font: font.into(), style: style.into(), size: 100.0, baseline: 0.0, h_scale: 100.0, v_scale: 100.0, scale_at_center: false }
}
}
/// The six parts of a composite font, one per [`CharClass`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeParts {
pub kanji: CompositePart,
pub kana: CompositePart,
pub punctuation: CompositePart,
pub symbols: CompositePart,
pub roman: CompositePart,
pub numerals: CompositePart,
}
impl CompositeParts {
/// Every class set in `part`.
pub fn all(part: CompositePart) -> Self {
Self { kanji: part.clone(), kana: part.clone(), punctuation: part.clone(), symbols: part.clone(), roman: part.clone(), numerals: part }
}
pub fn get(&self, class: CharClass) -> &CompositePart {
match class {
CharClass::Kanji => &self.kanji,
CharClass::Kana => &self.kana,
CharClass::Punctuation => &self.punctuation,
CharClass::Symbols => &self.symbols,
CharClass::Roman => &self.roman,
CharClass::Numerals => &self.numerals,
}
}
pub fn get_mut(&mut self, class: CharClass) -> &mut CompositePart {
match class {
CharClass::Kanji => &mut self.kanji,
CharClass::Kana => &mut self.kana,
CharClass::Punctuation => &mut self.punctuation,
CharClass::Symbols => &mut self.symbols,
CharClass::Roman => &mut self.roman,
CharClass::Numerals => &mut self.numerals,
}
}
}
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
/// that type set in it names.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeFont {
pub name: String,
pub parts: CompositeParts,
}
/// The size a part can take, in percent of the type's size.
pub const COMPOSITE_SIZE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
/// How far a part can raise or lower its characters, in percent of the type's size.
pub const COMPOSITE_BASELINE: std::ops::RangeInclusive<f64> = -100.0..=100.0;
/// The horizontal and vertical scale a part can take, in percent.
pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
/// The longest composite font name, in characters.
pub const COMPOSITE_NAME_MAX: usize = 255;
/// The most composite fonts a document or a file keeps.
pub const COMPOSITE_FONTS_MAX: usize = 256;
impl CompositeFont {
/// A composite font named `name` setting every class in `font` and `style`.
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
}
/// Do `a` and `b` name the same composite font: equal in any case?
pub fn same_name(a: &str, b: &str) -> bool {
a == b || a.to_lowercase() == b.to_lowercase()
}
/// The font of `fonts` (a document's composite fonts) named `name`, in any case.
pub fn named<'a>(fonts: &'a [CompositeFont], name: &str) -> Option<&'a CompositeFont> {
fonts.iter().find(|f| Self::same_name(&f.name, name))
}
/// `name` trimmed, when it can name a composite font: not empty, at most
/// [`COMPOSITE_NAME_MAX`] characters and without control characters.
pub fn clean_name(name: &str) -> Option<String> {
let name = name.trim();
let ok = !name.is_empty() && name.chars().count() <= COMPOSITE_NAME_MAX && !name.chars().any(char::is_control);
ok.then(|| name.to_string())
}
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
/// that has none.
pub fn check(&self) -> Result<(), String> {
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
return Err(format!("`{}` can't name a composite font", self.name));
}
for class in CharClass::ALL {
let p = self.parts.get(class);
let k = class.key();
if p.font.trim().is_empty() {
return Err(format!("{k}: give a font"));
}
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
if !within(p.size, &COMPOSITE_SIZE) {
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
}
if !within(p.baseline, &COMPOSITE_BASELINE) {
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
}
for v in [p.h_scale, p.v_scale] {
if !within(v, &COMPOSITE_SCALE) {
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
}
if v != 100.0 && !class.scales() {
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
}
}
if p.scale_at_center && class != CharClass::Kana {
return Err(format!("{k}: only kana can be scaled at the center"));
}
}
Ok(())
}
/// `fonts` without the ones that can't be used: those [`Self::check`] refuses, a later font
/// sharing an earlier one's name (in any case), a part set in one of the fonts, and those past
/// [`COMPOSITE_FONTS_MAX`]. `None` when every font can be used.
pub fn usable(fonts: &[CompositeFont]) -> Option<Vec<CompositeFont>> {
let mut names = std::collections::HashSet::new();
let mut kept: Vec<CompositeFont> =
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
(kept.len() != fonts.len()).then_some(kept)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Each class takes its characters: digits and Latin letters are half-width numerals and
/// Roman, kana both widths, and the punctuation, symbols and full-width forms their own.
#[test]
fn characters_fall_in_their_classes() {
for (s, class) in [
("漢字国一龍〇々", CharClass::Kanji),
("AZa09 ", CharClass::Kanji),
("あをアンーアンー", CharClass::Kana),
("、。「」『』【】〜・!?():", CharClass::Punctuation),
("“”‘’—…", CharClass::Punctuation),
("※→★○〒+=$%①㈱", CharClass::Symbols),
("AZaz é!? ()", CharClass::Roman),
// Latin Extended-C, -D and -E, phonetic extensions and a ligature.
("\u{2C60}\u{A7A0}\u{AB30}\u{1D00}\u{FB01}", CharClass::Roman),
("0123456789", CharClass::Numerals),
] {
for c in s.chars() {
assert_eq!(CharClass::of(c), class, "{c:?} (U+{:04X})", c as u32);
}
}
}
/// A composite font is read and written by its fields' names, and a part's omitted values
/// take the defaults.
#[test]
fn composite_fonts_read_back_with_defaults() {
let mut f = CompositeFont::new("Mixed", "Source Sans 3", "Regular");
f.parts.kana.v_scale = 90.0;
f.parts.kana.scale_at_center = true;
f.parts.roman.baseline = -5.0;
let json = serde_json::to_value(&f).unwrap();
assert_eq!(json["parts"]["kana"]["vScale"], 90.0);
assert_eq!(json["parts"]["kana"]["scaleAtCenter"], true);
assert!(json["parts"]["roman"].get("scaleAtCenter").is_none());
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
let part: CompositePart = serde_json::from_value(serde_json::json!({"font": "Inter"})).unwrap();
assert_eq!(part, CompositePart::new("Inter", "Regular"));
}
/// Names are trimmed; values out of their ranges, and scales on classes that don't scale, are
/// refused.
#[test]
fn composite_fonts_check_their_values() {
assert_eq!(CompositeFont::clean_name(" Mixed ").as_deref(), Some("Mixed"));
for bad in ["", " ", "a\tb", &"x".repeat(COMPOSITE_NAME_MAX + 1)] {
assert_eq!(CompositeFont::clean_name(bad), None, "{bad:?}");
}
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
assert_eq!(ok.check(), Ok(()));
let with = |f: fn(&mut CompositeParts)| {
let mut c = ok.clone();
f(&mut c.parts);
c.check()
};
assert!(with(|p| p.roman.size = 9.0).is_err());
assert!(with(|p| p.roman.size = f64::NAN).is_err());
assert!(with(|p| p.kana.baseline = 101.0).is_err());
assert!(with(|p| p.kana.h_scale = 401.0).is_err());
assert!(with(|p| p.kanji.v_scale = 90.0).is_err());
assert!(with(|p| p.symbols.h_scale = 90.0).is_err());
assert!(with(|p| p.roman.scale_at_center = true).is_err());
assert!(with(|p| p.numerals.font = " ".into()).is_err());
assert_eq!(with(|p| p.kana.scale_at_center = true), Ok(()));
assert_eq!(with(|p| p.numerals.h_scale = 50.0), Ok(()));
let mut spaced = ok.clone();
spaced.name = " Mixed".into();
assert!(spaced.check().is_err());
}
}
+13 -2
View File
@@ -1,8 +1,8 @@
use super::area::{AreaOptions, PathAlign, PathEffect};
use super::char_style::CharStyle;
use super::para_style::ParaStyle;
use super::runs::{RubySpan, TextKind, TextRun, move_anchors, reverse_from_end};
use super::tabs_lists::ParaList;
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
use super::tabs_lists::{ListCounts, ParaList};
use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2};
impl TextObject {
@@ -90,13 +90,24 @@ impl TextObject {
path_spacing: 0.0,
wrap: Vec::new(),
optical_margin: false,
anti_alias: TypeAntiAlias::Sharp,
system_layout: false,
fractional_widths: true,
list_count: 0,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
}
}
/// The list counts the story's earlier frames carry into this frame at each level
/// ([`Self::list_count`] and [`Self::list_level_counts`]).
pub fn list_counts(&self) -> ListCounts {
ListCounts::from_parts(self.list_count, &self.list_level_counts)
}
/// Set the list counts the story's earlier frames carry into this frame ([`Self::list_counts`]).
pub fn set_list_counts(&mut self, counts: ListCounts) {
(self.list_count, self.list_level_counts) = counts.parts();
}
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
+34
View File
@@ -234,6 +234,9 @@ pub struct ParaStyle {
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
/// line.
pub kinsoku: Kinsoku,
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
pub kinsoku_type: KinsokuShoriType,
/// 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.
@@ -258,6 +261,12 @@ impl ParaStyle {
}
}
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
/// list at a level past the first, [`ParaList::level_indent`] more.
pub fn laid_out_left_indent(&self) -> f64 {
self.left_indent + self.list.map_or(0.0, |l| l.level_indent())
}
/// The leading of characters styled `st` in this paragraph, as the layout sets it: their own
/// leading, or for Auto leading the paragraph's Justification › Auto Leading share of their
/// size (exactly [`CharStyle::effective_leading`] at the default 120%, or when the share is
@@ -316,6 +325,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku: Kinsoku,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku_type: KinsokuShoriType,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -347,6 +358,7 @@ impl From<ParaStyle> for ParaStyleFile {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
..
@@ -371,6 +383,7 @@ impl From<ParaStyle> for ParaStyleFile {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
}
@@ -399,6 +412,7 @@ impl From<ParaStyleFile> for ParaStyle {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
..
@@ -422,6 +436,7 @@ impl From<ParaStyleFile> for ParaStyle {
leading_model,
burasagari,
kinsoku,
kinsoku_type,
roman_hanging,
kashida,
}
@@ -486,6 +501,25 @@ pub enum Kinsoku {
Soft,
}
/// How a line keeps the characters [`Kinsoku`] rules out of its start and end (Kinsoku Shori
/// Type). Pushing in sets the characters that would start the next line (or that an opening
/// bracket ending this line would pull with it) on this line, with the line's gaps next to CJK
/// characters closed to make room, each by the same share of the em of the character before it
/// and by at most a tenth of that em; pushing out moves the character before them to the next
/// line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum KinsokuShoriType {
/// Push in when the line can close up enough, else push out.
PushInFirst,
/// Push out, unless that would leave the line more than an em short (of the character before
/// the break): then push in when the line can close up enough.
PushOutFirst,
/// Always push out; never push in.
#[default]
PushOutOnly,
}
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
+38
View File
@@ -144,6 +144,44 @@ pub(super) fn reverse_from_end(path: &mut PathData) {
}
}
/// The anti-aliasing method of a type object (Character panel › Anti-aliasing Method): how the
/// edges of its characters are drawn when the type is drawn as pixels (the canvas, raster exports,
/// rasterizing). SVG, PDF and EPS export ignore it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TypeAntiAlias {
/// Hard edges: a pixel takes the type's color where the type covers at least half of it, and
/// nothing elsewhere.
None,
/// Each edge pixel shows the share of it the type covers.
#[default]
Sharp,
/// An edge pixel covered by a share `c` shows `2c - 0.5`, between 0 and 1: edges about half as
/// wide as Sharp's.
Crisp,
/// An edge pixel covered by a share `c` shows `2c`, at most 1: heavier type.
Strong,
}
impl TypeAntiAlias {
pub const ALL: [Self; 4] = [Self::None, Self::Sharp, Self::Crisp, Self::Strong];
/// The id used in command params and files (`none`, `sharp`, `crisp`, `strong`).
pub fn id(self) -> &'static str {
match self {
Self::None => "none",
Self::Sharp => "sharp",
Self::Crisp => "crisp",
Self::Strong => "strong",
}
}
/// The method an id names.
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|a| a.id() == id)
}
}
/// Where ruby (furigana) text sits: above its base text in horizontal type, right of it in
/// vertical type (the Japanese convention), or below (left in vertical type).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+145 -12
View File
@@ -155,14 +155,29 @@ fn roman(mut n: u32) -> String {
s
}
/// Where a list's marker stands before the first line's text ([`ParaList::align`]): the Bullets
/// and Numbering dialog's Alignment.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ListAlign {
/// The marker starts where the first line starts: at the left indent plus the first-line
/// indent.
#[default]
Left,
/// The marker ends where the first line's text starts, against the text.
Right,
}
/// The list a paragraph is in (Paragraph panel › Bullets and Numbered List). The layout draws the
/// list's marker before the paragraph's first line, in the font, size and color of the paragraph's
/// first character without its baseline shift, rotation, superscript or subscript, tracking, manual
/// kerning, tate-chu-yoko, underline and strikethrough ([`Self::marker_style`]), and the text after
/// it starts at the next tab stop, the left indent counting as a stop. The marker is not a
/// character of the text, and an empty paragraph has none. A saved list reads the fields it leaves
/// out as their defaults, and a build ignores the fields it doesn't know.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
/// it starts at the next tab stop, the left indent counting as a stop. The marker stands at the
/// first line's start, or against the text with [`ListAlign::Right`]. A paragraph at a level past
/// the first ([`Self::level`]) is set [`LIST_LEVEL_INDENT`] further in for each level. The marker
/// is not a character of the text, and an empty paragraph has none. A saved list reads the fields
/// it leaves out as their defaults, and a build ignores the fields it doesn't know.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(default)]
pub struct ParaList {
/// The bullet each paragraph of a bulleted list starts with. A numbered list keeps it for
@@ -172,17 +187,127 @@ pub struct ParaList {
/// numbered list.
#[serde(skip_serializing_if = "Option::is_none")]
pub number: Option<NumberStyle>,
/// Where the marker stands before the first line's text. The file saves it only when it is
/// [`ListAlign::Right`].
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub align: ListAlign,
/// The paragraph's level in the list, 1 to [`LIST_LEVELS`] (Tab and Shift+Tab at the start of
/// the paragraph, Bullets and Numbering…'s Level): each level counts its own numbers
/// ([`Self::next_marker`]). A value outside that range is read as the nearest level
/// ([`Self::depth`]). The file saves it only when it is not 1.
#[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")]
pub level: u8,
}
impl Default for ParaList {
/// A bulleted list with a dot, its marker aligned left, at level 1.
fn default() -> Self {
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 }
}
}
/// Is `level` the first list level, which the file does not save?
fn is_first_level(level: &u8) -> bool {
*level == 1
}
/// Reads a saved list level, a whole number, as the nearest of 1 to [`LIST_LEVELS`], so a level
/// such as -1 or 300 opens the file at level 1 or 9. Anything else is an error.
fn read_level<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
let level = match serde_json::Value::deserialize(d)? {
serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => n.as_i64().map_or(LIST_LEVELS as i64, |n| n.clamp(1, LIST_LEVELS as i64)),
_ => return Err(serde::de::Error::custom("a list level must be a whole number")),
};
Ok(level as u8)
}
/// Reads a type object's saved counts at list levels 2 on ([`ListCounts::from_parts`]), keeping
/// the first `LIST_LEVELS - 1` and skipping the rest of a longer list without storing it.
pub(super) fn read_level_counts<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<u32>, D::Error> {
struct Counts;
impl<'de> serde::de::Visitor<'de> for Counts {
type Value = Vec<u32>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of list counts")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
let mut out = Vec::new();
while out.len() < LIST_LEVELS - 1 {
match seq.next_element::<u32>()? {
Some(c) => out.push(c),
None => return Ok(out),
}
}
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
Ok(out)
}
}
d.deserialize_seq(Counts)
}
/// How many levels a list has (Bullets and Numbering…'s Level: 1 to 9).
pub const LIST_LEVELS: usize = 9;
/// How much further in (pt) the layout sets a list paragraph for each level past the first: its
/// left indent counts that much more, and the marker and the text move with it.
pub const LIST_LEVEL_INDENT: f64 = 18.0;
/// The numbered paragraphs a story's list has counted at each level, level 1 first
/// ([`ParaList::next_marker`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ListCounts(pub [u32; LIST_LEVELS]);
impl ListCounts {
/// The counts with `first` at level 1 and `deeper` at levels 2 on, a missing level at 0, as a
/// type object saves them ([`TextObject::list_count`], [`TextObject::list_level_counts`]).
pub fn from_parts(first: u32, deeper: &[u32]) -> Self {
let mut counts = [0; LIST_LEVELS];
counts[0] = first;
for (c, &d) in counts[1..].iter_mut().zip(deeper) {
*c = d;
}
Self(counts)
}
/// The count at level 1, and the counts at levels 2 on without the zeros that end them.
pub fn parts(&self) -> (u32, Vec<u32>) {
let deeper = &self.0[1..];
let used = deeper.iter().rposition(|&c| c != 0).map_or(0, |i| i + 1);
(self.0[0], deeper[..used].to_vec())
}
}
impl ParaList {
/// A bulleted list with `bullet`.
pub fn bulleted(bullet: Bullet) -> Self {
Self { bullet, number: None }
Self { bullet, ..Self::default() }
}
/// A numbered list with `style`.
pub fn numbered(style: NumberStyle) -> Self {
Self { bullet: Bullet::default(), number: Some(style) }
Self { number: Some(style), ..Self::default() }
}
/// This list with its marker at `align`.
pub fn aligned(self, align: ListAlign) -> Self {
Self { align, ..self }
}
/// This list at level `level` (1 to [`LIST_LEVELS`]).
pub fn at_level(self, level: u8) -> Self {
Self { level, ..self }
}
/// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken
/// as the nearest level.
pub fn depth(&self) -> usize {
usize::from(self.level).clamp(1, LIST_LEVELS)
}
/// How much further in (pt) than its left indent the layout sets a paragraph of this list:
/// [`LIST_LEVEL_INDENT`] for each level past the first.
pub fn level_indent(&self) -> f64 {
(self.depth() - 1) as f64 * LIST_LEVEL_INDENT
}
/// The characters of the marker the layout draws before the paragraph: the bullet, or for a
@@ -195,18 +320,26 @@ impl ParaList {
}
/// The marker of the next paragraph of a story, whose list is `list` (None: in no list) and
/// which holds no text when `empty`, with `count` the numbered paragraphs counted before it.
/// A paragraph in no list sets the count back to 0 and has no marker; an empty paragraph has
/// none and leaves the count as it is; a bulleted paragraph has its bullet and leaves the
/// count as it is; a numbered paragraph adds one to the count and is numbered with it.
pub fn next_marker(list: Option<ParaList>, empty: bool, count: &mut u32) -> Option<String> {
/// which holds no text when `empty`, with `counts` the numbered paragraphs counted before it at
/// each level. A paragraph in no list sets every count back to 0 and has no marker; an empty
/// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts
/// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1
/// again; a bulleted one has its bullet and leaves the count of its level as it is, and a
/// numbered one adds one to the count of its level and is numbered with it. A paragraph back
/// at a shallower level then goes on with that level's count.
pub fn next_marker(list: Option<ParaList>, empty: bool, counts: &mut ListCounts) -> Option<String> {
let Some(list) = list else {
*count = 0;
*counts = ListCounts::default();
return None;
};
if empty {
return None;
}
let level = list.depth() - 1;
for deeper in &mut counts.0[level + 1..] {
*deeper = 0;
}
let count = &mut counts.0[level];
if list.number.is_some() {
*count = count.saturating_add(1);
}
+80 -2
View File
@@ -194,13 +194,13 @@ fn number_styles_write_their_numbers_and_roll_over() {
assert_eq!(ParaList::numbered(NumberStyle::UpperRoman).marker(4), "IV.");
assert_eq!(ParaList::bulleted(Bullet::Square).marker(4), "\u{25AA}");
let (num, dot) = (Some(ParaList::numbered(NumberStyle::Arabic)), Some(ParaList::bulleted(Bullet::Dot)));
let mut count = 0;
let mut count = ListCounts::default();
let markers: Vec<Option<String>> = [(num, false), (num, true), (dot, false), (num, false), (None, false), (num, false)]
.iter()
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut count))
.collect();
assert_eq!(markers, [Some("1.".into()), None, Some("\u{2022}".into()), Some("2.".into()), None, Some("1.".into())]);
assert_eq!(count, 1);
assert_eq!(count.parts(), (1, vec![]));
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
assert_eq!(read(serde_json::json!({"bullet": "dash"})), ParaList::bulleted(Bullet::Dash));
assert_eq!(read(serde_json::json!({"number": "threeDigits"})), ParaList::numbered(NumberStyle::ThreeDigits));
@@ -211,6 +211,20 @@ fn number_styles_write_their_numbers_and_roll_over() {
);
}
/// A list's marker alignment: Left by default and not saved, Right saved as `"align": "right"`;
/// a list saved without it reads as Left.
#[test]
fn a_list_saves_its_marker_alignment_only_when_it_is_right() {
let right = ParaList::numbered(NumberStyle::Arabic).aligned(ListAlign::Right);
assert_eq!(ParaList::bulleted(Bullet::Dot).align, ListAlign::Left);
assert_eq!(serde_json::to_value(right).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "align": "right"}));
assert_eq!(serde_json::to_value(ParaList::bulleted(Bullet::Dash)).unwrap(), serde_json::json!({"bullet": "dash"}));
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
assert_eq!(read(serde_json::json!({"bullet": "dot", "number": "arabic", "align": "right"})), right);
assert_eq!(read(serde_json::json!({"bullet": "square"})).align, ListAlign::Left);
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"align": "center"})).is_err());
}
/// Typed list detection: "1.", "1)", "A." and "A)" and a space at the start of a paragraph
/// start a numbered list, and "*", "+", "#" and ">" and a space start a bulleted list with the
/// filled dot, the hollow circle, the filled square and the dash. Other text, the same characters
@@ -240,6 +254,70 @@ fn typed_list_starts_are_found_at_a_paragraphs_start() {
assert_eq!(t.typed_list_at(19), Some((16, letters)));
}
/// List levels: each level counts its own numbers, a deeper paragraph starts its count at 1,
/// a paragraph back at a shallower level goes on with that level's count, and a paragraph in
/// no list starts every level again. A level past the first sets the paragraph 18 pt further
/// in; the file saves the level only when it is not 1, and a level outside 1 to 9 reads as the
/// nearest one. A type object's counts save level 1 and the deeper levels apart.
#[test]
fn list_levels_count_their_own_numbers_and_save_only_past_the_first() {
let num = |level| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level));
let dot = |level| Some(ParaList::bulleted(Bullet::Dot).at_level(level));
let mut counts = ListCounts::default();
let markers: Vec<Option<String>> = [
(num(1), false),
(num(2), false),
(num(2), false),
(num(3), false),
(num(2), true),
(num(2), false),
(num(1), false),
(num(2), false),
(dot(1), false),
(num(2), false),
(num(1), false),
(None, false),
(num(2), false),
]
.iter()
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts))
.collect();
let want = ["1.", "1.", "2.", "1.", "", "3.", "2.", "1.", "\u{2022}", "1.", "3.", "", "1."];
assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::<Vec<_>>(), want);
assert_eq!(counts, ListCounts([0, 1, 0, 0, 0, 0, 0, 0, 0]));
assert_eq!((ParaList::default().level, ParaList::bulleted(Bullet::Dot).depth()), (1, 1));
assert_eq!([0, 1, 4, 9, 12].map(|l| ParaList::bulleted(Bullet::Dot).at_level(l).depth()), [1, 1, 4, 9, 9]);
assert_eq!([1, 2, 9].map(|l| ParaList::bulleted(Bullet::Dot).at_level(l).level_indent()), [0.0, 18.0, 144.0]);
let para = ParaStyle { left_indent: 18.0, list: dot(3), ..Default::default() };
assert_eq!((para.laid_out_left_indent(), ParaStyle { list: None, ..para.clone() }.laid_out_left_indent()), (54.0, 18.0));
assert_eq!(serde_json::to_value(dot(1)).unwrap(), serde_json::json!({"bullet": "dot"}));
assert_eq!(serde_json::to_value(num(4)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "level": 4}));
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap();
assert_eq!((read(serde_json::json!({"bullet": "dash"})).level, read(serde_json::json!({"level": 4}))), (1, dot(4).unwrap()));
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"level": "two"})).is_err());
assert!(serde_json::from_value::<ParaList>(serde_json::json!({"level": 2.5})).is_err());
let levels = [serde_json::json!(0), serde_json::json!(-1), serde_json::json!(12), serde_json::json!(300), serde_json::json!(u64::MAX)];
assert_eq!(
levels.map(|l| read(serde_json::json!({ "level": l })).level),
[1, 1, 9, 9, 9],
"a saved level outside 1 to 9 reads as the nearest one"
);
let deep = ListCounts([5, 0, 2, 0, 0, 0, 0, 0, 0]);
assert_eq!(deep.parts(), (5, vec![0, 2]));
assert_eq!((ListCounts::from_parts(5, &[0, 2]), ListCounts::default().parts()), (deep, (0, vec![])));
let mut t = TextObject::point(Point::ZERO, "Text", CharStyle::default());
t.set_list_counts(deep);
assert_eq!((t.list_count, t.list_level_counts.as_slice(), t.list_counts()), (5, &[0, 2][..], deep));
let saved = serde_json::to_value(&t).unwrap();
assert_eq!((&saved["listCount"], &saved["listLevelCounts"]), (&serde_json::json!(5), &serde_json::json!([0, 2])));
t.set_list_counts(ListCounts::default());
assert!(serde_json::to_value(&t).unwrap().get("listLevelCounts").is_none(), "no counts past level 1 are saved without them");
let mut saved = serde_json::to_value(&t).unwrap();
saved["listLevelCounts"] = serde_json::json!((1..=20).collect::<Vec<u32>>());
let opened = serde_json::from_value::<TextObject>(saved).unwrap();
assert_eq!(opened.list_level_counts, (1..=8).collect::<Vec<u32>>(), "a file keeps only the counts of levels 2 to 9");
}
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
/// The paragraphs after it still start lists.
+26 -23
View File
@@ -95,8 +95,9 @@ pub struct DataSet {
impl DataSet {
/// Whether the art, as [`Document::captured_values`] read it, still holds what this row
/// says. A value the art can't report (its object is locked or gone) isn't drift: the row
/// keeps it, and applying it again would skip it too.
/// says. A value the art can't report (its object is gone, or is locked or in a locked layer
/// or group and the variable isn't a visibility variable) isn't drift: the row keeps it, and
/// applying it again would skip it too.
pub fn matches(&self, current: &BTreeMap<String, DataValue>) -> bool {
self.values.iter().all(|(k, v)| current.get(k).is_none_or(|c| c == v))
}
@@ -193,33 +194,35 @@ impl Document {
self.variables.bindings = bindings;
}
/// Whether a variable may be bound to the object `id`: it is in the document, neither it nor
/// anything above it is locked, nothing above it is hidden, and it is not on a locked artboard
/// ([`Document::on_locked_artboard`]). Its own visibility doesn't count, as that is what a
/// visibility variable drives.
pub fn variable_target(&self, id: NodeId) -> bool {
self.variable_target_with(&self.locked_artboards(), id)
/// Whether a variable of `kind` may be bound to the object `id`: it is in the document,
/// nothing above it is hidden, it is not on a locked artboard ([`Document::on_locked_artboard`]),
/// and, unless `kind` is visibility, neither it nor anything above it is locked. Its own
/// visibility doesn't count, as that is what a visibility variable drives.
pub fn variable_target(&self, id: NodeId, kind: VariableKind) -> bool {
self.variable_target_with(&self.locked_artboards(), id, kind)
}
/// [`Document::variable_target`] with the locked artboards `locks` of this document, measured
/// once for many ids.
pub fn variable_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked && (n.visible || *i == id))))
pub fn variable_target_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> bool {
let locking = kind != VariableKind::Visibility;
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !(locking && n.locked) && (n.visible || *i == id))))
&& !locks.holds_id(id)
}
/// Whether a data set reads and rewrites the bound object `id`: it is in the document, neither
/// it nor anything above it is locked, and it is not on a locked artboard
/// ([`Document::on_locked_artboard`]). Hidden objects count, and so do objects in a hidden
/// layer or group.
pub fn dataset_target(&self, id: NodeId) -> bool {
self.dataset_target_with(&self.locked_artboards(), id)
/// Whether a data set reads and rewrites the bound object `id` for a variable of `kind`: it
/// is in the document, it is not on a locked artboard ([`Document::on_locked_artboard`]) and,
/// unless `kind` is visibility, neither it nor anything above it is locked. Hidden objects
/// count, and so do objects in a hidden layer or group.
pub fn dataset_target(&self, id: NodeId, kind: VariableKind) -> bool {
self.dataset_target_with(&self.locked_artboards(), id, kind)
}
/// [`Document::dataset_target`] with the locked artboards `locks` of this document, measured
/// once for many ids.
pub fn dataset_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !n.locked))) && !locks.holds_id(id)
pub fn dataset_target_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> bool {
let locking = kind != VariableKind::Visibility;
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| !(locking && n.locked)))) && !locks.holds_id(id)
}
/// The type objects of the story that the type object `id` belongs to, in thread order: the
@@ -253,21 +256,21 @@ impl Document {
/// [`Document::story_target`] with the locked artboards `locks` of this document, measured
/// once for many ids.
pub fn story_target_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
self.story_of(id).into_iter().all(|f| self.dataset_target_with(locks, f))
self.story_of(id).into_iter().all(|f| self.dataset_target_with(locks, f, VariableKind::Text))
}
/// What the object `id` holds for the variable of `kind`: its characters (the whole story
/// for a frame of threaded text), whether it shows, or a linked image's path. `None` when the
/// object is gone, is not of that kind, has no link path yet (an embedded image), or is locked,
/// in a locked layer or group, or on a locked artboard, or for text when a frame of its story
/// is (the document's value is whatever it was left at).
/// object is gone, is not of that kind, has no link path yet (an embedded image), or, unless
/// `kind` is visibility, is locked or in a locked layer or group, or is on a locked artboard,
/// or for text when a frame of its story is (the document's value is whatever it was left at).
pub fn variable_value(&self, id: NodeId, kind: VariableKind) -> Option<DataValue> {
self.variable_value_with(&self.locked_artboards(), id, kind)
}
/// [`Document::variable_value`] with the locked artboards `locks` of this document.
fn variable_value_with(&self, locks: &LockedArtboards, id: NodeId, kind: VariableKind) -> Option<DataValue> {
if !self.dataset_target_with(locks, id) {
if !self.dataset_target_with(locks, id, kind) {
return None;
}
let node = self.node(id)?;
+15 -14
View File
@@ -348,16 +348,16 @@ fn moved_type_group(n: &Node) -> Option<Node> {
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
/// them. `None` when no type stays type.
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
fn keep(n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
let clips = n.clips();
let Some(ch) = n.children_mut() else { return };
for (i, c) in ch.iter_mut().enumerate() {
let clipping = clipping || (clips && i == 0);
if !matches!(c.kind, NodeKind::Text(_)) {
if has_pathfinder(c) || has_own_paint(c) || !geometry_effects(c).is_empty() {
outline_nested_text(Arc::make_mut(c), clipping);
outline_nested_text(Some(d), Arc::make_mut(c), clipping);
} else if c.children().is_some() {
keep(Arc::make_mut(c), moves, clipping, kept);
keep(d, Arc::make_mut(c), moves, clipping, kept);
}
continue;
}
@@ -372,7 +372,7 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
}
}
None if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }),
None => as_art(None, c, None),
None => as_art(Some(d), c, None),
};
if let Some(o) = art {
*c = Arc::new(o);
@@ -391,11 +391,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
}
let mut m = crate::reshape::evaluated(Some(d), n);
let mut kept = false;
keep(&mut m, &moves, false, &mut kept);
keep(d, &mut m, &moves, false, &mut kept);
if !kept {
return None;
}
reshape_leaves(&mut m, &fx);
reshape_leaves(&mut m, &fx, Some(d));
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
m.appearance.items.clear();
m.appearance.contents_index = None;
@@ -547,9 +547,10 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
/// its gradient meshes clipped to the outline; a brushed stroke stays a stroke), in paint order, as
/// the members of a group keeping `n`'s id, transparency, opacity mask and raster effects. A path
/// with [`has_transform_art`](crate::has_transform_art) is first made into the art [`reshape`]
/// makes of it, and each copy is baked this way. `None` when it has neither a stroke to outline nor
/// a geometry effect, so bending first changes nothing.
pub fn bake_appearance(n: &Node) -> Option<Node> {
/// makes of it, and each copy is baked this way; the swatches and patterns that live-effect plug-ins
/// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to
/// outline nor a geometry effect, so bending first changes nothing.
pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) {
return Some(m);
}
@@ -560,9 +561,9 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
// patterns: the art Expand Appearance makes of it (each copy an object with its own strokes,
// patterns and gradients), each piece baked in turn.
if crate::has_transform_art(n)
&& let Some(mut m) = reshape(None, n, None)
&& let Some(mut m) = reshape(doc, n, None)
{
bake_appearance_pieces(&mut m);
bake_appearance_pieces(doc, &mut m);
return Some(m);
}
let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
@@ -617,15 +618,15 @@ pub fn bake_appearance(n: &Node) -> Option<Node> {
}
/// [`bake_appearance`] every path and compound path in `n` that it changes, in place.
fn bake_appearance_pieces(n: &mut Node) {
fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) {
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
if let Some(m) = bake_appearance(n) {
if let Some(m) = bake_appearance(doc, n) {
*n = m;
}
return;
}
for c in n.children_mut().into_iter().flatten() {
bake_appearance_pieces(Arc::make_mut(c));
bake_appearance_pieces(doc, Arc::make_mut(c));
}
}
+310 -6
View File
@@ -210,6 +210,310 @@ fn baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bo
assert_eq!(baked(&fitted, distort()).1.geom, None);
}
/// A gradient fitted to the object turns, reflects and stretches with a Transform effect that a
/// refit would not reproduce: it is fixed to its fit on the geometry the effect takes, then mapped.
/// Moves and even scales leave it fitted.
#[test]
fn a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let fitted = |kind| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops.clone()))));
let geom = |start: (f64, f64), end: (f64, f64)| GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None };
// The geometry of the baked fill (`own`: the Transform effect is the fill's own effect).
let baked = |kind, effects: &[Effect], own: bool| {
let mut ap = Appearance::basic(fitted(kind), Paint::None, 0.0);
if own {
*ap.items[0].effects_mut() = effects.to_vec();
}
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
if !own {
n.appearance.effects = effects.to_vec();
}
let d = bake_document(&doc_with(n)).unwrap();
let mut found = vec![];
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
if let Paint::Gradient(g) = c.appearance.fill_paint() {
found.push(g.geom);
}
});
assert_eq!(found.len(), 1, "{effects:?}, own {own}");
found[0]
};
let t = |params| fx("distort.transform", params);
let offset = fx("path.offsetPath", json!({"offset": 10.0, "joins": "miter"}));
let corners = json!({"corners": [[1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]});
let linear = GradientKind::Linear;
let cases = [
// A quarter turn about the center: the left to right ramp runs from the bottom up.
(linear, vec![t(json!({"rotate": 90.0}))], geom((50.0, 100.0), (50.0, 0.0))),
// Reflected left to right: the ramp runs from right to left.
(linear, vec![t(json!({"reflectX": true}))], geom((100.0, 50.0), (0.0, 50.0))),
// With Scale Strokes & Effects on, the same.
(linear, vec![t(json!({"rotate": 90.0, "strokes": true}))], geom((50.0, 100.0), (50.0, 0.0))),
// Offset Path grows the square to -10..110 first: the turn takes the fit across 120 pt.
(linear, vec![offset.clone(), t(json!({"rotate": 90.0}))], geom((50.0, 110.0), (50.0, -10.0))),
// Stretched to twice the width: the circle of radius 50 about the center becomes an
// ellipse 100 pt across and 50 pt tall.
(GradientKind::Radial, vec![t(json!({"scaleH": 200.0}))], GradientGeom { aspect: 0.5, ..geom((50.0, 50.0), (150.0, 50.0)) }),
// Turned, then moved one width right by Free Distort: the fixed gradient moves with it.
(linear, vec![t(json!({"rotate": 90.0})), fx("distort.freeDistort", corners)], geom((150.0, 100.0), (150.0, 0.0))),
];
for (kind, effects, want) in cases {
for own in [false, true] {
let what = format!("{kind:?} {effects:?}, own {own}");
let got = baked(kind, &effects, own).unwrap_or_else(|| panic!("{what}: fixed to its fit"));
assert_geom_near(got, want, &what);
}
}
// A move and an even scale are what a refit gives: the gradient stays fitted.
for effects in [vec![t(json!({"moveH": 30.0}))], vec![t(json!({"scaleH": 150.0, "scaleV": 150.0})), offset]] {
for own in [false, true] {
assert_eq!(baked(linear, &effects, own), None, "{effects:?}, own {own}");
}
}
// A stroke's gradient is fixed to its fit on the box grown by half its weight (4 pt), -2..102,
// with Scale Strokes & Effects off or on.
let stroked = |effects: &[Effect], own: bool| {
let mut ap = Appearance::basic(Paint::None, fitted(linear), 4.0);
let Some(stroke) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) else { panic!("a stroke") };
if own {
*stroke.effects_mut() = effects.to_vec();
}
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap);
if !own {
n.appearance.effects = effects.to_vec();
}
let d = bake_document(&doc_with(n)).unwrap();
let mut found = vec![];
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
for item in &c.appearance.items {
if let AppearanceItem::Stroke(s) = item
&& let Paint::Gradient(g) = &s.paint
{
found.push(g.geom);
}
}
});
assert_eq!(found.len(), 1, "{effects:?}, own {own}");
found[0]
};
for strokes in [false, true] {
for own in [false, true] {
let what = format!("stroke, strokes {strokes}, own {own}");
let got = stroked(&[t(json!({"rotate": 90.0, "strokes": strokes}))], own).unwrap_or_else(|| panic!("{what}: fixed to its fit"));
assert_geom_near(got, geom((50.0, 102.0), (50.0, -2.0)), &what);
}
}
}
/// A Transform effect that scales the geometry to nothing across leaves a fitted gradient fitted:
/// mapping it with the effect would flatten it to one color.
#[test]
fn a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
// With Scale Strokes & Effects or Transform Patterns on, and for each copy, as without them.
for (options, strokes) in [
(json!({}), 1),
(json!({"strokes": true}), 1),
(json!({"patterns": true}), 1),
(json!({"copies": 2}), 3),
(json!({"strokes": true, "copies": 2}), 3),
(json!({"patterns": true, "copies": 2}), 3),
] {
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, fitted.clone(), 4.0));
let mut p = json!({"scaleH": 0.0, "rotate": 30.0});
if let (Some(p), Some(o)) = (p.as_object_mut(), options.as_object()) {
p.extend(o.clone());
}
n.appearance.effects = vec![fx("distort.transform", p)];
let d = bake_document(&doc_with(n)).unwrap();
let mut found = vec![];
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
for item in &c.appearance.items {
if let AppearanceItem::Stroke(s) = item
&& let Paint::Gradient(g) = &s.paint
{
found.push(g.geom);
}
}
});
assert_eq!(found, vec![None; strokes], "{options}");
}
}
#[test]
fn baked_warps_move_placed_gradients_from_the_bounds_to_the_warped_bounds() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let ramp = |kind| GradientPaint::new(Gradient::new(kind, stops.clone()));
// A ramp across the square and one down it, so both axes of the box map show.
let across = GradientGeom { start: Point::new(20.0, 30.0), end: Point::new(80.0, 30.0), aspect: 1.0, focal: None };
let down = GradientGeom { start: Point::new(60.0, 10.0), end: Point::new(60.0, 75.0), aspect: 1.0, focal: None };
let placed = |geom| Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp(GradientKind::Linear) }));
let fitted = Paint::Gradient(Box::new(ramp(GradientKind::Linear)));
let square = Rect::new(0.0, 0.0, 100.0, 100.0);
let baked = |fill: &Paint, e: Effect| {
let mut n = Node::path(NodeId(50), shapes::rectangle(square), Appearance::basic(fill.clone(), Paint::None, 0.0));
n.appearance.effects.push(e);
let d = bake_document(&doc_with(n)).unwrap();
let m = d.node(NodeId(50)).unwrap();
match m.appearance.fill_paint() {
Paint::Gradient(g) => (m.geometric_bounds().unwrap(), (*g).clone()),
p => panic!("a gradient: {p:?}"),
}
};
// Where the box map from the square to `to` takes `p`.
let follow = |p: Point, to: Rect| Point::new(to.x0 + p.x / 100.0 * to.width(), to.y0 + p.y / 100.0 * to.height());
let styles = [
"arc",
"arcLower",
"arcUpper",
"arch",
"bulge",
"shellLower",
"shellUpper",
"flag",
"wave",
"fish",
"rise",
"fisheye",
"inflate",
"squeeze",
"twist",
];
// The square's warped bounds, from `warp_point` on 401 points along each side: the square's
// corners are (-1, -1) and (1, 1) in the warp's box coordinates, and a vertical warp swaps
// the axes.
let warped_bounds = |style: &str, p: &serde_json::Value| {
let Some(style) = crate::WarpStyle::from_id(style) else { panic!("warp.{style}: a style") };
let share = |key: &str, default: f64| p.get(key).and_then(serde_json::Value::as_f64).unwrap_or(default) / 100.0;
let vertical = p.get("orientation").and_then(serde_json::Value::as_str) == Some("vertical");
let (bend, dh, dv) = (share("bend", 50.0), share("horizontal", 0.0), share("vertical", 0.0));
let mut r: Option<Rect> = None;
for k in 0..=400 {
let s = f64::from(k) / 200.0 - 1.0;
for (x, y) in [(s, -1.0), (s, 1.0), (-1.0, s), (1.0, s)] {
let (x2, y2) = if vertical {
let (a, b) = crate::warp_point(style, bend, dh, dv, 1.0, y, x);
(b, a)
} else {
crate::warp_point(style, bend, dh, dv, 1.0, x, y)
};
let q = Point::new(50.0 + x2 * 50.0, 50.0 + y2 * 50.0);
r = Some(r.map_or(Rect::from_points(q, q), |r| r.union_pt(q)));
}
}
r.unwrap_or(square)
};
let near =
|a: Rect, b: Rect, tol: f64| (a.x0 - b.x0).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y1 - b.y1).abs() < tol;
let mut moved = 0;
for style in styles {
for params in
[json!({"bend": 30.0}), json!({"bend": -40.0, "orientation": "vertical"}), json!({"bend": 20.0, "horizontal": 30.0, "vertical": -20.0})]
{
// A warp that bends the square's sides inward keeps its bounds (within 0.5 pt), and the
// gradient stays with them.
let expected = warped_bounds(style, &params);
let moves = !near(expected, square, 0.5);
moved += usize::from(moves);
for linear in [across, down] {
let what = format!("warp.{style} {params} {linear:?}");
let (b, g) = baked(&placed(linear), fx(&format!("warp.{style}"), params.clone()));
assert!(near(b, expected, 0.1), "{what}: bounds {b:?}, want {expected:?}");
let geom = g.geom.unwrap();
let shifted = geom.start.distance(linear.start).max(geom.end.distance(linear.end));
assert_eq!(shifted > 0.1, moves, "{what}: the gradient moves {shifted} with bounds {b:?}");
let want = GradientGeom { start: follow(linear.start, b), end: follow(linear.end, b), ..linear };
assert_geom_near(geom, want, &what);
}
let what = format!("warp.{style} {params}");
// A fitted gradient stays fitted, and fits the warped outline.
assert_eq!(baked(&fitted, fx(&format!("warp.{style}"), params)).1.geom, None, "{what}");
}
}
assert_eq!(moved, 39, "the warps that move the bounds, of 45");
// With no bend and no distortion the gradient stays where it is.
let (_, g) = baked(&placed(across), fx("warp.arc", json!({"bend": 0.0})));
assert_geom_near(g.geom.unwrap(), across, "no bend");
}
/// A warp with no distortion and no bend (or a bend Arc takes as none) leaves a placed gradient
/// exactly where it was, even where warping the outline moves its bounds by a rounding error.
#[test]
fn a_warp_with_no_bend_leaves_a_placed_gradient_exactly_in_place() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let geom = GradientGeom { start: Point::new(13.7, 31.3), end: Point::new(91.1, 47.9), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
let mut drift = 0;
let cases = crate::WARP_STYLES.map(|(s, _)| (s, 0.0));
for (k, (style, bend)) in cases.into_iter().chain([("arc", 1e-5), ("arc", -1e-5)]).enumerate() {
let k = k as f64;
let oval = Rect::new(10.1 + k * 0.37, 20.3 - k * 1.13, 97.7 + k * 3.31, 71.9 + k * 0.71);
let mut n = Node::path(NodeId(50), shapes::ellipse(oval), Appearance::basic(placed.clone(), Paint::None, 0.0));
n.appearance.effects.push(fx(&format!("warp.{style}"), json!({ "bend": bend })));
let d = bake_document(&doc_with(n)).unwrap();
let m = d.node(NodeId(50)).unwrap();
drift += usize::from(m.geometric_bounds() != shapes::ellipse(oval).bounds());
let Paint::Gradient(g) = m.appearance.fill_paint() else { panic!("warp.{style} {bend}: a gradient") };
assert_eq!(g.geom, Some(geom), "warp.{style} {bend}");
}
assert!(drift > 0, "the warped outlines' bounds move by a rounding error");
// Another style with as small a bend still moves the outline, and the gradient follows it.
let mut n = Node::path(NodeId(50), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(placed, Paint::None, 0.0));
n.appearance.effects.push(fx("warp.rise", json!({"bend": 1e-5})));
let d = bake_document(&doc_with(n)).unwrap();
let Paint::Gradient(g) = d.node(NodeId(50)).unwrap().appearance.fill_paint() else { panic!("warp.rise: a gradient") };
assert_ne!(g.geom, Some(geom), "warp.rise 1e-5");
}
/// A Warp effect on a fill or a stroke itself moves and scales its placed gradient from the
/// path's bounds before the warp to its bounds after it (a stroke: its stroke-inflated bounds).
#[test]
fn a_fills_and_a_strokes_own_warp_move_its_placed_gradient_with_the_bounds() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = GradientGeom { start: Point::new(20.0, 60.0), end: Point::new(80.0, 60.0), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
let square = Rect::new(0.0, 0.0, 100.0, 100.0);
let width = 4.0;
// Where the box map from `from` to `to` takes `p`.
let follow = |p: Point, from: Rect, to: Rect| {
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
};
let pad = |r: Rect| r.inflate(width / 2.0, width / 2.0);
for style in ["arc", "rise", "inflate"] {
for stroke in [false, true] {
let what = format!("warp.{style} on the {}", if stroke { "stroke" } else { "fill" });
let mut ap =
if stroke { Appearance::basic(Paint::None, placed.clone(), width) } else { Appearance::basic(placed.clone(), Paint::None, 0.0) };
let Some(item) = ap.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_)) == stroke) else { panic!("{what}: the item") };
item.effects_mut().push(fx(&format!("warp.{style}"), json!({"bend": 40.0})));
let n = Node::path(NodeId(50), shapes::rectangle(square), ap);
let d = bake_document(&doc_with(n)).unwrap();
let mut found = vec![];
d.node(NodeId(50)).unwrap().walk(&mut |c: &Node| {
for item in &c.appearance.items {
if let Paint::Gradient(g) = item.paint() {
found.push((c.geometric_bounds().unwrap(), g.geom.unwrap()));
}
}
});
assert!(!found.is_empty(), "{what}: the gradient is kept");
for (b, g) in found {
assert_ne!(b, square, "{what}: the warp changes the bounds");
let (from, to) = if stroke { (pad(square), pad(b)) } else { (square, b) };
let want = GradientGeom { start: follow(geom.start, from, to), end: follow(geom.end, from, to), ..geom };
assert_geom_near(g, want, &what);
}
}
}
}
#[test]
fn item_effects_split_into_one_path_per_item() {
let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
@@ -232,7 +536,7 @@ fn a_baked_stroke_keeps_its_raster_effects() {
s.effects.push(fx("path.offsetPath", json!({"offset": 5.0})));
s.effects.push(fx("stylize.dropShadow", json!({})));
}
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let ch = m.children().unwrap();
let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") };
assert_eq!(f.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["stylize.dropShadow"]);
@@ -247,7 +551,7 @@ fn a_baked_stroke_leaves_dither_behind() {
g.gradient.dither = true;
s.paint = Paint::Gradient(Box::new(g));
}
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let ch = m.children().unwrap();
let Some(AppearanceItem::Fill(f)) = ch[1].appearance.items.first() else { panic!("the outline is filled") };
let Paint::Gradient(g) = &f.paint else { panic!("a gradient fill") };
@@ -263,7 +567,7 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline
s.gradient_mode = vectorcraft_doc::StrokeGradientMode::Along;
s.opacity = 0.5;
}
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let ch = m.children().unwrap();
let NodeKind::Group { children, clip: true } = &ch[1].kind else { panic!("a clip group: {:?}", ch[1].kind) };
assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. }));
@@ -296,7 +600,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
// Distort Appearance: the 200% copy's stroke is 4 pt, as outside the envelope, so its outline
// is 204 pt wide.
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1, "strokes": true}));
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let w = widths(&m);
assert_eq!(w.len(), 2, "{w:?}");
assert!((w[0] - 102.0).abs() < 0.5 && (w[1] - 204.0).abs() < 0.5, "{w:?}");
@@ -307,7 +611,7 @@ fn a_baked_transform_copy_keeps_its_scaled_stroke() {
fn a_baked_transform_copy_keeps_its_moved_pattern() {
let paint = Paint::Pattern { pattern: "p".into(), xf: vectorcraft_geom::Affine::IDENTITY };
let n = transformed(paint, Paint::None, 0.0, json!({"moveH": 30, "copies": 1, "patterns": true}));
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let xs: Vec<f64> = baked_paths(&m)
.iter()
.map(|p| match p.appearance.fill_paint() {
@@ -322,7 +626,7 @@ fn a_baked_transform_copy_keeps_its_moved_pattern() {
fn a_baked_transform_without_its_options_outlines_the_copies_together() {
// Without Scale Strokes & Effects the copy keeps the 2 pt stroke: one outline of both squares.
let n = transformed(Paint::None, Paint::solid(Color::BLACK), 2.0, json!({"scaleH": 200, "scaleV": 200, "copies": 1}));
let m = bake_appearance(&n).unwrap();
let m = bake_appearance(None, &n).unwrap();
let w = widths(&m);
assert_eq!(w.len(), 1, "{w:?}");
assert!((w[0] - 202.0).abs() < 0.5, "{w:?}");
+11 -4
View File
@@ -1,4 +1,4 @@
use super::{CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap};
use super::{CLASSIC_EXTRUDE, CROP_MARKS, EXTRUDE, INFLATE, PATHFINDER_EFFECTS, RASTERIZE, REVOLVE, ROTATE, TRAP, Value, json, trap};
/// Catalogue entry for one effect.
#[derive(Clone, Debug, PartialEq)]
@@ -80,6 +80,7 @@ fn lengths_of(id: &str) -> Lengths {
"path.offsetPath" => always(&["offset"]),
"threeD.revolve" => always(&["offset"]),
"threeD.extrude" => always(&["depth", "bevelWidth", "bevelHeight"]),
"threeD.classicExtrude" => always(&["depth", "bevelHeight"]),
"threeD.inflate" => always(&["depth"]),
"path.outlineStroke" => always(&["width"]),
"stylize.roundCorners" | "stylize.feather" | "blur.gaussian" | "blur.smart" | "sharpen.unsharpMask" => always(&["radius"]),
@@ -111,8 +112,7 @@ fn lengths_of(id: &str) -> Lengths {
}
}
const WARP_DOC: &str =
"{bend: % (-100..100, 50), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}";
const WARP_DOC: &str = "{bend: % (-100..100, 50; with a bend or a distortion, placed gradients move and scale from the object's bounds to its warped bounds), horizontal: % distortion (0), vertical: % distortion (0), orientation: \"horizontal\"|\"vertical\"}";
const DT: &[&str] = &["Effect", "Distort & Transform"];
@@ -200,6 +200,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0}),
),
g(
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), 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","drawHiddenFaces":false}),
),
g(
"convertToShape.rectangle",
"Rectangle…",
@@ -240,7 +247,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"distort.transform",
"Transform…",
DT,
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
),
g(
+60 -21
View File
@@ -3,6 +3,7 @@ use super::{
Appearance, AppearanceItem, BezPath, Effect, FillRule, Node, NodeKind, PathData, Rect, StrokeLayer, Value, WarpStyle, distort, stroke, stylize,
util, warp,
};
use vectorcraft_doc::Document;
/// Context the geometry effects may need from the object's appearance.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
@@ -22,6 +23,9 @@ pub struct GeomContext<'a> {
/// The index in `appearance.items` of the fill or stroke whose own effects these are; `None`:
/// the object's effects.
pub item: Option<usize>,
/// The document that the swatches and patterns named by a live-effect plug-in that paints its
/// pieces are looked up in. Without one, a result that names any is refused.
pub doc: Option<&'a Document>,
}
impl<'a> GeomContext<'a> {
@@ -32,7 +36,7 @@ impl<'a> GeomContext<'a> {
_ => FillRule::NonZero,
};
let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0);
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None }
Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None, doc: None }
}
/// The context of the effects on `item`, one of the same object's appearance items: a
@@ -174,28 +178,40 @@ pub fn apply_geometry_bez_carrying(effects: &[Effect], path: &BezPath, bounds: R
(out.to_bezpath(), carry)
}
/// How placed gradients follow geometry effects. The Transform effect without copies maps them as
/// it maps the object (with copies, `crate::reshape` gives each copy its own). Free Distort moves
/// and scales them from the object's bounds before the effect to its bounds after it. For the
/// other geometry effects it is empty. It does not change gradients fitted to the object.
/// How gradients follow geometry effects. The Transform effect without copies maps placed
/// gradients as it maps the object (with copies, `crate::reshape` gives each copy its own). Free
/// Distort and the Warp effects move and scale them from the object's bounds before the effect to
/// its bounds after it. For the other geometry effects it is empty. A gradient fitted to the
/// object fits the geometry each effect makes, until a Transform effect turns, reflects or scales
/// it unevenly (a map after which a refit would not match the mapped gradient): it is fixed to its
/// fit on the geometry that effect takes, and then follows that effect and the ones after it as a
/// placed gradient does.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Carry(Vec<CarryStep>);
/// Does `m` fix a gradient fitted to the object to its fit before mapping it? It does when a refit
/// would not reproduce the map (a turn, a reflection or an uneven scale) and `m` keeps area: a map
/// that flattens the geometry to a line (a scale of 0) leaves the gradient fitted, since mapping it
/// would flatten it to one color ([`vectorcraft_doc::node::flattens`]).
pub(crate) fn fixes_fit(m: vectorcraft_geom::Affine) -> bool {
!vectorcraft_doc::node::flattens(m) && !vectorcraft_doc::node::keeps_gradient_fit(m)
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum CarryStep {
Affine(vectorcraft_geom::Affine),
/// Map `m`; `from` is the geometric bounds of the geometry it takes, which a fitted gradient
/// fits before `m` moves it (none: fitted gradients stay fitted).
Affine { m: vectorcraft_geom::Affine, from: Option<Rect> },
/// From box `from` to box `to` (strokes: their stroke-inflated boxes).
Boxes {
from: Rect,
to: Rect,
},
Boxes { from: Rect, to: Rect },
}
impl Carry {
/// Does effect `id` with merged params `p` on geometry with reference box `b` (`seed` for
/// Random) move placed gradients? Free Distort does unless it leaves every corner in place;
/// the Transform effect does without copies (with copies the original stays where it is, and
/// `crate::reshape` gives each copy its own gradients).
/// Random) move placed gradients? Free Distort does unless it leaves every corner in place, a
/// Warp effect unless it has no bend and no distortion, and the Transform effect does without
/// copies (with copies the original stays where it is, and `crate::reshape` gives each copy
/// its own gradients).
pub(crate) fn follows(id: &str, p: &Value, b: Rect, seed: u64) -> bool {
match id {
"distort.transform" => {
@@ -209,10 +225,17 @@ impl Carry {
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].iter().zip(&corners).all(|(a, c)| c.distance((*a).into()) <= tol);
!still && corners.iter().all(|c| c.x.is_finite() && c.y.is_finite())
}
_ if id.starts_with("warp.") => crate::warp::bends(id, p),
_ => false,
}
}
/// Does effect `id` move placed gradients from each path's bounds before it to its bounds
/// after it, rather than by one map for the whole object?
pub(crate) fn by_bounds(id: &str) -> bool {
id == "distort.freeDistort" || id.starts_with("warp.")
}
/// How placed gradients follow effect `id` (as [`Self::follows`]) on an object whose geometric
/// bounds are `from` before the effect and `to` after it; empty when they stay in place.
pub(crate) fn of(id: &str, p: &Value, b: Rect, from: Option<Rect>, to: Option<Rect>, seed: u64) -> Carry {
@@ -220,7 +243,7 @@ impl Carry {
return Carry::default();
}
let step = match id {
"distort.transform" => Some(CarryStep::Affine(distort::transform_map(b, p, seed).0)),
"distort.transform" => Some(CarryStep::Affine { m: distort::transform_map(b, p, seed).0, from }),
_ => match (from, to) {
(Some(from), Some(to)) if from != to && [to.x0, to.y0, to.x1, to.y1].iter().all(|v| v.is_finite()) => {
Some(CarryStep::Boxes { from, to })
@@ -236,20 +259,36 @@ impl Carry {
self.0.is_empty()
}
/// Does it move any of the gradients of `ap`? Callers check first, so an appearance shared
/// with other objects is not copied for nothing.
/// Does it move any of the gradients of `ap` (those drawn at a place in document space, a
/// freeform gradient's own points included)? Callers check first, so an appearance shared with
/// other objects is not copied for nothing.
pub fn moves(&self, ap: &Appearance) -> bool {
!self.0.is_empty() && ap.has_placed_gradient()
!self.0.is_empty() && (ap.has_positioned_gradient() || (self.pin().is_some() && ap.has_unplaced_gradient()))
}
/// Move the placed gradients of `ap` along, through each step in turn.
/// The first step that fixes gradients fitted to the object: a map a refit would not
/// reproduce, on geometry whose bounds are known.
fn pin(&self) -> Option<usize> {
self.0.iter().position(|s| matches!(s, CarryStep::Affine { m, from: Some(_) } if fixes_fit(*m)))
}
/// Move the gradients of `ap` along. Placed gradients take every step in turn; fitted ones
/// are fixed to their fit at the first step [`Self::pin`] finds and take it and the steps
/// after it.
pub fn apply(&self, ap: &mut Appearance) {
if !self.moves(ap) {
return;
}
for s in &self.0 {
// The steps move placed gradients only; fitted ones become placed at the pin.
let pin = self.pin();
for (k, s) in self.0.iter().enumerate() {
if Some(k) == pin
&& let CarryStep::Affine { from: Some(b), .. } = *s
{
ap.pin_gradients(b);
}
match *s {
CarryStep::Affine(m) => ap.transform_gradients(m),
CarryStep::Affine { m, .. } => ap.transform_gradients(m),
CarryStep::Boxes { from, to } => crate::reshape::follow_boxes(ap, from, to),
}
}
@@ -339,7 +378,7 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
use util::{join, num};
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item };
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone());
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
}
match id {
"distort.freeDistort" => distort::free_distort(path, b, p, max),
+62 -47
View File
@@ -67,25 +67,28 @@ pub type OutlineHook<'a> = &'a dyn Fn(&Node) -> Option<Node>;
/// back to front: a compound shape as its area, a blend, an envelope or an object with a warp as
/// the art it draws, and type and symbol instances as their art through `hook`. Past
/// [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) objects of symbol art, further
/// instances add nothing.
pub fn member_leaves(n: &Node, hook: Option<OutlineHook>) -> Vec<Node> {
/// instances add nothing. The swatches and patterns that live-effect plug-ins painting their
/// pieces name are looked up in `doc` ([`shape_art`]).
pub fn member_leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Vec<Node> {
let mut out = vec![];
leaves(n, hook, &SymbolNodes::default(), &mut out);
leaves(doc, n, hook, &SymbolNodes::default(), &mut out);
out
}
/// [`member_leaves`], with the symbol art given so far counted in `nodes`.
fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Vec<Node>) {
fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Vec<Node>) {
if !n.visible {
return;
}
// A blend, an envelope or an object with a warp takes part as the art it draws.
if let Some(art) = shape_art_in(n, hook, nodes) {
if let Some(art) = shape_art_in(doc, n, hook, nodes) {
let first = out.len();
leaves(&art, hook, nodes, out);
// Every path of a live object's, type's or symbol instance's art is drawn inside the
// object's opacity and blend mode.
if crate::needs_outline(n) {
leaves(doc, &art, hook, nodes, out);
// Every path of a live object's, type's or symbol instance's art, and every piece of a path
// whose live-effect plug-in paints its pieces, is drawn inside the object's opacity and
// blend mode.
let pieces = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && matches!(art.kind, NodeKind::Group { .. });
if crate::needs_outline(n) || pieces {
for l in out.iter_mut().skip(first) {
within(l, n);
}
@@ -95,11 +98,11 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
match &n.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.push(n.clone()),
// A compound shape takes part as its area, styled like it.
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art_in(n, hook, nodes) {
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => match compound_shape_art_in(doc, n, hook, nodes) {
Some(art) => out.push(art),
None => {
for c in children {
leaves(c, hook, nodes, out);
leaves(doc, c, hook, nodes, out);
}
}
},
@@ -114,7 +117,7 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
crate::reshape::outline_nested_text(&mut art, false);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
}
@@ -122,7 +125,7 @@ fn leaves(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes, out: &mut Ve
_ => art,
};
let first = out.len();
leaves(&art, None, nodes, out);
leaves(doc, &art, None, nodes, out);
for l in out.iter_mut().skip(first) {
within(l, n);
}
@@ -176,29 +179,37 @@ fn transparency_into_members(n: &mut Node) {
/// [`outline_object`](crate::outline_object) gives a symbol instance its symbol's art. The art
/// keeps the effects of `n` other than its geometry effects, and the groups inside it pass their
/// opacity and blend mode to the objects they hold. `None` when `n` is none of these, for images,
/// for symbol instances without geometry effects, and for one without art from `hook`.
pub fn shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
shape_art_in(n, hook, &SymbolNodes::default())
/// for symbol instances without geometry effects, and for one without art from `hook`. A
/// live-effect plug-in that paints its pieces makes a path, and each path of a group's or symbol's
/// art, a group of its pieces, whose swatches and patterns must be in `doc` (without one, pieces
/// that name one are refused and the path stays as it is).
pub fn shape_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
shape_art_in(doc, n, hook, &SymbolNodes::default())
}
/// [`shape_art`], with the symbol art given so far counted in `nodes`.
fn shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
let mut art = reshaped_art(n, hook, nodes)?;
fn shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
let mut art = reshaped_art(doc, n, hook, nodes)?;
transparency_into_members(&mut art);
Some(art)
}
/// [`shape_art_in`] before the groups inside the art pass on their transparency.
fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
let fx = crate::reshape::geometry_effects(n);
let outline = hook.unwrap_or(&crate::outline_text);
match &n.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } if !fx.is_empty() => Some(reshaped(n, n)),
NodeKind::Group { .. } | NodeKind::Layer { .. } if !fx.is_empty() => match compound_shape_art_in(n, hook, nodes) {
Some(area) => Some(reshaped(&area, n)),
// A path with a live-effect plug-in that paints its pieces: the group of its pieces, each
// with its own paints, as the renderer draws it.
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } if !fx.is_empty() => {
let painted = crate::reshape::has_painted_effects(n).then(|| crate::reshape::reshape(doc, n, None)).flatten();
Some(painted.unwrap_or_else(|| reshaped(n, n, doc)))
}
NodeKind::Group { .. } | NodeKind::Layer { .. } if !fx.is_empty() => match compound_shape_art_in(doc, n, hook, nodes) {
Some(area) => Some(reshaped(&area, n, doc)),
None => {
let mut m = crate::reshape::outlined_members_with(None, n, outline, nodes);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx);
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
// The group's own fills and strokes follow the effects as its members do.
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
@@ -213,8 +224,8 @@ fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Opt
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
crate::reshape::outline_nested_text(&mut art, false);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx);
crate::reshape::outline_nested_text(doc, &mut art, false);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
carry.apply(&mut art.appearance);
@@ -226,19 +237,21 @@ fn reshaped_art(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Opt
}
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None,
_ if crate::needs_outline(n) && (vectorcraft_doc::live::is_live(n) || !fx.is_empty()) => {
crate::reshape::as_art_with(None, n, None, outline, nodes)
crate::reshape::as_art_with(None, doc, n, None, outline, nodes)
}
_ => None,
}
}
/// `src`, a path, compound path or compound shape's area, as one path reshaped by the visible
/// geometry effects of `n`, without those effects.
fn reshaped(src: &Node, n: &Node) -> Node {
/// geometry effects of `n`, without those effects. The swatches and patterns a live-effect plug-in
/// that paints its pieces names are looked up in `doc`.
fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
let mut m = src.clone();
if let Some((path, rule)) = geometry(src) {
let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
let (g, carry) = crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext::of(n));
let (g, carry) =
crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) });
m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false };
// Its gradients move with the outline, as the canvas paints them.
if carry.moves(&m.appearance) {
@@ -282,12 +295,12 @@ fn shape_op(mode: ShapeMode) -> po::BoolOp {
/// it by the member's shape mode; the backmost member starts the area. `None` when `n` is not a
/// compound shape, or its members are past a live Pathfinder's budget ([`PATHFINDER_MAX_SEGMENTS`],
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES)).
pub fn compound_shape_area(n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
compound_shape_area_in(n, hook, &SymbolNodes::default())
pub fn compound_shape_area(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<PathData> {
compound_shape_area_in(doc, n, hook, &SymbolNodes::default())
}
/// [`compound_shape_area`], with the symbol art given so far counted in `nodes`.
fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<PathData> {
fn compound_shape_area_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<PathData> {
if !n.is_compound_shape() {
return None;
}
@@ -296,7 +309,7 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
let mut members: Vec<(po::BoolOp, usize)> = vec![];
for c in n.children()? {
let before = all.len();
leaves(c, hook, nodes, &mut all);
leaves(doc, c, hook, nodes, &mut all);
if all.len() > before {
members.push((shape_op(c.extras().shape_mode), all.len() - before));
}
@@ -312,7 +325,8 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
Some(po::boolean_n(&refs, |inside| {
let (mut start, mut area) = (0, false);
for (k, (op, count)) in members.iter().enumerate() {
let here = inside.get(start..start + count).is_some_and(|flags| flags.contains(&true));
// `inside` is ascending: the first leaf at or after `start` tells whether one of this member's is in it.
let here = inside.get(inside.partition_point(|&i| i < start)).is_some_and(|&i| i < start + count);
start += count;
area = if k == 0 { here } else { op.apply(area, here) };
}
@@ -322,13 +336,13 @@ fn compound_shape_area_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNod
/// Compound shape `n` as one path of its area ([`compound_shape_area`]) with its appearance,
/// opacity and blend mode: how it takes part in a Pathfinder operation.
pub fn compound_shape_art(n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
compound_shape_art_in(n, hook, &SymbolNodes::default())
pub fn compound_shape_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>) -> Option<Node> {
compound_shape_art_in(doc, n, hook, &SymbolNodes::default())
}
/// [`compound_shape_art`], with the symbol art given so far counted in `nodes`.
fn compound_shape_art_in(n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
let area = compound_shape_area_in(n, hook, nodes)?;
fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &SymbolNodes) -> Option<Node> {
let area = compound_shape_area_in(doc, n, hook, nodes)?;
let mut art = Node::path(n.id, area, Appearance { items: n.appearance.items.clone(), ..Default::default() });
(art.opacity, art.blend) = (n.opacity, n.blend);
Some(art)
@@ -434,15 +448,16 @@ fn within_budget<'a>(leaves: impl IntoIterator<Item = &'a Node>) -> bool {
/// Evaluate the visible Pathfinder effects of `group` in order: the resulting child objects.
/// `None` when the group has no Pathfinder effect. Past the budget ([`PATHFINDER_MAX_SEGMENTS`],
/// [`PATHFINDER_MAX_OVERLAPS`], [`SYMBOL_ART_MAX_NODES`](crate::SYMBOL_ART_MAX_NODES) for
/// each effect) it returns the children as they are.
pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Vec<Arc<Node>>> {
/// each effect) it returns the children as they are. The swatches and patterns that live-effect
/// plug-ins painting their pieces name are looked up in `doc` ([`shape_art`]).
pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<OutlineHook>) -> Option<Vec<Arc<Node>>> {
if !has_pathfinder(group) {
return None;
}
let source: &[Arc<Node>] = group.children()?;
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
match compound_shape_area(group, hook) {
match compound_shape_area(doc, group, hook) {
Some(area) if area.is_empty() => vec![],
Some(area) => vec![Arc::new(Node::path(group.id, area, Appearance::default()))],
None => return Some(source.to_vec()),
@@ -454,7 +469,7 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
if e.id == crate::trap::TRAP {
let (mut lv, nodes) = (vec![], SymbolNodes::default());
for c in &stack {
leaves(c, hook, &nodes, &mut lv);
leaves(doc, c, hook, &nodes, &mut lv);
}
if nodes.spent() || !within_budget(&lv) {
return Some(source.to_vec());
@@ -478,7 +493,7 @@ pub fn pathfinder_children(group: &Node, hook: Option<OutlineHook>) -> Option<Ve
.iter()
.map(|c| {
let mut lv = vec![];
leaves(c, hook, &nodes, &mut lv);
leaves(doc, c, hook, &nodes, &mut lv);
lv
})
.collect();
@@ -632,7 +647,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => out.extend(crate::reshape::leaf_geometry(n)),
NodeKind::Group { .. } if n.is_compound_shape() => {
let hook = |c: &Node| crate::outline_object(doc, c);
match compound_shape_area(n, Some(&hook)) {
match compound_shape_area(doc, n, Some(&hook)) {
Some(area) => out.push((area, FillRule::NonZero)),
None => members(doc, n, out),
}
@@ -714,7 +729,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
let mut m = n.clone();
if pathfinder {
let hook = |c: &Node| crate::outline_object(doc, c);
let result = pathfinder_children(n, Some(&hook)).unwrap_or_default();
let result = pathfinder_children(doc, n, Some(&hook)).unwrap_or_default();
if let Some(ch) = m.children_mut() {
*ch = result;
}
@@ -723,7 +738,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
if !fx.is_empty() {
m = crate::reshape::outlined_members(doc, &m);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx);
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
+235 -23
View File
@@ -27,7 +27,7 @@ fn area(n: &Node) -> f64 {
}
fn overlap_cmyk(g: &Node) -> [f32; 4] {
let faces = pathfinder_children(g, None).unwrap();
let faces = pathfinder_children(None, g, None).unwrap();
assert_eq!(faces.len(), 3);
let overlap = faces
.iter()
@@ -61,7 +61,7 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, yellow), sq(2, 10.0, blue)]);
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
let out = pathfinder_children(&g, None).unwrap();
let out = pathfinder_children(None, &g, None).unwrap();
assert_eq!(out.len(), 3, "both squares and one trap");
assert_eq!((out[0].id, out[1].id), (NodeId(1), NodeId(2)));
let b = out[2].geometric_bounds().unwrap();
@@ -89,17 +89,17 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
#[test]
fn shape_modes_follow_the_pathfinder_panel() {
let add = pathfinder_children(&group_with("pathfinder.add"), None).unwrap();
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
assert_eq!(add.len(), 1);
assert!((area(&add[0]) - 150.0).abs() < 1e-3);
// Add keeps the front object's paint, Subtract the back one's.
assert_eq!(add[0].id, NodeId(2));
let sub = pathfinder_children(&group_with("pathfinder.subtract"), None).unwrap();
let sub = pathfinder_children(None, &group_with("pathfinder.subtract"), None).unwrap();
assert_eq!(sub[0].id, NodeId(1));
assert!((area(&sub[0]) - 50.0).abs() < 1e-3);
let int = pathfinder_children(&group_with("pathfinder.intersect"), None).unwrap();
let int = pathfinder_children(None, &group_with("pathfinder.intersect"), None).unwrap();
assert!((area(&int[0]) - 50.0).abs() < 1e-3);
let div = pathfinder_children(&group_with("pathfinder.divide"), None).unwrap();
let div = pathfinder_children(None, &group_with("pathfinder.divide"), None).unwrap();
assert_eq!(div.len(), 3);
}
@@ -112,7 +112,7 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() {
for effect in ["pathfinder.divide", "pathfinder.outline"] {
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unpainted.clone()]);
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(&g, None).unwrap();
let out = pathfinder_children(None, &g, None).unwrap();
assert!(out.iter().any(|n| n.id == NodeId(1)) && out.iter().any(|n| n.id == NodeId(2)), "{effect}: {out:#?}");
for n in out.iter().filter(|n| n.id == NodeId(2)) {
assert!(n.appearance.items.iter().all(|i| i.paint().is_none()), "{effect}: {n:#?}");
@@ -138,7 +138,7 @@ fn square_and(front: Option<Node>, effect: &str) -> Node {
/// Returns the Pathfinder results of `g`, with type outlined as the renderer outlines it.
fn results(g: &Node) -> Vec<Arc<Node>> {
pathfinder_children(g, crate::text_outliner()).unwrap()
pathfinder_children(None, g, crate::text_outliner()).unwrap()
}
#[test]
@@ -167,7 +167,7 @@ fn type_changes_the_result_of_every_pathfinder_effect() {
assert!((with_type("pathfinder.intersect") + with_type("pathfinder.minusBack") - glyph_area).abs() < 0.5, "{glyph_area}");
// Outline art nested one group deeper takes part as well.
let nested: OutlineHook = &|n: &Node| crate::outline_text(n).map(|g| Node::group(n.id, vec![Arc::new(g)]));
let sub = pathfinder_children(&square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap();
let sub = pathfinder_children(None, &square_and(Some(type_h()), "pathfinder.subtract"), Some(nested)).unwrap();
assert!((sub.iter().map(|n| area(n)).sum::<f64>() - with_type("pathfinder.subtract")).abs() < 1e-6);
}
@@ -243,7 +243,7 @@ fn type_in_a_group_keeps_its_look_when_the_groups_geometry_effects_outline_it()
fn hidden_effect_or_plain_group_is_untouched() {
let mut g = group_with("pathfinder.add");
g.appearance.effects[0].visible = false;
assert!(pathfinder_children(&g, None).is_none());
assert!(pathfinder_children(None, &g, None).is_none());
assert!(!has_pathfinder(&sq(1, 0.0, Color::BLACK)));
}
@@ -320,12 +320,12 @@ fn shape_art_moves_gradients_with_a_transform_effect() {
};
let mut path = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(placed.clone(), Paint::None, 0.0));
path.appearance.effects.push(moved());
let got = starts(&shape_art(&path, None).unwrap());
let got = starts(&shape_art(None, &path, None).unwrap());
assert!(got.len() == 1 && (got[0] - 40.0).abs() < 1e-6, "the path's gradient: {got:?}");
let mut g = Node::group(NodeId(10), vec![sq(2, 0.0, Color::BLACK)]);
g.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed)));
g.appearance.effects.push(moved());
let got = starts(&shape_art(&g, None).unwrap());
let got = starts(&shape_art(None, &g, None).unwrap());
assert!(!got.is_empty() && got.iter().all(|s| (s - 40.0).abs() < 1e-6), "the group's own fill: {got:?}");
}
@@ -343,12 +343,48 @@ fn shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform() {
let hook = move |_: &Node| Some(art.clone());
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
instance.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30}), visible: true });
let out = shape_art(&instance, Some(&hook)).unwrap();
let out = shape_art(None, &instance, Some(&hook)).unwrap();
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient: {:?}", out.appearance) };
assert!((g.geom.unwrap().start.x - 30.0).abs() < 1e-6, "{:?}", g.geom);
assert!((out.geometric_bounds().unwrap().x0 - 30.0).abs() < 1e-6, "the art moves");
}
/// Under a Warp effect, the gradient placed on a symbol instance's art's own fill follows the art's
/// bounds, and the gradient placed on a compound shape follows its area's bounds, each from before
/// the warp to after it, in the art Pathfinder takes.
#[test]
fn shape_art_moves_the_gradients_of_a_symbol_instances_art_and_a_compound_shape_with_a_warp() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = GradientGeom { start: (2.0, 3.0).into(), end: (9.0, 3.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
let follow = |p: Point, from: Rect, to: Rect| {
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
};
let check = |out: &Node, from: Rect, what: &str| {
let to = out.geometric_bounds().unwrap();
assert_ne!(from, to, "{what}: the warp changes the bounds");
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("{what}: a gradient: {:?}", out.appearance) };
let got = g.geom.unwrap();
let (s, e) = (follow(geom.start, from, to), follow(geom.end, from, to));
assert!(got.start.distance(s) < 1e-6 && got.end.distance(e) < 1e-6, "{what}: {got:?}, want {s:?} {e:?}");
};
for style in ["arc", "rise", "bulge"] {
let warp = || Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true };
let mut art = Node::group(NodeId(20), vec![sq(21, 0.0, Color::BLACK)]);
art.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed.clone())));
let hook = move |_: &Node| Some(art.clone());
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
instance.appearance.effects.push(warp());
check(&shape_art(None, &instance, Some(&hook)).unwrap(), Rect::new(0.0, 0.0, 10.0, 10.0), &format!("warp.{style} on a symbol instance"));
let mut shape = compound_shape(ShapeMode::Add);
shape.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into();
shape.appearance.effects.push(warp());
check(&shape_art(None, &shape, None).unwrap(), Rect::new(0.0, 0.0, 15.0, 10.0), &format!("warp.{style} on a compound shape"));
}
}
#[test]
fn a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
@@ -378,6 +414,118 @@ fn a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths()
assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}");
}
/// A group's Warp effect moves and scales the gradient placed on each of its paths from that path's
/// bounds before the warp to its bounds after it, not by the group's bounds.
#[test]
fn a_groups_warp_moves_the_gradients_placed_on_its_paths_by_each_paths_bounds() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = |x: f64| GradientGeom { start: (x + 2.0, 3.0).into(), end: (x + 8.0, 3.0).into(), aspect: 1.0, focal: None };
let placed = |x: f64| Paint::Gradient(Box::new(GradientPaint { geom: Some(geom(x)), ..ramp.clone() }));
let square = |id: u64, x: f64| {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(placed(x), Paint::None, 0.0)))
};
for style in ["arc", "bulge", "rise", "twist"] {
let mut g = Node::group(NodeId(10), vec![square(1, 0.0), square(2, 20.0)]);
g.appearance.effects.push(Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true });
let art = evaluate_container(None, &g).unwrap();
let mut moved = false;
for (i, x) in [0.0, 20.0].into_iter().enumerate() {
let m = &art.children().unwrap()[i];
let b = m.geometric_bounds().unwrap();
let follow = |p: Point| Point::new(b.x0 + (p.x - x) / 10.0 * b.width(), b.y0 + p.y / 10.0 * b.height());
let Paint::Gradient(gp) = m.appearance.fill_paint() else { panic!("a gradient") };
let got = gp.geom.unwrap();
let want = geom(x);
assert!(
got.start.distance(follow(want.start)) < 1e-6 && got.end.distance(follow(want.end)) < 1e-6,
"warp.{style} path {i}: {got:?} in {b:?}"
);
moved |= got.start.distance(want.start) > 0.1;
}
assert!(moved, "warp.{style} moves a gradient");
}
}
/// Under a group's Warp effect, the group's own placed gradients follow the group's bounds, a
/// nested group's own placed gradients follow the nested group's bounds, and a compound path's
/// placed gradients follow the compound path's bounds, each from before the warp to after it (a
/// stroke's: those bounds inflated by the stroke).
#[test]
fn a_groups_warp_moves_its_own_a_nested_groups_and_a_compound_paths_gradients_by_their_bounds() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops));
let geom = GradientGeom { start: (12.0, 4.0).into(), end: (26.0, 4.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp }));
let own_fill = |n: &mut Node| {
n.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(placed.clone())));
n.appearance.items.push(AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(placed.clone(), 3.0)));
};
let follow = |p: Point, from: Rect, to: Rect| {
Point::new(to.x0 + (p.x - from.x0) / from.width() * to.width(), to.y0 + (p.y - from.y0) / from.height() * to.height())
};
for style in ["arc", "bulge", "rise", "flag"] {
let mut inner = Node::group(NodeId(5), vec![sq(1, 0.0, Color::BLACK)]);
own_fill(&mut inner);
let ring = vec![
Arc::new(Node::path(NodeId(6), shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 14.0)), Appearance::default())),
Arc::new(Node::path(NodeId(7), shapes::rectangle(Rect::new(23.0, 3.0, 27.0, 7.0)), Appearance::default())),
];
let mut compound = Node::new(NodeId(3), NodeKind::Compound { children: ring, rule: FillRule::EvenOdd });
compound.appearance = Appearance::basic(placed.clone(), placed.clone(), 2.0).into();
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), Arc::new(compound), sq(2, 40.0, Color::BLACK)]);
own_fill(&mut g);
let mut before = std::collections::HashMap::new();
g.walk(&mut |c: &Node| {
before.insert(c.id, c.geometric_bounds().unwrap());
});
g.appearance.effects.push(Effect { id: format!("warp.{style}"), params: serde_json::json!({"bend": 40.0}), visible: true });
let art = evaluate_container(None, &g).unwrap();
// The bounds after the warp of the group, the nested group and the compound path (the paths
// a group's own fill paints carry the group's id).
let mut after = std::collections::HashMap::new();
art.walk(&mut |c: &Node| {
if matches!(c.kind, NodeKind::Group { .. } | NodeKind::Compound { .. }) {
after.entry(c.id).or_insert_with(|| c.geometric_bounds().unwrap());
}
});
let mut checked = vec![];
art.walk(&mut |c: &Node| {
if ![NodeId(3), NodeId(5), NodeId(10)].contains(&c.id) {
return;
}
for item in &c.appearance.items {
let Paint::Gradient(gp) = item.paint() else { continue };
let (from, to) = (before[&c.id], after[&c.id]);
assert_ne!(from, to, "warp.{style} {:?}: the warp changes the bounds", c.id);
let stroke = match item {
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
};
let (from, to) = match stroke {
Some(s) => (s.paint_bounds(from), s.paint_bounds(to)),
None => (from, to),
};
let got = gp.geom.unwrap();
let (s, e) = (follow(geom.start, from, to), follow(geom.end, from, to));
assert!(
got.start.distance(s) < 1e-6 && got.end.distance(e) < 1e-6,
"warp.{style} {:?} (stroke: {}): {got:?}, want {s:?} {e:?} ({from:?} to {to:?})",
c.id,
stroke.is_some()
);
checked.push((c.id, stroke.is_some()));
}
});
checked.sort();
checked.dedup();
let want: Vec<_> = [NodeId(3), NodeId(5), NodeId(10)].into_iter().flat_map(|id| [(id, false), (id, true)]).collect();
assert_eq!(checked, want, "warp.{style}");
}
}
/// A group nested in a group with a Transform effect or Free Distort keeps its own placed gradient
/// on its members: the Transform's map moves it, and Free Distort moves and scales it from the
/// nested group's bounds before the effect to its bounds after it.
@@ -450,6 +598,70 @@ fn a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills() {
}
}
/// A group's Transform effect that turns its art turns the gradients fitted to its paths, to the
/// group's own fill, to a nested group's own fill and to an image's and a symbol instance's own
/// fills: each is fixed to its fit on its own object first. A move leaves the members' gradients
/// fitted.
#[test]
fn a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::ImageObject;
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
let fitted = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let square = |id: u64, x: f64| {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::basic(fitted.clone(), Paint::None, 0.0)))
};
let mut image = Node::new(
NodeId(4),
NodeKind::Image(Box::new(ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::translate((30.0, 0.0)),
link: None,
placement: Default::default(),
pixels: None,
})),
);
image.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into();
// A symbol instance whose symbol is not in a document is measured as the 20 pt square about
// its origin: here 22.5..27.5 across and 2.5..7.5 down.
let at = vectorcraft_geom::Affine::translate((25.0, 5.0)) * vectorcraft_geom::Affine::scale(0.25);
let mut instance = Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: at });
instance.appearance = Appearance::basic(fitted.clone(), Paint::None, 0.0).into();
// Ends of each gradient by object id; none for a gradient still fitted.
let ends = |params: serde_json::Value| {
let mut inner = Node::group(NodeId(5), vec![square(2, 10.0)]);
inner.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone())));
let mut g = Node::group(NodeId(10), vec![square(1, 0.0), Arc::new(inner), Arc::new(image.clone()), Arc::new(instance.clone())]);
g.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(fitted.clone())));
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let mut out = std::collections::BTreeMap::new();
art.walk(&mut |c: &Node| {
if let Paint::Gradient(p) = c.appearance.fill_paint() {
out.insert(c.id.0, p.geom.map(|g| (g.start, g.end)));
}
});
out
};
let near = |a: Point, b: Point| a.distance(b) < 1e-6;
// A quarter turn about the group's center (20, 5): (x, 5) goes to (20, 5 + 20 - x), so a ramp
// from (x0, 5) to (x1, 5) runs from (20, 25 - x0) up to (20, 25 - x1).
let turned = ends(serde_json::json!({"rotate": 90}));
let want = [(1, 0.0, 10.0), (2, 10.0, 20.0), (5, 10.0, 20.0), (4, 30.0, 40.0), (6, 22.5, 27.5), (10, 0.0, 40.0)];
for (id, x0, x1) in want {
let got = turned.get(&id).copied().flatten();
let ok = got.is_some_and(|(s, e)| near(s, Point::new(20.0, 25.0 - x0)) && near(e, Point::new(20.0, 25.0 - x1)));
assert!(ok, "object {id}: {got:?} in {turned:?}");
}
// The group's own fill is fixed to its fit on the art it paints, which the move took to 30..70.
let moved = ends(serde_json::json!({"moveH": 30}));
let group = moved.get(&10).copied().flatten();
assert!(group.is_some_and(|(s, e)| near(s, Point::new(30.0, 5.0)) && near(e, Point::new(70.0, 5.0))), "{moved:?}");
assert!(moved.len() == 6 && [1, 2, 4, 5, 6].iter().all(|id| moved[id].is_none()), "{moved:?}");
}
#[test]
fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
@@ -502,7 +714,7 @@ fn pathfinder_past_its_budget_draws_the_source_art() {
// n² crossings past the cap: no evaluation (#3591), the source art as it is.
for n in [130, 800] {
let g = crossing_bars(n, "pathfinder.divide");
let out = pathfinder_children(&g, None).unwrap();
let out = pathfinder_children(None, &g, None).unwrap();
assert_eq!(out.len(), 2 * n, "{n} x {n} bars");
let ids: Vec<NodeId> = out.iter().map(|c| c.id).collect();
let src: Vec<NodeId> = g.children().unwrap().iter().map(|c| c.id).collect();
@@ -517,7 +729,7 @@ fn pathfinder_within_its_budget_still_divides() {
// n x n bars divide into 3·n² pieces, and 128 x 128 bars, which overlap in exactly
// `PATHFINDER_MAX_OVERLAPS` pairs, must still divide.
for n in [8, 128] {
let out = pathfinder_children(&crossing_bars(n, "pathfinder.divide"), None).unwrap();
let out = pathfinder_children(None, &crossing_bars(n, "pathfinder.divide"), None).unwrap();
assert_eq!(out.len(), 3 * n * n, "{n} x {n} bars");
}
}
@@ -535,7 +747,7 @@ fn pathfinder_on_many_stacked_bars_still_runs() {
.collect();
let mut g = Node::group(NodeId(10), children);
g.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(&g, None).unwrap();
let out = pathfinder_children(None, &g, None).unwrap();
assert_eq!(out.len(), 1);
}
@@ -556,9 +768,9 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
for (mode, want) in [(ShapeMode::Add, 150.0), (ShapeMode::Subtract, 50.0), (ShapeMode::Intersect, 50.0), (ShapeMode::Exclude, 100.0)] {
let g = compound_shape(mode);
assert!(has_pathfinder(&g), "{mode:?}");
let area_path = compound_shape_area(&g, None).unwrap();
let area_path = compound_shape_area(None, &g, None).unwrap();
assert!((po::area(&area_path, FillRule::NonZero).abs() - want).abs() < 0.01, "{mode:?}");
let out = pathfinder_children(&g, None).unwrap();
let out = pathfinder_children(None, &g, None).unwrap();
assert_eq!(out.len(), 1, "{mode:?}");
assert!(out[0].appearance.items.is_empty(), "the group's own appearance paints it");
let art = evaluate_container(None, &g).unwrap();
@@ -575,7 +787,7 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
back.extras_mut().shape_mode = ShapeMode::Subtract;
ch[0] = Arc::new(back);
}
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01);
assert!((po::area(&compound_shape_area(None, &g, None).unwrap(), FillRule::NonZero).abs() - 150.0).abs() < 0.01);
// Hidden members take no part; the mark on a clip group is ignored.
let mut g = compound_shape(ShapeMode::Subtract);
if let Some(ch) = g.children_mut() {
@@ -583,10 +795,10 @@ fn compound_shapes_draw_the_area_their_shape_modes_make() {
front.visible = false;
ch[1] = Arc::new(front);
}
assert!((po::area(&compound_shape_area(&g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01);
assert!((po::area(&compound_shape_area(None, &g, None).unwrap(), FillRule::NonZero).abs() - 100.0).abs() < 0.01);
let mut clip = compound_shape(ShapeMode::Add);
clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true };
assert!(!clip.is_compound_shape() && compound_shape_area(&clip, None).is_none());
assert!(!clip.is_compound_shape() && compound_shape_area(None, &clip, None).is_none());
}
/// A compound shape inside another (and inside an Effect › Pathfinder group) takes part as its area,
@@ -599,10 +811,10 @@ fn nested_compound_shapes_take_part_as_their_area() {
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner.clone()), Arc::new(cutter)]);
outer.extras_mut().compound_shape = true;
// (0–5 of the inner area) ∩ (2–12) = 2–5 by 10 high.
assert!((po::area(&compound_shape_area(&outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01);
assert!((po::area(&compound_shape_area(None, &outer, None).unwrap(), FillRule::NonZero).abs() - 30.0).abs() < 0.01);
let mut effect = Node::group(NodeId(30), vec![Arc::new(inner)]);
effect.appearance.effects.push(Effect { id: "pathfinder.add".into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(&effect, None).unwrap();
let out = pathfinder_children(None, &effect, None).unwrap();
assert_eq!(out.len(), 1);
assert!((area(&out[0]) - 50.0).abs() < 0.01);
assert_eq!(out[0].appearance.fill_paint().color(), Some(Color::rgb(0.0, 1.0, 0.0)), "styled like the compound shape");
+7 -5
View File
@@ -80,13 +80,14 @@ pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, has_gradient_copies, has_item_geometry, has_transform_art, has_transform_copies, has_transform_options,
image_paint, needs_outline, outline_art, outline_text, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
};
pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve};
pub use solids::{
EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, SolidMesh, THREE_D_TYPES, extrude_options, has_solid, inflate_options, is_three_d, solid_art,
three_d_meshes, three_d_params_as, validate_solid, validate_three_d, view_options,
CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options,
classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as,
validate_solid, validate_three_d, validate_three_d_params, view_options,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
@@ -106,5 +107,6 @@ pub use geometry::{
#[cfg(test)]
pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within};
pub use params::{
default_params, has_geometry, has_plugin_effect, is_geometry, is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params,
any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params,
new_effect, plugin_revision, scale_effect, upgrade_params,
};
+2 -1
View File
@@ -43,7 +43,8 @@ fn with_hooks<R>(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
vectorcraft_text::register_envelope_ink();
let outline = |n: &Node| outline_object(doc, n);
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
f(Hooks { outline: Some(&outline), appearance: Some(&bake_appearance), pattern: Some(&tiles), symbols: doc })
let appearance = |n: &Node| bake_appearance(doc, n);
f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc })
}
/// One level of evaluation of live object `n` ([`live::expand_live_hooks`]).
+13
View File
@@ -148,6 +148,19 @@ pub fn has_plugin_effect(n: &Node) -> bool {
n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.effects().iter().any(plugin))
}
/// Does `n` have a visible live-effect plug-in effect, its own or a fill's or stroke's, whose
/// plug-in paints the pieces it returns? What such an effect draws also depends on the document's
/// swatches and patterns, which its pieces may name.
pub fn has_painted_plugin_effect(n: &Node) -> bool {
let painted = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some_and(vectorcraft_plugins::effect::paints_output);
n.appearance.effects.iter().any(painted) || n.appearance.items.iter().any(|i| i.effects().iter().any(painted))
}
/// Is a live-effect plug-in that paints the pieces it returns installed?
pub fn any_plugin_paints_output() -> bool {
vectorcraft_plugins::registry::list().iter().any(|p| vectorcraft_plugins::effect::paints_output(&p.manifest().id))
}
/// The plug-in registry's revision, which changes whenever a plug-in is installed or removed.
pub fn plugin_revision() -> u64 {
vectorcraft_plugins::registry::revision()
+305 -81
View File
@@ -103,10 +103,27 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`])? It is drawn, baked and expanded through
/// that art ([`reshape`]).
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`]), or whose
/// live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, baked and
/// expanded through that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n)
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n)
}
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
/// else `None`.
fn painted_plugin(e: &Effect) -> Option<&str> {
let id = vectorcraft_plugins::effect::plugin_id(&e.id).filter(|_| e.visible)?;
vectorcraft_plugins::effect::paints_output(id).then_some(id)
}
/// Is `n` a path or compound path with a live-effect plug-in that paints what it returns
/// ([`painted_plugin`]), its own or on a fill or stroke that paints? Each piece the plug-in returns
/// is then an object of its own with its own paints ([`paint_leaf`], [`transform_item_leaf`]).
pub fn has_painted_effects(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })
&& (n.appearance.effects.iter().any(|e| painted_plugin(e).is_some())
|| n.appearance.items.iter().any(|i| crate::paints(i) && i.effects().iter().any(|e| painted_plugin(e).is_some())))
}
/// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a
@@ -133,7 +150,13 @@ fn gives_shape(e: &Effect) -> bool {
/// Does `item`, a fill or stroke of an image, paint something: does it paint and carry an effect
/// that gives it a shape ([`gives_shape`])?
fn shapes_image(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(gives_shape)
crate::paints(item) && gives_image_shape(item.effects())
}
/// Do `effects`, those of an image's fill or stroke, give that fill or stroke a shape to paint
/// ([`gives_shape`])?
pub fn gives_image_shape(effects: &[Effect]) -> bool {
effects.iter().any(gives_shape)
}
/// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each
@@ -157,17 +180,18 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
/// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill
/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that
/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies
/// them. Empty for anything but an image with such fills or strokes.
pub fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
}
let Some(art) = reshape(None, n, None) else { return vec![] };
let Some(art) = reshape(doc, n, None) else { return vec![] };
let mut out = vec![];
art.walk(&mut |c| {
let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return };
let Some(g) = c.stroke_path() else { return };
let ctx = GeomContext::of(c);
let ctx = GeomContext { doc, ..GeomContext::of(c) };
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
let fx = item.effects();
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
@@ -280,14 +304,17 @@ fn with_id(art: &Node, id: NodeId) -> Node {
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
/// `doc`'s symbols that its instances show toward its instance budget.
pub fn outline_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
outline_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
outline_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default(), false)
}
/// [`outline_art`] with live objects evaluated through `outline` ([`evaluated_with`]); with
/// `apart`, also a path or compound path whose Transform effect makes copies
/// ([`has_transform_copies`]), as the one piece the copies are made from.
/// ([`has_transform_copies`]), as the one piece the copies are made from. `symbols` is the document
/// the symbols of the art come from; `paint_doc` is the one the swatches and patterns of painted
/// pieces are looked up in.
fn outline_art_with(
doc: Option<&Document>,
symbols: Option<&Document>,
paint_doc: Option<&Document>,
n: &Node,
symbol_art: Option<&Node>,
outline: OutlineHook,
@@ -297,7 +324,7 @@ fn outline_art_with(
let mut art = match &n.kind {
NodeKind::Text(_) => outline_text(n)?,
NodeKind::SymbolInstance { symbol, xf } => {
let a = match doc {
let a = match symbols {
Some(d) => d.place_symbol_art(symbol, symbol_art?, *xf)?,
None => {
let mut a = symbol_art?.clone();
@@ -317,10 +344,10 @@ fn outline_art_with(
one.appearance.effects.clear();
Node::group(n.id, vec![Arc::new(one)])
}
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(doc, n, outline, nodes),
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes),
_ => return None,
};
outline_nested_text(&mut art, false);
outline_nested_text(paint_doc, &mut art, false);
art.opacity = 1.0;
art.blend = Default::default();
art.isolate = false;
@@ -427,21 +454,22 @@ fn instances_as_art(doc: Option<&Document>, n: &mut Node, outline: OutlineHook,
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
/// its plain outlines ([`outline_text`]) with its visibility, which is what
/// [`crate::clip_outline`] clips by.
pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) {
/// [`crate::clip_outline`] clips by. The swatches and patterns that live-effect plug-ins painting
/// their pieces name are looked up in `doc`.
pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) {
let clips = n.clips();
let Some(ch) = n.children_mut() else { return };
for (i, c) in ch.iter_mut().enumerate() {
let clipping = clipping || (clips && i == 0);
let art = match &c.kind {
NodeKind::Text(_) if clipping => outline_text(c).map(|o| Node { visible: c.visible, ..o }),
NodeKind::Text(_) => as_art(None, c, None),
NodeKind::Text(_) => as_art(doc, c, None),
_ => None,
};
if let Some(o) = art {
*c = Arc::new(o);
} else if c.children().is_some() {
outline_nested_text(Arc::make_mut(c), clipping);
outline_nested_text(doc, Arc::make_mut(c), clipping);
}
}
}
@@ -474,7 +502,7 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
// effect in a group of their own (copies of copies nest), as the reference app expands them
// (#5612).
if has_transform_art(n) || has_transform_copies(n) {
return as_art_opts(doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
return as_art_opts(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default(), true);
}
let own_paint = match n.kind {
NodeKind::Text(_) => !n.appearance.items.is_empty(),
@@ -488,17 +516,34 @@ pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Nod
/// [`reshape`] without its checks (no geometry effects: just the art).
pub(crate) fn as_art(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
as_art_with(doc, n, symbol_art, &outline_text, &SymbolNodes::default())
as_art_with(doc, doc, n, symbol_art, &outline_text, &SymbolNodes::default())
}
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]).
pub(crate) fn as_art_with(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes) -> Option<Node> {
as_art_opts(doc, n, symbol_art, outline, nodes, false)
/// [`as_art`] with live objects evaluated through `outline` ([`evaluated_with`]). `symbols` is the
/// document the symbols of the art come from; `paint_doc` is the one the swatches and patterns of
/// painted pieces are looked up in.
pub(crate) fn as_art_with(
symbols: Option<&Document>,
paint_doc: Option<&Document>,
n: &Node,
symbol_art: Option<&Node>,
outline: OutlineHook,
nodes: &SymbolNodes,
) -> Option<Node> {
as_art_opts(symbols, paint_doc, n, symbol_art, outline, nodes, false)
}
/// [`as_art_with`]; with `apart`, a path's or compound path's Transform effects make each copy an
/// object of its own ([`copy_leaf`]) rather than one path of every copy.
fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outline: OutlineHook, nodes: &SymbolNodes, apart: bool) -> Option<Node> {
fn as_art_opts(
symbols: Option<&Document>,
paint_doc: Option<&Document>,
n: &Node,
symbol_art: Option<&Node>,
outline: OutlineHook,
nodes: &SymbolNodes,
apart: bool,
) -> Option<Node> {
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
@@ -526,13 +571,13 @@ fn as_art_opts(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>, outl
Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect())
}
}
_ => outline_art_with(doc, n, symbol_art, outline, nodes, apart)?,
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
};
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart);
reshape_leaves_apart(&mut art, &fx, Budget::EFFECTS, apart, paint_doc);
if apart {
hoist_copies(&mut art);
}
transform_items(&mut art);
transform_items(&mut art, paint_doc);
// Type and symbols in perspective: the art projected onto their plane.
if let Some(h) = n.projection() {
project_leaves(&mut art, &h);
@@ -590,20 +635,22 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
/// symbol instances follow a Transform effect the same way ([`transform_placed`]); other geometry
/// effects leave them as they are (a raster follows a non-affine map only as a mesh warp). The
/// paths keep to one [`Budget::EFFECTS`] together (or to what they cost, when that is more): a path
/// whose effect would pass what the others leave of it keeps its shape.
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect]) {
reshape_leaves_within(art, fx, Budget::EFFECTS);
/// whose effect would pass what the others leave of it keeps its shape. The swatches and patterns
/// that live-effect plug-ins painting their pieces name are looked up in `doc`
/// ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc);
}
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
/// strokes) follow the effects ([`crate::Carry`]).
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect]) -> crate::Carry {
reshape_leaves_within(art, fx, Budget::EFFECTS)
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_within(art, fx, Budget::EFFECTS, doc)
}
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget) -> crate::Carry {
reshape_leaves_apart(art, fx, budget, false)
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, budget, false, doc)
}
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
@@ -623,9 +670,11 @@ fn hoist_copies(art: &mut Node) {
}
/// [`reshape_leaves_within`]; with `apart`, a Transform effect's copies of each path are objects
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. Returns how
/// gradients that paint the art as a whole follow the effects.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool) -> crate::Carry {
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
@@ -652,12 +701,24 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
for e in fx {
let Some(bounds) = art.geometric_bounds() else { break };
let params = merged_params(&e.id, &e.params);
// Placed gradients follow a Transform effect and Free Distort ([`crate::Carry`]): under
// Free Distort (`boxes`) each path's move and scale from its bounds before the effect to
// its bounds after it. Under that and the other effects, the placed gradients of type's
// outlines in `art` (`outline_text`) move and scale with the outlines' bounds.
if let Some(plugin) = painted_plugin(e) {
for_each_leaf(art, &mut |leaf| {
let Some((path, _)) = leaf_geometry(leaf) else { return };
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc) {
used = used.minus(before).plus(made);
}
});
continue;
}
// Placed gradients follow a Transform effect, Free Distort and the Warp effects
// ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from
// its bounds before the effect to its bounds after it. Under those and the other effects,
// the placed gradients of type's outlines in `art` (`outline_text`) move and scale with
// the outlines' bounds.
let follows = crate::Carry::follows(&e.id, &params, bounds, seed);
let boxes = follows && e.id == "distort.freeDistort";
let boxes = follows && crate::Carry::by_bounds(&e.id);
let mut outlines = vec![];
if !follows || boxes {
type_outline_bounds(art, &mut outlines);
@@ -670,8 +731,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
if follows {
group_marks(art, &mut vec![], &HashSet::new(), &mut groups);
}
// Whether a path kept its shape (past the budget), and the ids of those that did.
let mut kept = false;
// The ids of the paths that kept their shape (past the budget).
let mut kept_ids = HashSet::new();
let transform = (e.id == "distort.transform").then(|| {
let (m, copies) = crate::distort::transform_map(bounds, &params, seed);
@@ -697,25 +757,28 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
used = used.minus(before).plus(made);
if !moved {
kept = true;
kept_ids.insert(leaf.id);
}
return;
}
if separate {
let made = copy_leaf(leaf, &path, m, copies, vectorcraft_doc::Scaling::default(), room);
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
let made = copy_leaf(leaf, &path, m, copies, scaling, room);
used = used.minus(before).plus(made);
return;
}
}
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, ..GeomContext::of(leaf) }, room) else {
kept = true;
kept_ids.insert(leaf.id);
return;
};
used = used.minus(before).plus(Budget::of(&out));
if follows && !boxes && leaf.appearance.has_placed_gradient() {
crate::Carry::of(&e.id, &params, bounds, None, None, seed).apply(&mut leaf.appearance);
if follows && !boxes {
// A gradient fitted to the path fits the path's own bounds.
let carry = crate::Carry::of(&e.id, &params, bounds, path.bounds(), None, seed);
if carry.moves(&leaf.appearance) {
carry.apply(&mut leaf.appearance);
}
}
set_geometry(leaf, out, rule);
});
@@ -731,14 +794,14 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
rebase_type_outlines(art, &mut outlines.into_iter());
}
// What paints the art as a whole, and the own fills and strokes of the groups inside it,
// follow their bounds under Free Distort (they stay when no path changed them). Each stays
// when a path under it kept its shape (past the budget).
// follow their bounds under Free Distort and Warp (they stay when no path changed them).
// Each stays when a path under it that its bounds measure kept its shape (past the budget).
let mut after = vec![];
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, &mut after).1;
if !groups.is_empty() {
let mut after = vec![];
group_marks(art, &mut vec![], &kept_ids, &mut after);
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, &params, bounds, from, to, seed));
}
if follows && !kept {
if follows && !held {
whole.push(crate::Carry::of(&e.id, &params, bounds, Some(bounds), art.geometric_bounds(), seed));
}
}
@@ -770,6 +833,8 @@ fn transform_leaf(
strokes: options.strokes,
effects: options.strokes.then_some(crate::scale_effect as fn(&mut Effect, f64)),
patterns: options.patterns,
// A map that flattens the path leaves its fitted gradients fitted, as `fixes_fit` does.
keep_fit_when_flat: true,
..Default::default()
};
if !options.objects {
@@ -832,15 +897,118 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
made
}
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params` run on `leaf`, a
/// path or compound path, as one of its object's effects with reference box `bounds`: `leaf`
/// becomes a group with its id and name of one object for each piece returned, in order, each with
/// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
/// refused, or they would pass `budget`.
fn paint_leaf(leaf: &mut Node, plugin: &str, params: &serde_json::Value, bounds: Rect, budget: Budget, doc: Option<&Document>) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
return None;
}
let children = pieces
.iter()
.map(|p| {
let mut one = leaf.clone();
one.name = None;
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
set_geometry(&mut one, p.path.clone(), p.rule);
Arc::new(one)
})
.collect();
let mut g = Node::group(leaf.id, children);
g.name = leaf.name.clone();
*leaf = g;
Some(made)
}
/// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
fn piece_cost(path: &PathData) -> Budget {
let max = vectorcraft_plugins::objects::MAX_OBJECTS;
Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max })
}
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference
/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that
/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first
/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's
/// other fills and strokes; one that gives none keeps the leaf's. Returns
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
/// `budget`.
fn paint_piece(
leaf: &mut Node,
item: &AppearanceItem,
plugin: &str,
params: &serde_json::Value,
bounds: Rect,
budget: Budget,
doc: Option<&Document>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0) };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
return None;
}
let mut children = vec![];
for p in pieces.iter() {
let gives = match item {
AppearanceItem::Fill(_) => p.fills.is_some(),
AppearanceItem::Stroke(_) => p.strokes.is_some(),
};
let items = if gives {
let mut items = vectorcraft_plugins::painted::items(item, p);
items.extend_from_slice(leaf.appearance.items.get(1..).unwrap_or_default());
items
} else {
leaf.appearance.items.clone()
};
if items.is_empty() {
continue;
}
let mut one = leaf.clone();
one.appearance.items = items;
set_geometry(&mut one, p.path.clone(), p.rule);
children.push(Arc::new(one));
}
*leaf = Node::group(leaf.id, children);
Some(made)
}
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
/// ([`item_transform_options`]), made into a group of objects of its own ([`transform_item_leaf`]).
/// The new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is
/// more).
fn transform_items(art: &mut Node) {
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
fn transform_items(art: &mut Node, doc: Option<&Document>) {
let mut used = art_cost(art);
let max = Budget::EFFECTS.at_least(used);
for_each_leaf(art, &mut |leaf| transform_item_leaf(leaf, max, &mut used));
for_each_leaf(art, &mut |leaf| transform_item_leaf(leaf, max, &mut used, doc));
}
/// Is `e` an effect that makes a fill's or stroke's piece of a path an object of its own: a
/// Transform effect that [`reaches_appearance`], or a live-effect plug-in that paints what it
/// returns ([`painted_plugin`])?
fn makes_piece(e: &Effect) -> bool {
reaches_appearance(e) || painted_plugin(e).is_some()
}
/// Does `item` paint and carry an effect that [`makes_piece`]?
fn item_makes_piece(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(makes_piece)
}
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
@@ -855,8 +1023,17 @@ fn transform_items(art: &mut Node) {
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
/// what it has spent.
fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
if matches!(leaf.kind, NodeKind::Path { clipping: true, .. }) || !leaf.appearance.items.iter().any(item_transform_options) {
///
/// A fill or stroke whose first such effect is a live-effect plug-in that paints what it returns
/// ([`painted_plugin`]) becomes, in place of a transformed path, one path for each piece the
/// plug-in returns, painted by copies of the fill or stroke with the piece's paints
/// ([`vectorcraft_plugins::painted::items`]); the plug-in is given the geometry before it and told
/// which fill or stroke it is on. When it fails (or names a swatch or pattern not in `doc`, or any
/// without a document), the
/// fill or stroke paints that geometry as it is. The geometry effects after it then apply to all
/// the pieces as one ([`transform_piece`]).
fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Option<&Document>) {
if matches!(leaf.kind, NodeKind::Path { clipping: true, .. }) || !leaf.appearance.items.iter().any(item_makes_piece) {
return;
}
let Some((path, rule)) = leaf_geometry(leaf) else { return };
@@ -884,12 +1061,12 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
let mut pieces: Vec<Arc<Node>> = vec![];
let mut plain: Vec<AppearanceItem> = vec![];
// Which items become a transformed piece of their own; every other run of items is one plain piece.
let transformed: Vec<bool> = original.appearance.items.iter().map(|i| crate::paints(i) && i.effects().iter().any(reaches_appearance)).collect();
let transformed: Vec<bool> = original.appearance.items.iter().map(item_makes_piece).collect();
// The number of pieces after item `i` in paint order: each costs at least the leaf's geometry.
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
for (i, item) in original.appearance.items.iter().enumerate() {
let fx = item.effects();
let Some(at) = fx.iter().position(reaches_appearance).filter(|_| crate::paints(item)) else {
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
plain.push(item.clone());
continue;
};
@@ -912,6 +1089,33 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
};
let Some(tb) = g.bounds() else { continue };
let params = merged_params(&fx[at].id, &fx[at].params);
if let Some(plugin) = painted_plugin(&fx[at]) {
let mut it = item.clone();
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest;
let mut one = Appearance { items: vec![it.clone()], ..Default::default() };
if carry.moves(&one) {
carry.apply(&mut one);
}
let it = one.items.pop().unwrap_or(it);
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i) };
let painted = vectorcraft_plugins::effect::apply_painted(plugin, &params, &g, tb, rule, paints, doc)
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
// A failed run draws the fill or stroke on the geometry it was given.
let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]);
let mut group: Vec<Arc<Node>> = vec![];
for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) {
*used = used.plus(piece_cost(&path));
let mut p = piece(items);
set_geometry(&mut p, path, rule);
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, ctx.seed, limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
let (_, copies) = crate::distort::transform_map(tb, &params, ctx.seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(tb, &params, ctx.seed);
@@ -925,7 +1129,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
set_geometry(&mut p, g.clone(), rule);
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
*used = used.plus(made);
transform_piece(&mut p, ctx.seed, limit, used);
transform_piece(&mut p, ctx.seed, limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -944,9 +1148,11 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget) {
/// own effects reshape all its paths ([`reshape_leaves_within`]). Each path applies its own copy of
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
/// The geometry effects then leave the fills and strokes; their other effects stay. The paths keep
/// to `max` together with the rest of the art (`used`).
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and
/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`.
fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget, doc: Option<&Document>) {
let mut count = 0;
for_each_leaf(p, &mut |l| {
if let Some(item) = l.appearance.items.first() {
@@ -962,6 +1168,12 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
// What the other paths leave of the budget.
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
if let Some(plugin) = painted_plugin(&e) {
if let Some(made) = paint_piece(leaf, &item, plugin, &merged_params(&e.id, &e.params), bounds, room, doc) {
*used = used.minus(before).plus(made);
}
return;
}
if reaches_appearance(&e) {
let params = merged_params(&e.id, &e.params);
let (_, copies) = crate::distort::transform_map(bounds, &params, seed);
@@ -976,7 +1188,7 @@ fn transform_piece(p: &mut Node, seed: u64, max: Budget, used: &mut Budget) {
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
};
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0) };
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc };
let mut carry = crate::Carry::default();
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
*used = used.minus(before).plus(Budget::of(&out));
@@ -1020,7 +1232,7 @@ fn rebase_type_outlines(n: &mut Node, before: &mut std::vec::IntoIter<Option<Rec
&& from != to
{
for_each_leaf(n, &mut |leaf| {
if leaf.appearance.has_placed_gradient() {
if leaf.appearance.has_positioned_gradient() {
follow_boxes(&mut leaf.appearance, from, to);
}
});
@@ -1048,12 +1260,12 @@ fn is_member_group(n: &Node) -> bool {
}
/// A group below the art that [`is_member_group`] takes and whose own fills or strokes hold a
/// placed gradient: the child indices that lead to it from the art, its geometric bounds, and
/// whether a path below it kept its shape.
/// gradient: the child indices that lead to it from the art, its geometric bounds, and
/// whether a path below it that its bounds measure kept its shape.
type GroupMark = (Vec<usize>, Option<Rect>, bool);
/// The geometric bounds of `n` (as [`Node::geometric_bounds`] gives them) and whether a path or
/// compound path below it is in `kept`, measured in one walk. Each group below `n` that
/// compound path below it that those bounds measure is in `kept`, measured in one walk. Each group below `n` that
/// [`GroupMark`] describes goes into `out`, reached from `n` through `at`.
fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut Vec<GroupMark>) -> (Option<Rect>, bool) {
match &n.kind {
@@ -1065,14 +1277,15 @@ fn group_marks(n: &Node, at: &mut Vec<usize>, kept: &HashSet<NodeId>, out: &mut
for (i, c) in children.iter().enumerate() {
at.push(i);
let (b, h) = group_marks(c, at, kept, out);
if is_member_group(c) && c.appearance.has_placed_gradient() {
if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) {
out.push((at.clone(), b, h));
}
at.pop();
held |= h;
// Only members measured in the bounds hold the group's gradients in place.
let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) };
if counts {
bounds = vectorcraft_geom::union_opt(bounds, b);
held |= h;
}
}
(bounds, held)
@@ -1126,7 +1339,7 @@ fn rebase_leaves(n: &mut Node, before: &mut std::vec::IntoIter<Option<Rect>>) {
if let Some(Some(from)) = before.next()
&& let Some(to) = n.geometric_bounds()
&& from != to
&& n.appearance.has_placed_gradient()
&& n.appearance.has_positioned_gradient()
{
follow_boxes(&mut n.appearance, from, to);
}
@@ -1218,13 +1431,17 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
let src = (**c).clone();
let placed = |xf: Affine| {
let mut one = src.clone();
// Gradients fitted to it are fixed to their fit first when a refit would not match.
if crate::geometry::fixes_fit(xf) {
one.pin_gradients();
}
match &mut one.kind {
NodeKind::Image(im) => im.xf = xf * im.xf,
NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at,
_ => {}
}
// The placed gradients of its own fills and strokes move with it, as a path's do.
if xf != Affine::IDENTITY && one.appearance.has_placed_gradient() {
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
one.appearance.transform_gradients(xf);
}
one
@@ -1260,14 +1477,21 @@ fn placed_count(n: &Node) -> usize {
/// `n` with type anywhere inside it outlined and live objects evaluated, so geometry effects on
/// it reach every member.
pub(crate) fn outlined_members(doc: Option<&Document>, n: &Node) -> Node {
outlined_members_with(doc, n, &outline_text, &SymbolNodes::default())
outlined_members_with(doc, doc, n, &outline_text, &SymbolNodes::default())
}
/// [`outlined_members`] with live objects and symbol instances given as art through `outline`
/// ([`evaluated_with`]).
pub(crate) fn outlined_members_with(doc: Option<&Document>, n: &Node, outline: OutlineHook, nodes: &SymbolNodes) -> Node {
let mut art = evaluated_with(doc, n, outline, nodes);
outline_nested_text(&mut art, false);
/// ([`evaluated_with`]), with the symbols of the art from `symbols` and the swatches and patterns
/// of painted pieces looked up in `paint_doc`.
pub(crate) fn outlined_members_with(
symbols: Option<&Document>,
paint_doc: Option<&Document>,
n: &Node,
outline: OutlineHook,
nodes: &SymbolNodes,
) -> Node {
let mut art = evaluated_with(symbols, n, outline, nodes);
outline_nested_text(paint_doc, &mut art, false);
art
}
+16 -7
View File
@@ -66,19 +66,25 @@ pub fn revolve_options(p: &Value) -> Revolve {
/// Validate before a command mutates the document. Loading external files is still bounded
/// by the evaluator; unsupported source kinds remain unchanged when rendered.
pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> {
crate::lighting::validate(p)?;
validate_revolve_params(p)?;
let path = profile(n).ok_or("Revolve currently requires a path or compound path. Select a profile drawn with the Pen tool.")?;
let b = path.bounds().ok_or("Revolve requires a profile with at least two anchors")?;
if !path.subpaths.iter().any(|sp| sp.anchors.len() >= 2) {
return Err("Revolve requires at least two anchors".into());
}
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
}
/// Check Revolve's parameter values `p` alone: its lights, `edge` and `cap`.
pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
crate::lighting::validate(p)?;
if p.get("edge").is_some_and(|v| v.as_str() != Some("left") && v.as_str() != Some("right")) {
return Err("Revolve edge must be left or right".into());
}
if p.get("cap").is_some_and(|v| v.as_bool().is_none()) {
return Err("Revolve cap must be a boolean".into());
}
vectorcraft_three_d::revolve(&path, b, revolve_options(p)).map(|_| ())
Ok(())
}
fn profile(n: &Node) -> Option<PathData> {
@@ -228,8 +234,9 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
/// the object, one in its top visible fill (else its stroke); with it on fills and strokes, one for
/// each of them.
pub(crate) fn revolve_meshes(n: &Node) -> Result<Vec<crate::SolidMesh>, String> {
/// each of them. Each mesh adds its triangles to `total` as it is built, and the first that takes
/// `total` past `limit` stops with an error before the next is built.
pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let path = profile(n).ok_or("Revolve currently requires a path or compound path")?;
let ctx = GeomContext::of(n);
let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<crate::SolidMesh, String> {
@@ -250,7 +257,9 @@ pub(crate) fn revolve_meshes(n: &Node) -> Result<Vec<crate::SolidMesh>, String>
.find(|i| matches!(i, AppearanceItem::Fill(_)) && crate::paints(i))
.or_else(|| n.appearance.items.iter().rev().find(|i| crate::paints(i)))
.ok_or("the revolved object has no fill or stroke")?;
return Ok(vec![mesh(&path, fx, item)?]);
let mut out = vec![];
crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?;
return Ok(out);
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
@@ -259,7 +268,7 @@ pub(crate) fn revolve_meshes(n: &Node) -> Result<Vec<crate::SolidMesh>, String>
&& let Some(fx) = item.effects().get(index)
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
out.push(mesh(&p, fx, item)?);
crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?;
}
}
Ok(out)
@@ -473,7 +482,7 @@ mod tests {
let expanded = expand_revolve_art(&n).unwrap();
let count = |n: &Node| n.children().unwrap()[0].children().unwrap().len();
assert!(count(&expanded) < count(&live) * 3 / 4, "hidden back surfaces are removed");
assert_eq!(crate::bake_appearance(&n), Some(live.clone()), "other baking retains the full surface");
assert_eq!(crate::bake_appearance(None, &n), Some(live.clone()), "other baking retains the full surface");
n.appearance.effects[0].params["expandVisibleOnly"] = json!(false);
assert_eq!(revolve_art(&n), Some(live.clone()), "the live view ignores the expansion setting");
assert_eq!(expand_revolve_art(&n), Some(live));
+65 -23
View File
@@ -1,5 +1,5 @@
//! Extrude & Bevel, Inflate and Rotate as live, shaded vector art, shared by the canvas and every
//! exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces.
//! Extrude & Bevel, Inflate, Rotate and Extrude & Bevel (Classic) as live, shaded vector art,
//! shared by the canvas and every exporter. Like Revolve, the source path stays editable and the effect draws its 3D faces.
use std::sync::Arc;
use serde_json::Value;
@@ -14,11 +14,14 @@ use vectorcraft_doc::color::Color;
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry};
mod classic;
pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading};
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
/// The 3D effects this module draws (Revolve has its own).
pub const SOLIDS: [&str; 3] = [EXTRUDE, INFLATE, ROTATE];
pub const SOLIDS: [&str; 4] = [EXTRUDE, INFLATE, ROTATE, CLASSIC_EXTRUDE];
/// Is `id` one of the 3D and Materials effects (Revolve included)?
pub fn is_three_d(id: &str) -> bool {
@@ -119,6 +122,7 @@ pub fn extrude_options(p: &Value) -> Extrude {
inside: flag(p, "bevelInside", false),
both_sides: flag(p, "bevelBothSides", false),
}),
hidden: false,
}
}
@@ -172,21 +176,32 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
let view = view_options(p);
match id {
EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, extrude_options(p), view),
CLASSIC_EXTRUDE => vectorcraft_three_d::extrude(path, rule, bounds, classic_extrude_options(p), view),
INFLATE => vectorcraft_three_d::inflate(path, rule, bounds, inflate_options(p), view),
_ => vectorcraft_three_d::plane(path, rule, bounds, view),
}
}
/// Validate before a command changes the document; the evaluator bounds loaded files too.
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
/// need the object.
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
if id == CLASSIC_EXTRUDE {
classic::validate(p)?;
}
crate::lighting::validate(p)?;
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
{
let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect();
return Err(format!("bevel must be none or one of {}", names.join(", ")));
}
Ok(())
}
/// Validate before a command changes the document; the evaluator bounds loaded files too.
pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> {
validate_solid_params(id, p)?;
let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…'));
if is_container(n) {
let shapes = members(n, label)?;
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
@@ -273,6 +288,13 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) }
}
/// Are 3D effect `id`'s parameter values `p` valid? The checks of [`validate_three_d`] that do not
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
/// not need to fit.
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE { crate::revolve::validate_revolve_params(p) } else { validate_solid_params(id, p) }
}
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
/// blend mode (so overlapping facets don't add up their transparency).
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node {
@@ -384,7 +406,8 @@ fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile]) {
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let colored = view_options(&p).has_colored_lights();
let classic = fx.id == CLASSIC_EXTRUDE;
let colored = !classic && view_options(&p).has_colored_lights();
if fx.id == ROTATE {
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
@@ -432,7 +455,8 @@ fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>>
.map(|(item, member, f)| {
let depths: Vec<f64> = f.iter().map(|f| f.depth).collect();
let (paint, opacity, blend) = paint_of(item, member);
(depths, surface(n, f, &paint, opacity, blend, colored))
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
(depths, art)
})
.collect();
// One order takes a plain group of faces from each solid, one face for each facet. With
@@ -566,14 +590,15 @@ pub(crate) fn keep_mesh(out: &mut Vec<SolidMesh>, total: &mut usize, mesh: Solid
/// The solids effect `fx` builds from `shapes`, as [`art_for`] draws them, as meshes: Rotate turns
/// every fill and stroke; Extrude & Bevel and Inflate build one from each shape's top fill and one
/// from the outline of each stroke. A stroke whose solid is past the limits is left out.
fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize) -> Result<Vec<SolidMesh>, String> {
/// from the outline of each stroke. A stroke whose solid is past the limits is left out. Each mesh
/// is counted against `limit` ([`keep_mesh`]) before the next is built.
fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
let p = crate::merged_params(&fx.id, &fx.params);
let view = view_options(&p);
let mut out = vec![];
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, MAX_MESH_TRIANGLES);
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
if fx.id == ROTATE {
for s in shapes {
for item in &s.items {
@@ -585,8 +610,8 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize) -> Result<Vec<
return Ok(out);
}
let (parts, bounds) = solid_parts(shapes, b);
// Inflate lays out every puff at once (they share one eye); each mesh, and each Extrude &
// Bevel solid, is built as it is reached.
// Inflate lays out every puff at once (they share one eye); each Inflate and Extrude & Bevel
// solid and its mesh are built as the loop reaches them.
let mut inflated = (fx.id == INFLATE).then(|| {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule)| (area, *rule)).collect();
vectorcraft_three_d::inflate_meshes(&shapes, bounds, inflate_options(&p), view)
@@ -614,16 +639,33 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize) -> Result<Vec<
/// colors they are painted ([`SolidMesh`]), faces turned away from the viewer included; meshes
/// with no triangles are left out. On a group or layer, the effect's solids of its members
/// ([`members`]). The object's opacity multiplies every color's. An error when `n` carries no
/// such effect, its solids can't be built, or none has a triangle.
/// such effect, its solids can't be built, none has a triangle, or together they have more than
/// [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
// Triangles of every solid together, against [`MAX_MESH_TRIANGLES`].
meshes_within(n, &mut 0, MAX_MESH_TRIANGLES)
}
/// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports
/// them: the objects share one budget of [`MAX_MESH_TRIANGLES`].
pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Result<Vec<SolidMesh>, String> {
meshes_of_within(nodes, MAX_MESH_TRIANGLES)
}
/// [`three_d_meshes_of`] with a budget of `limit` triangles.
fn meshes_of_within<'a>(nodes: impl IntoIterator<Item = &'a Node>, limit: usize) -> Result<Vec<SolidMesh>, String> {
let mut total = 0usize;
let mut out = vec![];
for n in nodes {
out.extend(meshes_within(n, &mut total, limit)?);
}
Ok(out)
}
/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an
/// error as soon as `total` passes `limit`.
fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<SolidMesh>, String> {
let meshes = if crate::has_revolve(n) {
let mut out = vec![];
for m in crate::revolve::revolve_meshes(n)? {
keep_mesh(&mut out, &mut total, m, MAX_MESH_TRIANGLES)?;
}
out
crate::revolve::revolve_meshes(n, total, limit)?
} else if !has_solid(n) {
return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into());
} else if is_container(n) {
@@ -631,21 +673,21 @@ pub fn three_d_meshes(n: &Node) -> Result<Vec<SolidMesh>, String> {
let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…'));
let mut shapes = members(n, label)?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
meshes_for(fx, &shapes, &mut total)?
meshes_for(fx, &shapes, total, limit)?
} else {
let (path, rule) = profile(n).ok_or("3D export needs a path, compound path, type or group")?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], &mut total)?
meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0 }], total, limit)?
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], &mut total)?);
out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0 }], total, limit)?);
}
}
out
+220
View File
@@ -0,0 +1,220 @@
//! Extrude & Bevel (Classic): the solid Extrude & Bevel builds from a path, drawn with the classic
//! surfaces (Wireframe, No Shading, Diffuse and Plastic), their highlight, blend steps and shading
//! color.
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, StrokeLayer};
use vectorcraft_geom::Rect;
use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light};
use crate::util::{flag, num, text};
pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude";
/// 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 surface settings of Extrude & Bevel (Classic)'s parameters.
pub fn classic_shading(p: &Value) -> ClassicShading {
let d = ClassicShading::default();
ClassicShading {
surface: ClassicSurface::parse(text(p, "surface", "plastic")).unwrap_or_default(),
ambient: num(p, "ambient", d.ambient * 100.0) / 100.0,
highlight_intensity: num(p, "highlightIntensity", d.highlight_intensity * 100.0) / 100.0,
highlight_size: num(p, "highlightSize", d.highlight_size * 100.0) / 100.0,
blend_steps: num(p, "blendSteps", f64::from(d.blend_steps)).round().clamp(1.0, 256.0) as u32,
}
}
/// The solid of Extrude & Bevel (Classic)'s parameters: its depth, cap and bevel (as tall as it is
/// wide, added around the shape or carved into it), with the faces turned away from the viewer kept
/// for Draw Hidden Faces and for the Wireframe surface.
pub fn classic_extrude_options(p: &Value) -> Extrude {
let height = num(p, "bevelHeight", 4.0);
Extrude {
depth: num(p, "depth", 50.0),
cap: flag(p, "cap", true),
bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel {
shape,
width: height,
height,
inside: flag(p, "bevelInside", false),
..Bevel::default()
}),
hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe,
..Extrude::default()
}
}
/// The color faces darken toward: black, 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,
"custom" => Some(p.get("shadingCustom").and_then(Value::as_str).and_then(parse_hex).unwrap_or(Color::BLACK)),
_ => Some(Color::BLACK),
}
}
fn parse_hex(s: &str) -> Option<Color> {
(s.len() == 7 && s.starts_with('#') && s.bytes().skip(1).all(|b| b.is_ascii_hexdigit())).then(|| Color::from_hex(s)).flatten()
}
/// The lights: the `lights` list when it is given, else the one light of `lightRotation`,
/// `lightHeight`, `lightBehind` and `lightIntensity`. Each is its direction toward the light in view
/// space and its intensity (0..1).
fn lights(p: &Value) -> Vec<([f64; 3], f64)> {
if let Some(list) = crate::lighting::lights(p) {
return list.iter().map(|l| (l.direction(), l.intensity)).collect();
}
let light = Light {
rotation: num(p, "lightRotation", vectorcraft_three_d::DEFAULT_LIGHT.0),
height: num(p, "lightHeight", vectorcraft_three_d::DEFAULT_LIGHT.1),
behind: flag(p, "lightBehind", false),
..Light::default()
};
vec![(light.direction(), num(p, "lightIntensity", 100.0) / 100.0)]
}
/// The numeric parameters: (key, lowest, highest, whole numbers only).
const RANGES: [(&str, f64, f64, bool); 13] = [
("depth", 0.0, 2000.0, false),
("bevelHeight", 1.0, 100.0, false),
("rotationX", -180.0, 180.0, false),
("rotationY", -180.0, 180.0, false),
("rotationZ", -180.0, 180.0, false),
("perspectiveAngle", 0.0, 160.0, false),
("lightRotation", -180.0, 180.0, false),
("lightHeight", 0.0, 90.0, false),
("lightIntensity", 0.0, 100.0, false),
("ambient", 0.0, 100.0, false),
("highlightIntensity", 0.0, 100.0, false),
("highlightSize", 0.0, 100.0, false),
("blendSteps", 1.0, 256.0, true),
];
const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"];
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
/// `shadingCustom` name a surface, a shading color and a #rrggbb color.
pub fn validate(p: &Value) -> Result<(), String> {
let Some(map) = p.as_object() else { return Ok(()) };
let defaults = crate::default_params(CLASSIC_EXTRUDE).unwrap_or(Value::Null);
let known: Vec<&str> = defaults.as_object().map(|m| m.keys().map(String::as_str).collect()).unwrap_or_default();
for key in map.keys() {
if !known.contains(&key.as_str()) {
let keys = known.join(", ");
return Err(format!("unknown parameter `{key}`; the command takes: {keys}"));
}
}
for (key, min, max, whole) in RANGES {
let Some(v) = map.get(key) else { continue };
let Some(x) = v.as_f64() else { return Err(format!("`{key}` must be a number")) };
if whole && (x.fract() != 0.0 || !(min..=max).contains(&x)) {
return Err(format!("`{key}` must be a whole number between {min} and {max} (got {x})"));
}
if !(min..=max).contains(&x) {
return Err(format!("`{key}` must be between {min} and {max} (got {x})"));
}
}
for key in FLAGS {
if map.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(format!("`{key}` must be true or false"));
}
}
let one_of = |key: &str, ids: &[&str]| -> Result<(), String> {
match map.get(key) {
Some(v) if !v.as_str().is_some_and(|s| ids.contains(&s)) => Err(format!("`{key}` must be one of {}", ids.join(", "))),
_ => Ok(()),
}
};
let surfaces: Vec<&str> = ClassicSurface::ALL.iter().map(|s| s.id()).collect();
one_of("surface", &surfaces)?;
one_of("shadingColor", &SHADING_COLORS)?;
let key = "shadingCustom";
if map.get(key).is_some_and(|v| !v.as_str().is_some_and(|s| parse_hex(s).is_some())) {
return Err(format!("`{key}` must be a #rrggbb color"));
}
Ok(())
}
/// `c` with tone `tone` (0 the shading color, 1 the color itself) and highlight `spec` (toward
/// white) on top.
fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
let base = c.to_rgb();
let dark = shade.map_or(base, |s| s.to_rgb());
let (tone, spec) = (tone as f32, spec as f32);
let [r, g, b] = [0, 1, 2].map(|i| {
let mixed = dark[i] + (base[i] - dark[i]) * tone;
(mixed + (1.0 - mixed) * spec).clamp(0.0, 1.0)
});
Color::rgb(r, g, b)
}
/// 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. A gradient with transparent stops is shaded opaque and then masked by
/// its own transparency, so the shading follows the gradient's coverage.
pub(super) 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 wire = shading.surface == ClassicSurface::Wireframe;
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
let paint = &paint;
let children = facets
.into_iter()
.map(|face| {
if wire {
let mut edge = StrokeLayer::new(paint.clone(), WIRE);
edge.join = vectorcraft_doc::LineJoin::Round;
return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() }));
}
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 = (face.thickness() / 2.0).clamp(0.05, 0.75);
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.
Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => {
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))]
}
Some(c) => {
let fill = Paint::solid(shaded(c, tone, spec, shade));
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(StrokeLayer::new(fill, seam))]
}
// Gradients and patterns keep their paint, darkened by a layer of the shading color
// and lightened by one of white. As with the other 3D effects' pattern shadow, the
// layers cover the whole face, transparent pattern cells included.
None => {
let mut items =
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(StrokeLayer::new(paint.clone(), seam))];
for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] {
if let Some(color) = color.filter(|_| share > 0.0) {
let mut layer = FillLayer::new(Paint::solid(color));
layer.opacity = share as f32;
items.push(AppearanceItem::Fill(layer));
}
}
items
}
};
Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() }))
})
.collect();
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
if let Some(mask) = mask {
let bounds = group.visual_bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0));
group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true)));
}
group
}
+166 -4
View File
@@ -45,10 +45,15 @@ fn every_solid_draws_shaded_faces_and_leaves_the_source_editable() {
assert_eq!(n.path_data(), Some(&source), "{id}");
assert!(!faces(&art).is_empty(), "{id}");
// The faces are the fill's red or the stroke's black, shaded: never brighter, never another
// hue.
// hue. The classic Plastic surface, its default, also lightens a face toward white, which
// scales every channel's distance from white by the same factor and so keeps r - g to
// r - b at 6 to 7.
for f in faces(&art) {
let [r, g, b] = fill_rgb(f);
assert!(r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE, "{id}: {r} {g} {b}");
let shaded = r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4;
let highlighted =
id == CLASSIC_EXTRUDE && [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) && ((r - g) * 7.0 - (r - b) * 6.0).abs() < 1e-4;
assert!(shaded || highlighted || id == ROTATE, "{id}: {r} {g} {b}");
}
// The art follows the source when it moves.
let before = art.visual_bounds().unwrap();
@@ -325,7 +330,7 @@ fn export_and_expand_bake_faces_with_their_own_ids() {
let mut n = square_node();
n.id = d.alloc_id();
n.appearance.effects.push(fx(id, json!({"bevel": "rounded"})));
assert_eq!(crate::bake_appearance(&n), solid_art(&n), "{id}");
assert_eq!(crate::bake_appearance(None, &n), solid_art(&n), "{id}");
let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None;
let art = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap();
let mut ids = std::collections::HashSet::new();
@@ -351,7 +356,7 @@ fn a_twisted_tapered_hollow_inflate_exports_and_expands() {
let params = json!({"twist": 120, "taper": 50, "cap": false, "bothSides": true, "rotationX": -20, "rotationY": 35});
n.appearance.effects.push(fx(INFLATE, params));
let art = solid_art(&n).unwrap();
assert_eq!(crate::bake_appearance(&n), Some(art.clone()));
assert_eq!(crate::bake_appearance(None, &n), Some(art.clone()));
assert!(faces(&art).len() > 20, "{} faces", faces(&art).len());
let mut stroke = |_: &mut Document, _: &PathData, _: FillRule, _: &StrokeLayer| None;
let expanded = crate::expand_leaf(&mut d, &n, &mut stroke).unwrap();
@@ -595,3 +600,160 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() {
assert!(err.contains("clipping groups"), "{err}");
assert!(solid_art(&g).is_none(), "drawn as the group it is");
}
/// The red square without its stroke, with Extrude & Bevel (Classic) and `params`.
fn classic(params: Value) -> Node {
let mut n = square_node();
n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_)));
n.appearance.effects.push(fx(CLASSIC_EXTRUDE, params));
n
}
fn classic_faces(params: Value) -> Vec<Node> {
let art = solid_art(&classic(params)).unwrap();
faces(&art).into_iter().cloned().collect()
}
fn close3(a: [f32; 3], b: [f32; 3]) -> bool {
a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-4)
}
#[test]
fn classic_surfaces_draw_edges_flat_paint_soft_light_and_a_highlight() {
// Wireframe: the edges of every face, the hidden ones too, in the paint; no fills.
let wire = classic_faces(json!({"surface": "wireframe"}));
let plastic = classic_faces(json!({}));
assert_eq!(plastic.len(), 3, "a box shows three faces");
assert_eq!(wire.len(), 6, "and has six");
for f in &wire {
let [AppearanceItem::Stroke(s)] = &f.appearance.items[..] else { panic!("a stroke alone: {:?}", f.appearance.items) };
assert_eq!(s.paint, Paint::solid(RED));
}
// No Shading: every face in the art's own paint, a CMYK color kept as it is.
assert!(classic_faces(json!({"surface": "none"})).iter().all(|f| close3(fill_rgb(f), RED.to_rgb())));
let cmyk = Paint::solid(Color::Cmyk { c: 0.1, m: 0.9, y: 0.8, k: 0.0 });
let mut n = classic(json!({"surface": "none"}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = cmyk.clone();
}
for f in faces(&solid_art(&n).unwrap()) {
let AppearanceItem::Fill(fill) = &f.appearance.items[0] else { panic!("a fill first") };
assert_eq!(fill.paint, cmyk);
}
// Diffuse: the red darkened toward black by how far each face turns from the light, so the
// faces differ but keep their hue.
let diffuse: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse"})).iter().map(fill_rgb).collect();
assert!(diffuse.iter().all(|[r, g, b]| *r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4), "{diffuse:?}");
assert!(diffuse.windows(2).any(|w| !close3(w[0], w[1])), "{diffuse:?}");
// Plastic: the same faces, one of them lightened toward white by the highlight.
let shiny: Vec<[f32; 3]> =
classic_faces(json!({"highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60})).iter().map(fill_rgb).collect();
let soft: Vec<[f32; 3]> = classic_faces(json!({"surface": "diffuse", "lightHeight": 60})).iter().map(fill_rgb).collect();
assert!(shiny.iter().zip(&soft).any(|(s, d)| s[1] > d[1] + 0.01), "{shiny:?} {soft:?}");
assert!(shiny.iter().zip(&soft).all(|(s, d)| s[1] >= d[1] - 1e-4));
// Without highlight, Plastic shades as Diffuse.
let dull: Vec<[f32; 3]> = classic_faces(json!({"highlightIntensity": 0, "lightHeight": 60})).iter().map(fill_rgb).collect();
assert!(dull.iter().zip(&soft).all(|(a, b)| close3(*a, *b)));
}
#[test]
fn classic_shading_color_blend_steps_and_lights() {
let base = json!({"surface": "diffuse", "ambient": 20});
let with = |extra: Value| {
let mut p = base.clone();
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
classic_faces(p).iter().map(fill_rgb).collect::<Vec<_>>()
};
// A custom shading color darkens toward that color; None keeps the paint.
assert!(with(json!({"shadingColor": "custom", "shadingCustom": "#0000ff"})).iter().any(|c| c[2] > c[0] / 8.0 + 0.01));
assert!(with(json!({"shadingColor": "none"})).iter().all(|c| close3(*c, RED.to_rgb())));
// One blend step: every face fully lit or fully in shadow.
let stepped = with(json!({"blendSteps": 1, "ambient": 0}));
assert!(stepped.iter().all(|c| close3(*c, RED.to_rgb()) || close3(*c, [0.0; 3])), "{stepped:?}");
// No light: the ambient share of the red. Two lights add up.
let dark = with(json!({"lightIntensity": 0, "blendSteps": 256}));
assert!(dark.iter().all(|c| (c[0] - 0.8 * 0.2).abs() < 0.01), "{dark:?}");
let one = with(json!({"lights": [{"intensity": 30}], "blendSteps": 256}));
let two = with(json!({"lights": [{"intensity": 30}, {"intensity": 30}], "blendSteps": 256}));
assert!(one.iter().zip(&two).all(|(a, b)| b[0] >= a[0] - 1e-4) && one.iter().zip(&two).any(|(a, b)| b[0] > a[0] + 0.01));
// Draw Hidden Faces keeps the faces turned away, drawn first.
assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6);
}
#[test]
fn classic_bevel_height_extent_and_cap_shape_the_solid() {
let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap();
let front = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "bevel": "classic", "bevelHeight": 10});
let out = bounds(front.clone());
let mut inside = front.clone();
inside["bevelInside"] = json!(true);
// Straight on, a bevel added around the shape widens it; one carved into it keeps its size.
assert!(out.width() > 100.0 + 15.0, "{out:?}");
let carved = bounds(inside);
assert!((carved.width() - 100.0).abs() < 2.0, "{carved:?}");
// Hollow: no caps, so the walls seen from inside show too.
assert!(classic_faces(json!({"cap": false})).len() > classic_faces(json!({})).len());
// The depth sets how far back the solid goes.
let side = json!({"rotationX": 0, "rotationY": 90, "rotationZ": 0});
let mut deep = side.clone();
deep["depth"] = json!(120);
assert!((bounds(deep).width() - 120.0).abs() < 1.0);
}
/// A gradient fill with a transparent stop is shaded opaque and masked by its own transparency, so
/// the shading does not cover the transparent part; an opaque gradient needs no mask.
#[test]
fn classic_shading_keeps_a_gradients_transparency() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
for (end, masked) in [(0.25, true), (1.0, false)] {
let mut stop = GradientStop::new(1.0, RED);
stop.opacity = end;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, RED), stop]));
let mut n = classic(json!({}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let art = solid_art(&n).unwrap();
let surface = &art.children().unwrap()[0];
assert_eq!(surface.extras().mask.is_some(), masked, "{end}");
let mut opaque = true;
surface.walk(&mut |c| {
for item in &c.appearance.items {
if let AppearanceItem::Fill(f) = item
&& let Paint::Gradient(g) = &f.paint
{
opaque &= g.gradient.stops.iter().all(|s| s.opacity == 1.0);
}
}
});
assert!(opaque, "{end}: the faces are drawn opaque");
}
}
#[test]
fn classic_parameters_are_checked() {
let n = classic(json!({}));
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());
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!({"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)"),
(json!({"bevelHeight": 0}), "`bevelHeight` must be between 1 and 100 (got 0)"),
(json!({"ambient": -1}), "`ambient` must be between 0 and 100 (got -1)"),
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number between 1 and 256 (got 2.5)"),
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
(json!({"highlightSize": "big"}), "`highlightSize` must be a number"),
(json!({"cap": "yes"}), "`cap` must be true or false"),
(json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"),
(json!({"bevel": "fancy"}), "bevel must be none or one of"),
(json!({"twist": 10}), "unknown parameter `twist`"),
(json!({"lights": []}), "lights must contain one to ten lights"),
] {
let err = check(p.clone()).unwrap_err();
assert!(err.starts_with(says), "{p}: {err}");
}
}
+42 -2
View File
@@ -54,9 +54,49 @@ fn the_meshes_of_one_object_share_one_triangle_budget() {
let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0 }];
let Some(effect) = n.appearance.effects.first() else { panic!("no effect") };
let mut total = 0;
assert!(meshes_for(effect, &shapes, &mut total).is_ok());
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok());
let mut total = MAX_MESH_TRIANGLES - first + 1;
assert!(meshes_for(effect, &shapes, &mut total).is_err_and(|e| e.contains("too complex")));
assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex")));
}
#[test]
fn revolve_stops_at_the_first_mesh_past_the_budget() {
// The fill revolves into a mesh; the stroke's profile, copied 1000 times, is too complex to
// revolve at all.
let mut n = square_node(1, 100.0);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.get_mut(0) {
f.effects.push(fx(crate::REVOLVE, json!({})));
}
let fill_only = n.clone();
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
s.effects.push(fx("distort.transform", json!({ "moveH": 1.0, "copies": 1000 })));
s.effects.push(fx(crate::REVOLVE, json!({})));
}
let fill = three_d_meshes(&fill_only).unwrap();
let triangles = fill[0].mesh.triangles.len();
assert!(triangles > 1);
let whole = three_d_meshes(&n);
assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}");
// With room for less than the fill's mesh, the stroke's is never built.
let mut total = 0;
let capped = meshes_within(&n, &mut total, triangles - 1);
assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}");
assert_eq!(total, triangles);
}
#[test]
fn the_objects_of_one_asset_share_one_triangle_budget() {
let mut a = square_node(1, 0.0);
a.appearance.effects.push(fx(EXTRUDE, json!({})));
let mut b = square_node(2, 300.0);
b.appearance.effects.push(fx(EXTRUDE, json!({})));
let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
let (ta, tb) = (triangles(&a), triangles(&b));
assert!(meshes_of_within([&a], ta).is_ok());
assert!(meshes_of_within([&b], tb).is_ok());
assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export")));
assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4));
assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4));
}
#[test]
+60 -13
View File
@@ -57,16 +57,27 @@ fn numbers(v: &str) -> Option<Vec<f64>> {
/// Filter `xml` as it is drawn and written ([`rebuilt`]) when it passes [`check`], `None` when it
/// doesn't. Remembered for the filters seen last, so drawing does not check a filter again each time.
fn checked(xml: &str) -> Option<Arc<str>> {
use std::hash::BuildHasher;
type Seen = (std::collections::hash_map::RandomState, std::collections::HashMap<(u64, usize), Option<Arc<str>>>, usize);
static SEEN: std::sync::OnceLock<std::sync::Mutex<Seen>> = std::sync::OnceLock::new();
let seen = SEEN.get_or_init(Default::default);
remembered(&SEEN, xml, |xml| checked_form(xml).ok().map(|(_, form)| Arc::from(form)))
}
/// The results [`remembered`] keeps: the hash's seed, the results by key, and their size in bytes.
type Seen = (std::collections::hash_map::RandomState, std::collections::HashMap<(u64, usize), Option<Arc<str>>>, usize);
/// `make(xml)`, remembered in `seen` for the filters seen last.
fn remembered(
seen: &'static std::sync::OnceLock<std::sync::Mutex<Seen>>,
xml: &str,
make: impl FnOnce(&str) -> Option<Arc<str>>,
) -> Option<Arc<str>> {
use std::hash::BuildHasher;
let seen = seen.get_or_init(Default::default);
// Keyed by a hash that a file can't aim at (randomly seeded) and the length.
let key = seen.lock().ok().map(|s| (s.0.hash_one(xml), xml.len()));
if let Some(hit) = key.and_then(|k| seen.lock().ok().and_then(|s| s.1.get(&k).cloned())) {
return hit;
}
let form: Option<Arc<str>> = checked_form(xml).ok().map(|(_, form)| Arc::from(form));
let form = make(xml);
if let (Some(k), Ok(mut s)) = (key, seen.lock())
&& !s.1.contains_key(&k)
{
@@ -83,7 +94,7 @@ fn checked(xml: &str) -> Option<Arc<str>> {
form
}
/// The most check results [`checked`] keeps, and the most bytes of filters it keeps.
/// The most results [`remembered`] keeps in one place, and the most bytes of filters it keeps there.
const MAX_CHECKED: usize = 65_536;
const MAX_CHECKED_BYTES: usize = 32 << 20;
@@ -279,9 +290,30 @@ const LATER_BLEND_MODES: [&str; 11] =
/// The `feComposite` operators of SVG 1.1.
const SVG11_OPERATORS: [&str; 6] = ["over", "in", "out", "atop", "xor", "arithmetic"];
/// The longest form SVG output writes ([`svg11`]), leaving room within [`MAX_DRAWN_XML`] for the
/// region and id written into it.
const MAX_WRITTEN_XML: usize = MAX_DRAWN_XML - 1024;
/// The longest id SVG output gives a filter it writes: a unique-id prefix of up to 13 characters,
/// `filter-` and a counter of up to 20 digits, with room to spare.
const WRITTEN_ID_ROOM: usize = 64;
/// The longest text `{}` writes for a finite `f64`: a sign, `0.`, 307 zeros and 17 digits, as for
/// `-f64::MIN_POSITIVE`.
const MAX_NUMBER_TEXT: usize = 327;
/// The most the four region attributes written into a filter ([`SvgFilterFx::written_xml`]) add to
/// it: each of `x`, `y`, `width` and `height` as ` height="…"` with the longest number.
const REGION_ROOM: usize = 4 * (" height=\"\"".len() + MAX_NUMBER_TEXT);
/// The longest form SVG output writes ([`svg11`]): room is left within [`SvgFilter::MAX_XML`], the
/// longest filter SVG import reads, for the id written into it. Measured with [`written_len`].
const MAX_WRITTEN_XML: usize = SvgFilter::MAX_XML - WRITTEN_ID_ROOM;
/// How long `s` is as SVG output can write it and import reads it back: SVG output with the Latin-1
/// encoding writes each character past U+00FF as `&#x…;`, which import keeps as text, so the
/// longer of the two lengths is counted for each such character.
fn written_len(s: &str) -> usize {
// `&#x`, one hex digit per four significant bits, and `;`.
let reference = |c: u32| 4 + ((u32::BITS - c.leading_zeros()) as usize).div_ceil(4);
s.chars().map(|c| if u32::from(c) < 0x100 { c.len_utf8() } else { reference(u32::from(c)) }).sum()
}
/// Filter `xml` (a rebuilt one, [`rebuilt`]) as SVG 1.1 output writes it, in the form an SVG 1.1
/// viewer draws as resvg draws `xml`:
@@ -413,7 +445,7 @@ fn svg11(xml: &str) -> Option<String> {
}
out.push_str("</filter>");
}
(out.len() <= MAX_WRITTEN_XML).then_some(out)
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
}
/// The result names of a filter's SVG 1.1 form ([`svg11`]): the names its elements use, and the
@@ -1278,13 +1310,28 @@ impl SvgFilterFx {
/// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1
/// can't hold it ([`Self::writes_as_svg11`]).
pub fn written_xml(&self, bounds: Rect) -> Option<String> {
self.with_region(&svg11(&self.xml)?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))
let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?;
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
}
/// Can SVG 1.1 output write the filter as a `<filter>` element ([`svg11`])? When it can't, SVG
/// output treats it as it treats the other pixel effects.
/// Can SVG 1.1 output write the filter as a `<filter>` element ([`svg11`]) that SVG import
/// reads back? When it can't, SVG output treats it as it treats the other pixel effects.
pub fn writes_as_svg11(&self) -> bool {
svg11(&self.xml).is_some()
self.svg11_form().is_some()
}
/// The filter's SVG 1.1 form ([`svg11`]) when, with any region and id that SVG output writes
/// into it, it is a filter SVG import reads ([`check`]): at most [`SvgFilter::MAX_XML`] bytes,
/// [`MAX_PRIMITIVES`] primitives and [`MAX_DEPTH`] levels deep, and drawn. Remembered for the
/// filters seen last, so export does not check a filter again for each object.
fn svg11_form(&self) -> Option<Arc<str>> {
static FORMS: std::sync::OnceLock<std::sync::Mutex<Seen>> = std::sync::OnceLock::new();
// `measured` follows from the XML, so the XML is the whole key.
let region = if self.measured { REGION_ROOM } else { 0 };
remembered(&FORMS, &self.xml, |xml| {
let form = svg11(xml)?;
(written_len(&form) + region <= MAX_WRITTEN_XML && check(&form).is_ok()).then(|| Arc::from(form))
})
}
/// How finely the filter runs on a raster whose pixels are `space.px` points wide, for an
+42 -3
View File
@@ -457,9 +457,48 @@ fn a_filter_at_the_size_limit_draws_with_its_measured_region() {
assert_eq!(xml.len(), SvgFilter::MAX_XML);
assert_eq!(check(&xml), Ok("r".into()));
let f = filter(json!({ "xml": xml }));
let written = f.written_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap();
assert!(written.len() > SvgFilter::MAX_XML, "the region written out is longer: {} bytes", written.len());
assert!(with_id(&written, DRAWN_ID).is_some(), "the drawn form is read");
let drawn = f.drawn_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap();
assert!(drawn.len() > SvgFilter::MAX_XML, "the region written out is longer: {} bytes", drawn.len());
assert!(with_id(&drawn, DRAWN_ID).is_some(), "the drawn form is read");
}
/// SVG output writes a filter live only when the form it writes, with its region and id, is one
/// SVG import reads back: at most [`SvgFilter::MAX_XML`] bytes. A filter at the limit whose region
/// is measured against the box, one at the limit whose id is a character long, and one whose
/// shadows make its SVG 1.1 form longer are left to be written as other pixel effects are.
#[test]
fn svg_output_writes_a_filter_only_in_a_form_import_reads() {
let at_limit = |open: &str, close: &str| {
let xml = format!("{open}{}{close}", "a".repeat(SvgFilter::MAX_XML - open.len() - close.len()));
assert_eq!((xml.len(), check(&xml).is_ok()), (SvgFilter::MAX_XML, true));
filter(json!({ "xml": xml }))
};
let measured = at_limit(
r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#,
r#""/><feOffset/></filter>"#,
);
let short_id = at_limit(r#"<filter id="r"><feOffset result=""#, r#""/><feOffset/></filter>"#);
let shadows = format!(r#"<filter id="s">{}<feOffset result="{}"/></filter>"#, "<feDropShadow/>".repeat(12), "a".repeat(SvgFilter::MAX_XML - 400));
assert!(check(&shadows).is_ok() && shadows.len() <= SvgFilter::MAX_XML);
for f in [measured, short_id, filter(json!({ "xml": shadows }))] {
assert!(!f.writes_as_svg11() && f.written_xml(Rect::new(0.0, 0.0, 10.0, 10.0)).is_none(), "{} bytes", f.xml().len());
}
// Room for the id and the longest region: still written, and read back.
let open = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-1%" y="-1%" width="1%" height="1%"><feOffset result=""#;
let close = r#""/><feOffset/></filter>"#;
let xml = format!("{open}{}{close}", "a".repeat(MAX_WRITTEN_XML - REGION_ROOM - open.len() - close.len()));
let f = filter(json!({ "xml": xml }));
assert!(f.writes_as_svg11());
let id = format!("u_vc_unique_-filter-{}", usize::MAX);
let out = with_id(&f.written_xml(Rect::new(0.123456789, 0.123456789, 1000.987654321, 1000.987654321)).unwrap(), &id).unwrap();
assert!(out.len() <= SvgFilter::MAX_XML && check(&out).is_ok(), "{} bytes", out.len());
// The longest numbers a region can take still fit.
let far = f.written_xml(Rect::new(-f64::MIN_POSITIVE, -f64::MIN_POSITIVE, f64::MAX / 4.0, f64::MAX / 4.0)).unwrap();
assert!(with_id(&far, &id).is_some_and(|out| out.len() <= SvgFilter::MAX_XML));
for v in [-f64::MIN_POSITIVE, -5e-324, -2.225073858507201e-308, f64::MIN, -1.0 / 3.0] {
assert!(format!("{v}").len() <= MAX_NUMBER_TEXT, "{v:e}");
}
assert_eq!(format!("{}", -f64::MIN_POSITIVE).len(), MAX_NUMBER_TEXT);
}
/// Only a type selector naming a filter or one of its elements, or `*`, lets a style sheet reach
+112 -8
View File
@@ -180,6 +180,24 @@ fn warp_zero_bend_is_identity_ish() {
}
}
/// `warp::bends` says a warp moves placed gradients exactly when the warp moves the outline:
/// Arc leaves the outline as it is under a bend of 0.0001 % and moves it above that, and the other
/// styles move it at any bend.
#[test]
fn warp_bends_when_the_warp_moves_the_outline() {
// A star: Fisheye moves nothing on the edge of the box, where an ellipse or a rectangle lies.
let oval = shapes::star(Point::new(51.7, 34.3), 40.9, 17.3, 5, 7.0);
for (s, _) in WARP_STYLES {
let id = format!("warp.{s}");
let flat = run(&id, json!({"bend": 0}), &oval);
for bend in [0.0, 1e-5, -1e-5, 0.9e-4, -0.9e-4, 1.1e-4, -1.1e-4] {
let p = json!({ "bend": bend });
let moved = run(&id, p.clone(), &oval) != flat;
assert_eq!(crate::warp::bends(&id, &p), moved, "{id} at {bend} %");
}
}
}
#[test]
fn warp_arc_bends_the_top_edge() {
let out = run("warp.arc", json!({"bend": 50}), &square());
@@ -394,7 +412,7 @@ fn stacked_effects_on_art_stay_within_the_anchor_budget() {
let leaf = |x: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0)), Appearance::default()));
let mut art = Node::group(id, (0..10).map(|k| leaf(k as f64 * 120.0)).collect());
let rough = fx("distort.roughen", json!({"size": 50, "detail": 100}));
crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX });
crate::reshape::reshape_leaves_within(&mut art, &[&rough, &rough, &rough], Budget { anchors: 5_000, lines: usize::MAX }, None);
let mut total = 0;
let mut reshaped = 0;
for c in art.children().into_iter().flatten() {
@@ -433,12 +451,12 @@ fn art_past_the_budget_keeps_its_own_gradients_in_place() {
for params in [json!({"scaleH": 1000, "scaleV": 1000}), json!({"scaleH": 1000, "scaleV": 1000, "strokes": true})] {
let grow = fx("distort.transform", params.clone());
let mut art = Node::group(id, vec![circle()]);
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget::EFFECTS);
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget::EFFECTS, None);
let end = own_end(&carry).unwrap();
assert!((end - 550.0).abs() < 1e-6, "{params}: within the budget the group's gradient grows with the circle: {end}");
// No room beyond what the circle costs: scaled up, it would be drawn with more lines.
let mut art = Node::group(id, vec![circle()]);
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 });
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }, None);
let b = art.geometric_bounds().unwrap();
assert!(b.width() < 101.0 && b.height() < 101.0, "{params}: the circle keeps its shape: {b:?}");
assert_eq!(own_end(&carry), Some(100.0), "{params}: the group's gradient stays where it was placed");
@@ -447,7 +465,7 @@ fn art_past_the_budget_keeps_its_own_gradients_in_place() {
let mut inner = Node::group(NodeId(2), vec![square]);
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
let mut art = Node::group(id, vec![circle(), Arc::new(inner)]);
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 });
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], Budget { anchors: usize::MAX, lines: 0 }, None);
assert_eq!(own_end(&carry), Some(100.0), "{params}: the art's own gradient stays");
let inner = &art.children().unwrap()[1];
let Paint::Gradient(g) = inner.appearance.fill_paint() else { panic!("a gradient") };
@@ -455,6 +473,92 @@ fn art_past_the_budget_keeps_its_own_gradients_in_place() {
}
}
/// A hidden path in a layer that keeps its shape past the budget does not hold the layer's
/// gradients in place: the layer's bounds leave it out, so the layer's own gradient moves with
/// the visible art under a Transform effect and Free Distort, as does the art's when the layer is
/// the art.
#[test]
fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
use std::sync::Arc;
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint};
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
let end = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.geom.map(|g| g.end.x),
_ => None,
};
// A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own.
let layer = || {
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
let mut circle = Node::path(NodeId(4), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default());
circle.visible = false;
let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
*children = vec![square, Arc::new(circle)];
}
layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
layer
};
// No room beyond what the paths cost: the square takes each effect, the circle would be drawn
// with more lines and keeps its shape.
let budget = Budget { anchors: usize::MAX, lines: 0 };
// Each scales the art ten times about its center: 0..100 becomes -450..550.
let corners = json!({"corners": [[-4.5, -4.5], [5.5, -4.5], [5.5, 5.5], [-4.5, 5.5]]});
for grow in [fx("distort.transform", json!({"scaleH": 1000, "scaleV": 1000})), fx("distort.freeDistort", corners)] {
let mut art = layer();
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget, None);
let circle = art.children().unwrap()[1].geometric_bounds().unwrap();
assert!(circle.width() < 101.0, "{}: the hidden circle keeps its shape: {circle:?}", grow.id);
let square = art.children().unwrap()[0].geometric_bounds().unwrap();
assert!((square.x1 - 550.0).abs() < 1e-6, "{}: the square takes the effect: {square:?}", grow.id);
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert_eq!(end(&own), Some(550.0), "{}: the layer's gradient, as the art", grow.id);
let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]);
crate::reshape::reshape_leaves_within(&mut art, &[&grow], budget, None);
assert_eq!(end(&art.children().unwrap()[0].appearance), Some(550.0), "{}: the layer's gradient, inside the art", grow.id);
}
}
/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its
/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the
/// art itself, as a placed gradient does.
#[test]
fn edited_freeform_points_follow_a_transform_effect_and_free_distort() {
use std::sync::Arc;
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() });
let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c);
ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() });
assert!(ramp.geom.is_none() && !ramp.is_placed());
let freeform = Paint::Gradient(Box::new(ramp));
let xs = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at.x).collect::<Vec<_>>()),
_ => None,
};
let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap));
// Each moves the art 30 pt right.
let corners = json!({"corners": [[0.3, 0.0], [1.3, 0.0], [1.3, 1.0], [0.3, 1.0]]});
for e in [fx("distort.transform", json!({"moveH": 30})), fx("distort.freeDistort", corners)] {
let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]);
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]);
art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None);
let members = art.children().unwrap();
assert_eq!(xs(&members[0].appearance), Some(vec![30.0, 130.0]), "{}: the path's points", e.id);
assert_eq!(xs(&members[1].appearance), Some(vec![30.0, 130.0]), "{}: the inner group's points", e.id);
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert_eq!(xs(&own), Some(vec![30.0, 130.0]), "{}: the art's own points", e.id);
}
}
/// #3578: a large Roughen draws each of its points as many lines; they stay within the budget,
/// the Roughen built again with fewer points where they wouldn't.
#[test]
@@ -521,7 +625,7 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
let start = std::time::Instant::now();
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS);
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None);
let elapsed = start.elapsed();
assert!(elapsed < std::time::Duration::from_secs(2));
@@ -548,7 +652,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
let mut art_evenodd = Node::group(id, vec![Arc::new(leaf)]);
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 2}));
let offset = fx("path.offsetPath", json!({"offset": 4.0}));
crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS);
crate::reshape::reshape_leaves_within(&mut art_evenodd, &[&transform, &offset], Budget::EFFECTS, None);
let p = art_evenodd.children().unwrap()[0].path_data().unwrap();
assert_eq!(p.subpaths.len(), 1, "EvenOdd does not swap; copies union into 1 outer subpath");
@@ -556,7 +660,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
let leaf_round = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
let mut art_round = Node::group(id, vec![leaf_round]);
let round_corners = fx("stylize.roundCorners", json!({"radius": 2.0}));
crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS);
crate::reshape::reshape_leaves_within(&mut art_round, &[&transform, &offset, &round_corners], Budget::EFFECTS, None);
let p = art_round.children().unwrap()[0].path_data().unwrap();
assert_eq!(p.subpaths.len(), 1, "Non-terminal Offset Path does not swap; copies union into 1 outer subpath");
@@ -564,7 +668,7 @@ fn reshape_leaves_within_preserves_order_when_not_terminal_or_not_style_safe() {
let leaf_miter = Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default()));
let mut art_miter = Node::group(id, vec![leaf_miter]);
let offset_miter = fx("path.offsetPath", json!({"offset": 4.0, "joins": "miter"}));
crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS);
crate::reshape::reshape_leaves_within(&mut art_miter, &[&transform, &offset_miter], Budget::EFFECTS, None);
let p = art_miter.children().unwrap()[0].path_data().unwrap();
assert_eq!(p.subpaths.len(), 1, "Miter join does not swap; copies union into 1 outer subpath");
}
+11
View File
@@ -32,3 +32,14 @@ pub fn warp(path: &PathData, b: Rect, style: WarpStyle, p: &Value, max: usize) -
let piece = b.width().hypot(b.height()) / 24.0;
map_nonlinear_within(path, piece, max, f)
}
/// Does warp effect `id` with params `p` move any point? Every style leaves the box as it is with
/// no bend and no distortion, and Arc (`warp.arc`) takes a bend under 0.0001 % as none: the
/// threshold must match the one in [`warp_point`]'s Arc case (`warp_bends_when_the_warp_moves_the_outline`
/// tests both sides of it).
pub(crate) fn bends(id: &str, p: &Value) -> bool {
let share = |key: &str, default: f64| num(p, key, default).clamp(-100.0, 100.0) / 100.0;
let bend = share("bend", 50.0);
let bent = if id == "warp.arc" { bend.abs() >= 1e-6 } else { bend != 0.0 };
bent || share("horizontal", 0.0) != 0.0 || share("vertical", 0.0) != 0.0
}
+6
View File
@@ -40,6 +40,9 @@ vectorcraft-plugins = { workspace = true }
vectorcraft-affinity = { workspace = true }
vectorcraft-scriptcheck = { workspace = true }
image = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
jxl-grid = { workspace = true }
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
# Pure Rust, no unsafe; pinned at the version photocraft-heif uses.
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"], optional = true }
@@ -77,5 +80,8 @@ vectorcraft-pdf = { workspace = true, features = ["read-count"] }
wat = { workspace = true }
# Zstandard streams for the Illustrator editing data fuzz tests.
ruzstd = { workspace = true }
# JPEG XL files for the `.jxl` open and place tests.
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
# The JavaScript parser's lexer, compared with the script checker's on the same scripts.
vectorcraft-js = { workspace = true }
+28 -4
View File
@@ -12,6 +12,7 @@ pub mod clipboard;
mod colorcmds;
pub mod colormgmt;
pub mod colortheme;
pub mod compositefonts;
mod compoundshape;
pub(crate) mod create;
mod css;
@@ -286,6 +287,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(inline::specs());
v.extend(textstyles::specs());
v.extend(fonts::specs());
v.extend(compositefonts::specs());
v.extend(fontfiles::specs());
v.extend(help::specs());
v.extend(threads::specs());
@@ -354,8 +356,16 @@ pub fn command_specs() -> &'static [CommandSpec] {
})
}
/// The command `id`: a built-in one, or a command an installed plug-in adds
/// ([`plugin::command_specs`]).
pub fn find_command(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id))
}
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
/// ([`plugin::run_command`]), which needs the command's id.
pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
}
// ---------- param helpers ----------
@@ -420,8 +430,22 @@ pub(crate) fn text_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Optio
pub(crate) fn id_param(p: &Value, key: &str) -> Option<NodeId> {
p.get(key).and_then(Value::as_u64).map(NodeId)
}
pub(crate) fn ids_param(p: &Value, key: &str) -> Option<Vec<NodeId>> {
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(NodeId).collect())
/// The object ids `p` gives for `key`, or `None` when `p` leaves it out or gives null. A value that
/// is not an array, or an entry that is not a non-negative integer, is an error with the message
/// [`checked_ids_param`] gives, so no entry is dropped. Whether each id names an object is left to
/// the caller.
pub(crate) fn ids_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<NodeId>>> {
let values = match p.get(key) {
None | Some(Value::Null) => return Ok(None),
Some(Value::Array(a)) => a,
Some(_) => return Err(bad(cmd, format!("{key} must be an array of non-negative integer object ids"))),
};
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, cmd)).collect::<Result<Vec<_>>>().map(Some)
}
/// Entry `index` (from 0) of the `key` list as an object id: anything but a non-negative integer is
/// an error naming the key, the entry and its value.
fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId> {
value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("`{key}` entry {index} is {value}, not a non-negative integer object id")))
}
/// The objects `p` gives `command`: its `ids`, else its `id` as `ids` of one (as [`targets`] reads
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
@@ -447,7 +471,7 @@ pub(crate) fn index(v: u64) -> usize {
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
let values =
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
values.iter().map(|value| checked_id(s, value, command)).collect()
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
}
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
+8 -7
View File
@@ -962,11 +962,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
let default = CharStyle::default().font_family;
let wanted = text_param(p, "font", C)?.filter(|f| !f.trim().is_empty()).unwrap_or(&default);
let db = FontDb::global();
// Any name of the family is stored as its own name.
let family = match db.resolve(wanted, "Regular") {
Some((f, m)) if m != FontMatch::Missing => f.family.clone(),
_ => return Err(bad(C, "the replacement font is not available")),
};
// Any name of the family is stored as its own name, and a composite font as its own name.
let composite = db.composite_font(wanted).is_some();
let family = db.stored_family(wanted, "Regular").ok_or_else(|| bad(C, "the replacement font is not available"))?;
let missing = |st: &CharStyle| db.resolve(&st.font_family, &st.font_style).is_none_or(|(_, m)| m == FontMatch::Missing);
let lacks = |t: &TextObject| t.runs.iter().any(|r| missing(&r.style));
let d = &s.doc()?.doc;
@@ -988,8 +986,11 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
let mut runs = 0;
let mut replace = |t: &mut TextObject| {
for r in t.runs.iter_mut().filter(|r| missing(&r.style)) {
// The style the font has closest to the one the character had.
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
// The style the font has closest to the one the character had (a composite font's
// parts name their own styles: the character keeps its style).
if !composite {
r.style.font_style = db.face(&family, &r.style.font_style).map_or_else(|| r.style.font_style.clone(), |f| f.style.clone());
}
r.style.font_family = family.clone();
r.style.font_version = None;
r.style.font_axes.clear();
+1 -1
View File
@@ -174,7 +174,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
@@ -189,7 +189,7 @@ pub(super) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let given = json!({
"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fill": fill, "stroke": stroke, "includeImages": false, "includePatterns": false,
});
let r = recolor_links(s, &given, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
let r = recolor_links(s, &given, APPLY, "Apply Nearest Swatch", &|c| to(c).and_then(Paint::color).unwrap_or(c), &links)?;
squash(s, undo, "Apply Nearest Swatch");
Ok(json!({ "changed": r["changed"], "swatches": names, "added": added }))
}
+48 -28
View File
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
has_doc,
clear_appearance
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reduce to Basic Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
reduce_basic
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Item",
[],
None,
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
set_item
),
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Item",
[],
None,
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
remove_item
),
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Duplicate Item",
["Window", "Appearance"],
None,
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
duplicate_item
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder Appearance Item",
[],
None,
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
has_doc,
move_item
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
has_doc,
copy_from
),
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All Hidden Attributes",
["Window", "Appearance"],
None,
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
has_doc,
show_all_hidden
),
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Appearance",
[],
None,
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {source, target}",
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
has_doc,
transfer
),
@@ -628,25 +628,33 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
}
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
let object = super::graph::capture_series_object_opacity(d, &ids);
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || object))
})?;
s.active_appearance_item = None;
ok()
}
/// Each of `ids` whose object opacity or blend mode is another in `d` than in `before`, for
/// [`super::graph::capture_series_object_opacity`].
fn object_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<NodeId> {
let of = |d: &vectorcraft_doc::Document, id: NodeId| d.node(id).map(|n| (n.opacity, n.blend));
ids.iter().copied().filter(|id| of(before, *id) != of(d, *id)).collect()
}
/// Each of `ids` with both kinds of row (fill, then stroke), for [`super::graph::capture_series_opacity`] after an
/// edit that replaces whole stacks.
fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> {
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect()
}
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another opacity in `d`
/// than in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another opacity or blend
/// mode in `d` than in `before` (no row counts as opaque and Normal), for [`super::graph::capture_series_opacity`].
fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| {
d.node(id)
.and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()).map(AppearanceItem::opacity))
.unwrap_or(1.0)
.and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()).map(|it| (it.opacity(), it.blend())))
.unwrap_or((1.0, BlendMode::Normal))
};
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
}
@@ -666,9 +674,10 @@ fn painted_rows(d: &vectorcraft_doc::Document, rows: impl IntoIterator<Item = (N
}
/// Store on the graph what an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke of the
/// series marks among them: a paint, weight or opacity that changed, and the paint (`paints`) and opacity (`opacities`) of
/// the kinds of row the edit wrote, as (fill, stroke). With `top_only` the edit wrote the topmost row of each kind, which
/// counts only when it is visible. Returns whether the stored paint changed.
/// series marks among them: a paint, weight, opacity or blend mode that changed, and the paint (`paints`) and opacity and
/// blend mode (`opacities`) of the kinds of row the edit wrote, as (fill, stroke). With `top_only` the edit wrote the
/// topmost row of each kind, which counts only when it is visible. It also stores the marks' object opacity and blend mode
/// when they changed, or on every mark when the edit wrote them (`object`). Returns whether the stored paint changed.
pub(super) fn capture_series_writes(
before: &vectorcraft_doc::Document,
d: &mut vectorcraft_doc::Document,
@@ -676,22 +685,29 @@ pub(super) fn capture_series_writes(
paints: (bool, bool),
opacities: (bool, bool),
top_only: bool,
object: bool,
) -> bool {
let top_shows = |d: &vectorcraft_doc::Document, id: NodeId, kind: bool| {
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(AppearanceItem::visible)
};
let written = |d: &vectorcraft_doc::Document, (fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
let kinds = |(fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
let rows = ids.iter().flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))]).flatten();
painted_rows(d, rows.filter(|(id, kind)| !top_only || top_shows(d, *id, *kind)))
rows.filter(|(id, kind)| !top_only || top_shows(d, *id, *kind)).collect()
};
let written = |d: &vectorcraft_doc::Document, rows: (bool, bool)| painted_rows(d, kinds(rows));
let mut opacity_rows = top_opacity_changed(before, d, ids);
// A written row that had paint before the edit counts too when the edit left it without paint: only a row without
// paint both before and after keeps what the graph stores.
opacity_rows.extend(painted_rows(before, kinds(opacities)));
opacity_rows.extend(written(d, opacities));
let mut rows = top_paint_changed(before, d, ids);
rows.extend(written(d, paints));
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
let painted = super::graph::capture_series_top_paints(d, &rows);
kept || painted
let objects = if object { ids.to_vec() } else { object_opacity_changed(before, d, ids) };
let stored = super::graph::capture_series_object_opacity(d, &objects);
kept || painted || stored
}
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
@@ -743,7 +759,8 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
let mut rows = top_paint_changed(&before, d, &changed);
rows.extend(painted_rows(d, both_kinds(&[target])));
let painted = super::graph::capture_series_top_paints(d, &rows);
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted))
let object = super::graph::capture_series_object_opacity(d, &changed);
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
@@ -862,10 +879,10 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
edited.push((*id, fill));
}
}
// The graph keeps an opacity, paint or weight set on the topmost visible fill or stroke of its series art for when
// it is drawn again, and hiding or showing a row changes which row that is.
// The graph keeps an opacity, blend mode, paint or weight set on the topmost visible fill or stroke of its series art
// for when it is drawn again, and hiding or showing a row changes which row that is.
let mut opacities = top_opacity_changed(&before, d, &ids);
if p.get("opacity").and_then(Value::as_f64).is_some() {
if p.get("opacity").and_then(Value::as_f64).is_some() || blend.is_some() {
opacities.extend(edited.iter().copied());
}
let kept = super::graph::capture_series_opacity(d, &opacities);
@@ -1230,7 +1247,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
let selected = if defaults_only {
vec![]
} else {
match ids_param(p, "ids") {
match ids_param(p, "ids", C)? {
Some(v) => outermost(&s.doc()?.doc, v),
None => selected_roots(s)?,
}
@@ -1347,7 +1364,10 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
rows.extend(painted_rows(d, written(paints)));
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
let painted = super::graph::capture_series_top_paints(d, &rows);
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted))
// A pick of the object's transparency writes it on every target.
let objects = if attrs.appearance.transparency { targets.clone() } else { object_opacity_changed(&before, d, &targets) };
let object = super::graph::capture_series_object_opacity(d, &objects);
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object))
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
+5 -6
View File
@@ -277,12 +277,11 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
for id in ids {
let Some(a) = d.asset(id) else { continue };
let format = a.format_3d.as_deref().unwrap_or(DEFAULT_FORMAT_3D);
let mut parts = vec![];
for node in &a.nodes {
let n = d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))?;
let what = &a.name;
parts.extend(vectorcraft_render::effects::three_d_meshes(n).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?);
}
let nodes =
a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::<Result<Vec<_>>>()?;
// The asset's objects share one budget of triangles.
let what = &a.name;
let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
+1 -1
View File
@@ -263,7 +263,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Instance Appearance",
[],
None,
"{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol or a path naming no object → {id, overrides: how many objects the instance changes}",
"{id?|ids?: [one id] (default: the one selected object), path: [i…] (the object in the symbol's art: child indices in paint order from the art's root down through its groups; [] the root), fill?: \"#rrggbb\"|{…paint params of paint.setFill: color, none, swatch, tint, gradient, keepModel}|null (null: the symbol's own again), stroke?: as fill, opacity?: 0..100|null, blend?: name|null} change the appearance of one object of a dynamic symbol instance's art, for that instance only: it stays linked, so editing the symbol reshapes it and keeps the change; refused for a static symbol, a path naming no object, or a fill or stroke other than null for an object that does not draw it (a guide, blend, envelope, Repeat, Intertwine group, gradient mesh or placed document; a symbol instance's stroke, and its fill unless a solid color or none, which stains its art; an image's fill or stroke without a Convert to Shape or Outline Object effect), with nothing of the call applied; opacity, blend and null are taken for every object → {id, overrides: how many objects the instance changes}",
has_selection,
symbol_instance_set_appearance
),
+60
View File
@@ -129,6 +129,64 @@ fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
Ok(path)
}
/// The refusal of `key` (`fill` or `stroke`) for `n`, an object of a dynamic symbol's art, when `n`
/// does not draw that paint of its own; `None` when it does. Paths (not guides),
/// compound paths, type, groups and layers draw them; a symbol instance draws its fill as a stain
/// on its art ([`solid_fill_check`]) and no stroke; an image draws one only when that fill or
/// stroke has a Convert to Shape or Outline Object effect.
fn paint_refusal(n: &Node, key: &str, cmd: &str) -> Option<EngineError> {
Some(match &n.kind {
NodeKind::Path { guide: true, .. } => bad(cmd, format!("{key} cannot be set on a guide")),
NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) | NodeKind::Group { .. } | NodeKind::Layer { .. } => return None,
NodeKind::Image(_) => {
let effects = if key == "fill" { n.appearance.fill().map(|f| &f.effects) } else { n.appearance.stroke().map(|s| &s.effects) };
if effects.is_some_and(|e| vectorcraft_render::effects::gives_image_shape(e)) {
return None;
}
bad(cmd, format!("{key} cannot be set on an image without a Convert to Shape or Outline Object effect on it"))
}
NodeKind::SymbolInstance { .. } if key == "fill" => return None,
NodeKind::SymbolInstance { .. } => bad(cmd, "stroke cannot be set on a symbol instance"),
NodeKind::Blend { .. } => bad(cmd, format!("{key} cannot be set on a blend")),
NodeKind::Envelope { .. } => bad(cmd, format!("{key} cannot be set on an envelope")),
NodeKind::Mesh(_) => bad(cmd, format!("{key} cannot be set on a gradient mesh")),
NodeKind::Repeat(_) => bad(cmd, format!("{key} cannot be set on a Repeat")),
NodeKind::PlacedDocument(_) => bad(cmd, format!("{key} cannot be set on a placed document")),
NodeKind::Intertwine { .. } => bad(cmd, format!("{key} cannot be set on an Intertwine group")),
})
}
/// Refuse a `fill` or `stroke` other than null that the object at `path` of `art` does not draw
/// ([`paint_refusal`]); null, which takes a change back, is taken for every object.
fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<()> {
let Some(n) = symbol_overrides::part(art, path) else { return Ok(()) };
for key in ["fill", "stroke"] {
if p.get(key).is_some_and(|v| !v.is_null())
&& let Some(e) = paint_refusal(n, key, cmd)
{
return Err(e);
}
}
Ok(())
}
/// Refuse `fill`, the paint `p` asks for the object at `path` of `art`, when that object is a
/// symbol instance and `fill` is a gradient or a pattern: an instance stains its art with a solid
/// fill only, so such a fill draws nothing.
fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> {
let asked = p.get("fill").is_some_and(|v| !v.is_null());
let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }));
let draws_nothing = |f: &vectorcraft_color::Paint| match f {
vectorcraft_color::Paint::Gradient(_) => true,
vectorcraft_color::Paint::Pattern { .. } => true,
vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false,
};
if asked && is_instance && fill.is_some_and(draws_nothing) {
return Err(bad(cmd, "fill on a symbol instance must be a solid color or none"));
}
Ok(())
}
/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or
/// an object of `paint.setFill`'s paint params sets it.
fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> {
@@ -170,9 +228,11 @@ pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Resu
}
let (id, art) = dynamic_instance(s, p, C)?;
let path = path_param(p, &art, C)?;
check_paint_kinds(p, &art, &path, C)?;
let d = &s.doc()?.doc;
let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned());
let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?;
solid_fill_check(p, &art, &path, new.fill.as_ref(), C)?;
let count = edit_part(s, id, &path, "Symbol Instance Appearance", |o| *o = new)?;
Ok(json!({ "id": id.0, "overrides": count }))
}
+2 -2
View File
@@ -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\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), 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), 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)}",
"{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\", 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), 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)
),
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make and Expand",
["Object", "Image Trace"],
None,
"{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors}",
"{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors, warnings: [text…] (as imageTrace.make)}",
has_selection_or_ids,
|s, p| trace_make(s, p, true)
),
@@ -1,5 +1,5 @@
use super::{
Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, SubPath, Touched, Value, b, bad, check_numbers,
Arc, Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, Touched, Value, b, bad, check_numbers,
f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, po, points_param, remnant, replace_leaves, replace_with_pieces, root_ids,
shape_node, switch_or,
};
@@ -41,6 +41,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
let gap = gap_param(p);
// The map the Shape Builder tool already has, which a click or drag of it is made over.
let shared = s.tool.shape_builder_map().filter(|(_, g)| *g == gap);
let prepared = s.tool.shape_builder_merge();
let label = if erase { "Shape Builder Delete" } else { "Shape Builder" };
let (ids, merged, touched, split) = s.edit(label, |d, sel| {
let (shapes, leaves) = b::shape_builder_shapes(d, &roots, open_filled_as_closed);
@@ -89,16 +90,28 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
touched.add(map.hit(q, Some(tol)));
return Ok((ids, None, touched, Some(split)));
}
let mut touched = Touched { regions: marquee.map(|(a, b)| map.regions_in_marquee(a, b)).unwrap_or_default(), ..Default::default() };
touched.extend(&map.builder_hits_along(&pts, piece_tol));
touched.edges = map.erased_edges(&touched);
let touched = map.merge_touched(&pts, marquee, piece_tol);
if touched.is_empty() {
return Err(EngineError::Other("Shape Builder: no region under the pointer".into()));
}
let cuts: Vec<&SubPath> = touched.edges.iter().filter_map(|&k| map.edges.get(k)?.0.path.subpaths.first()).collect();
let inputs = b::merge_inputs(&leaves.iter().collect::<Vec<_>>(), open_filled_as_closed);
// The tool computed this merge on another thread when it would come out the same.
let ready = prepared.as_ref().filter(|m| {
shared.as_ref().is_some_and(|(s, _)| Arc::ptr_eq(s, &m.map) && std::ptr::eq(s.as_ref(), map))
&& m.gap == gap
&& m.touched == touched
&& m.inputs == inputs
});
let computed;
let geometry = match ready {
Some(m) => &m.geometry,
None => {
computed = b::merge_geometry(map, &touched, gap, &inputs);
&computed
}
};
let picked: Vec<&po::Region> = touched.regions.iter().filter_map(|&i| map.regions.get(i).map(|r| &r.0)).collect();
let faces = po::FaceMerger::with_gap(&map.shapes, gap_param(p));
let union = if picked.is_empty() { PathData::default() } else { faces.merge(&picked) };
let union = &geometry.union;
// Pick Color From Artwork: the merged shape takes the look of the front-most object under the
// drag's first point, else under its last point, else of the front-most object. Color
// Swatches: the current fill, with the rest of the look of the front-most object over the
@@ -115,7 +128,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
// What goes in place of each object the map was made from (none: it stays as it is).
let mut outs: Vec<Option<Vec<Node>>> = vec![];
let mut merged_id = None;
for (i, (sh, leaf)) in map.shapes.iter().zip(&leaves).enumerate() {
for (i, leaf) in leaves.iter().take(map.shapes.len()).enumerate() {
let mut out = None;
let pieces: Vec<usize> = map.lines.iter().enumerate().filter(|(_, (l, _))| l.key == i as u64).map(|(k, _)| k).collect();
if !pieces.is_empty() {
@@ -131,41 +144,15 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
}
out = Some(kept);
}
} else {
} else if let Some(Some(rest)) = geometry.rests.get(i) {
// A shape loses the regions deleted or merged, then the edges deleted (each one on
// its outline, shared edges from every shape along them).
let in_union = picked.iter().any(|r| r.sources.contains(&i));
let mut rest = if in_union {
// What is left of it: its faces not merged or deleted, united. They share their
// edges with the merged faces exactly, where subtracting the merged shape left
// slivers of the outline along them (#569). A sliver goes in only where the
// shape covers it and the merged shape does not take it in.
let kept: Vec<&po::Region> = map
.regions
.iter()
.enumerate()
.filter(|(k, (r, ..))| r.sources.contains(&i) && !touched.regions.contains(k))
.map(|(_, (r, ..))| r)
.collect();
if kept.is_empty() { PathData::default() } else { faces.merge_rest(i, &kept, &picked) }
// its outline, shared edges from every shape along them). What is left of its own
// outline keeps its fill rule; united faces fill with non-zero.
out = Some(if rest.path.is_empty() {
vec![]
} else {
b::node_outline(leaf).map_or_else(|| sh.path.clone(), |o| o.0)
};
let fill_closes = open_filled_as_closed && !leaf.appearance.fill_paint().is_none();
// Edges come back from the planar map within a few hundredths of the outlines they
// follow, whatever else is selected.
let cut_tol = b::outline_snap(&sh.path);
let mut cut = false;
for piece in &cuts {
if let Some(r) = po::cut_out(&rest, piece, fill_closes, cut_tol) {
rest = r;
cut = true;
}
}
if in_union || cut {
// What is left of its own outline keeps its fill rule; united faces fill with non-zero.
out = Some(if rest.is_empty() { vec![] } else { vec![remnant(d, leaf, rest, in_union.then_some(FillRule::NonZero))] });
}
vec![remnant(d, leaf, rest.path.clone(), rest.united.then_some(FillRule::NonZero))]
});
}
// The merged shape goes in place of the object it takes its look from, so it stays in
// that object's group (a clip group too).
+45 -2
View File
@@ -712,7 +712,8 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
};
let TraceInputs { target, image: img, .. } = inputs;
let warnings = trace_warnings((img.width, img.height), raster, res.worked_at);
let mut warnings = keep_warnings(&trace, &res);
warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at));
// Pixel space of the decoded raster → the image object's pixel space → document.
let sx = img.width.max(1) as f64 / raster.0.max(1) as f64;
let sy = img.height.max(1) as f64 / raster.1.max(1) as f64;
@@ -824,6 +825,30 @@ pub(crate) fn trace_warnings(size: (u32, u32), traced: (u32, u32), worked: Optio
out
}
/// What a trace with Keep Colors tells the user: that nothing was traced because no color the
/// trace found matches a listed one, because Ignore Color left out the ones that match, or because
/// the ones that match produce no paths; each listed color that matches none of them; and that Flat
/// Logo mode does not use the list.
pub(crate) fn keep_warnings(params: &tr::TraceParams, res: &tr::TraceResult) -> Vec<String> {
if params.keep_colors.is_empty() {
return vec![];
}
if params.mode == tr::Mode::Logo {
return vec!["Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds.".to_string()];
}
if res.paths.is_empty() && res.keep_unmatched.len() == params.keep_colors.len() {
return vec![format!("Nothing was traced: none of the colors the trace found matches keepColors ({}).", params.keep_colors.join(", "))];
}
let mut out = vec![];
if res.paths.is_empty() && res.keep_ignored {
out.push("Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists.".to_string());
} else if res.paths.is_empty() {
out.push("Nothing was traced: the colors that match keepColors produce no paths.".to_string());
}
out.extend(res.keep_unmatched.iter().map(|c| format!("keepColors: none of the colors the trace found matches {c}, so nothing of it is traced.")));
out
}
fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let v: Vec<NodeId> = root_ids(s, p)?.into_iter().filter(|i| d.node(*i).is_some_and(is_trace_group)).collect();
@@ -1069,7 +1094,25 @@ mod color_group_tests {
#[cfg(test)]
mod trace_limit_tests {
use super::{MAX_TRACE_ANCHORS, trace_warnings};
use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings};
use vectorcraft_trace as tr;
#[test]
fn keep_warnings_name_matched_colors_that_produce_no_paths() {
let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() };
// A listed color was traced, and produced no paths: the palette lists no color without paths.
let traced = tr::TraceResult::default();
let none = vec!["Nothing was traced: the colors that match keepColors produce no paths.".to_string()];
assert_eq!(keep_warnings(&params, &traced), none);
// With Ignore Color, too: Ignore Color did not leave that color out.
let ignoring = tr::TraceParams { ignore_white: true, ..params.clone() };
assert_eq!(keep_warnings(&ignoring, &traced), none);
// Ignore Color left out every color that matches: none was traced.
assert_eq!(
keep_warnings(&ignoring, &tr::TraceResult { keep_ignored: true, ..tr::TraceResult::default() }),
vec!["Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists.".to_string()]
);
}
#[test]
fn trace_warnings_name_a_large_or_scaled_down_image() {
+1 -1
View File
@@ -182,7 +182,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Image into Clipboard",
[],
None,
"{dataBase64 (PNG, JPEG, GIF, WebP, TIFF or BMP bytes), mime?: the type the system clipboard gave (an image/… type; the format is read from the bytes), center?: [x, y]} replace the clipboard with the image, embedded at 100% of its physical size (its resolution, else 72 ppi), centred on `center` (default: the first artboard) → {count, width, height (pt), pixelWidth, pixelHeight}; then run edit.paste. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error",
"{dataBase64 (PNG, JPEG, GIF, WebP, TIFF, BMP, Targa, PCX, PSD, PSB or JPEG XL bytes), mime?: the type the system clipboard gave (an image/… type; the format is read from the bytes), center?: [x, y]} replace the clipboard with the image, embedded at 100% of its physical size (its resolution, else 72 ppi), centered on `center` (default: the first artboard) → {count, width, height (pt), pixelWidth, pixelHeight}; then run edit.paste. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error",
has_doc,
import_image
),
+180 -26
View File
@@ -30,37 +30,37 @@ pub fn specs() -> Vec<CommandSpec> {
"Invert Colors",
["Edit", "Edit Colors"],
None,
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed}",
"{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}",
has_selection,
|s, p| recolor(s, p, "Invert Colors", &invert)
|s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert)
),
cmd!(
"edit.colors.toCMYK",
"Convert to CMYK",
["Edit", "Edit Colors"],
None,
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}",
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
has_selection,
|s, p| recolor(s, p, "Convert to CMYK", &to_cmyk)
|s, p| recolor(s, p, "edit.colors.toCMYK", "Convert to CMYK", &to_cmyk)
),
cmd!(
"edit.colors.toGrayscale",
"Convert to Grayscale",
["Edit", "Edit Colors"],
None,
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}",
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
has_selection,
|s, p| recolor(s, p, "Convert to Grayscale", &to_gray)
|s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
),
cmd!(
"edit.colors.toRGB",
"Convert to RGB",
["Edit", "Edit Colors"],
None,
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed}",
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
has_selection,
|s, p| {
recolor(s, p, "Convert to RGB", &|c| {
recolor(s, p, "edit.colors.toRGB", "Convert to RGB", &|c| {
let [r, g, b] = c.to_rgb();
Color::rgb(r, g, b)
})
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Saturate…",
["Edit", "Edit Colors"],
None,
"{intensity: -100..100 (%; a number outside the range counts as its nearest end), fill?, stroke?, includeImages?, includePatterns?, ids?} scale saturation by (1 + intensity/100), reaching what edit.colors.invert does → {changed}",
"{intensity: -100..100 (%; a number outside the range counts as its nearest end), fill?, stroke?, includeImages?, includePatterns?, ids?} scale saturation by (1 + intensity/100), reaching what edit.colors.invert does → {changed, notChanged, warning?} (as edit.colors.invert)",
has_selection,
saturate
),
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Adjust Color Balance…",
["Edit", "Edit Colors"],
None,
"{mode?: \"rgb\"|\"cmyk\"|\"gray\"|\"global\" (default: from the channels given), r?, g?, b? | c?, m?, y?, k? | gray? | tint?: -100..100 (% added per channel, default 0; `tint` is global mode: it shifts the tints of colours and gradient stops linked to global and spot swatches, which stay linked, and leaves other colours and images alone), convert?: false (true: the results stay in the adjusted model; false: each colour keeps its own), fill?, stroke?, includeImages?, includePatterns?, ids?} reaching what edit.colors.invert does → {changed}",
"{mode?: \"rgb\"|\"cmyk\"|\"gray\"|\"global\" (default: from the channels given), r?, g?, b? | c?, m?, y?, k? | gray? | tint?: -100..100 (% added per channel, default 0; `tint` is global mode: it shifts the tints of colours and gradient stops linked to global and spot swatches, which stay linked, and leaves other colours and images alone), convert?: false (true: the results stay in the adjusted model; false: each colour keeps its own), fill?, stroke?, includeImages?, includePatterns?, ids?} reaching what edit.colors.invert does → {changed, notChanged, warning?} (as edit.colors.invert)",
has_selection,
adjust_balance
),
@@ -213,6 +213,48 @@ impl<'a> Recolor<'a> {
Self { links: Some(links), ..Self::new(scope, f) }
}
/// A pass that maps colors as this one does, with nothing recolored yet.
fn again(&self) -> Self {
Self { links: self.links, ..Self::new(self.scope, self.f) }
}
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
/// than by swatch links alone, its patterns' tiles included. The document stays as it is.
pub(crate) fn would_change<T: Copy>(mut self, d: &Document, objects: &[(NodeId, T)]) -> Vec<(NodeId, T)> {
let tried: Vec<(&Node, Node, T)> =
objects.iter().filter_map(|&(id, flag)| d.node(id).and_then(|n| Some((n, self.subtree(d, n)?, flag)))).collect();
let same = self.link_only_copies(d);
tried.into_iter().filter_map(|(n, m, flag)| (without_links(m, &same) != without_links(n.clone(), &same)).then_some((n.id, flag))).collect()
}
/// The patterns this pass has copied whose copy differs from the original only by swatch
/// links: the copy's name → the original's. A copy whose tile uses other copies counts when
/// those copies do.
fn link_only_copies(&self, d: &Document) -> HashMap<String, String> {
let art = |v: &[Arc<Node>], same: &HashMap<String, String>| v.iter().map(|n| without_links((**n).clone(), same)).collect::<Vec<_>>();
let copies: HashMap<&str, &PatternDef> = self.new_patterns.iter().map(|p| (p.name.as_str(), p)).collect();
let pairs: Vec<(&String, &String, &PatternDef, &PatternDef)> = self
.patterns
.iter()
.filter_map(|(old, new)| {
let new = new.as_ref()?;
Some((new, old, d.pattern(old)?, *copies.get(new.as_str())?))
})
.collect();
let mut same = HashMap::new();
loop {
let found: Vec<(String, String)> = pairs
.iter()
.filter(|(new, _, original, copy)| !same.contains_key(*new) && art(&original.art, &same) == art(&copy.art, &same))
.map(|(new, old, _, _)| ((*new).clone(), (*old).clone()))
.collect();
if found.is_empty() {
return same;
}
same.extend(found);
}
}
/// Recolour the objects `ids` and everything inside them (each once), add the new images and
/// pattern swatches, and return the number of paints, meshes and images changed.
pub(crate) fn run(mut self, d: &mut Document, ids: &[NodeId]) -> usize {
@@ -313,6 +355,29 @@ impl<'a> Recolor<'a> {
}
}
/// `n` with the swatch links of its paints and its children's removed, each color kept as it
/// shows, and each pattern named in `same` (a copy → its original) by its original's name.
fn without_links(mut n: Node, same: &HashMap<String, String>) -> Node {
for p in vectorcraft_doc::swatches::node_paints_mut(&mut n) {
map_links(p, &|_, link, _| link.take().is_some());
match p {
Paint::Gradient(g) => g.swatch = None,
Paint::Pattern { pattern, .. } => {
if let Some(original) = same.get(pattern.as_str()) {
*pattern = original.clone();
}
}
_ => {}
}
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(without_links((**c).clone(), same));
}
}
n
}
/// What a pass over document `d` does to each colour the shared visitor meets.
struct Visit<'p, 'a> {
pass: &'p mut Recolor<'a>,
@@ -331,34 +396,123 @@ impl ColorVisitor for Visit<'_, '_> {
}
}
pub(crate) fn recolor(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
run_pass(s, p, label, Recolor::new(Scope::of(p), f))
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), f))
}
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
/// link and tint.
pub(crate) fn recolor_links(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
run_pass(s, p, label, Recolor::with_links(Scope::of(p), f, links))
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links))
}
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step.
fn run_pass(s: &mut Session, p: &Value, label: &str, pass: Recolor) -> Result<Value> {
let ids = match ids_param(p, "ids") {
Some(v) => v,
None => selected_roots(s)?,
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
/// errors name the command `cmd`. The reply's `notChanged` counts the locked and hidden objects the
/// selection left out ([`left_out`]) that the pass would have changed.
fn run_pass(s: &mut Session, p: &Value, cmd: &str, label: &str, pass: Recolor) -> Result<Value> {
let (ids, left) = match ids_param(p, "ids", cmd)? {
Some(v) => (v, vec![]),
None => {
let roots = selected_roots(s)?;
let st = s.doc()?;
let left = left_out(&st.doc, st.isolation, &roots);
(roots, left)
}
};
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
let n = s.edit(label, |d, _| {
let (n, not_changed) = s.edit(label, |d, _| {
let not_changed = NotChanged::of(pass.again().would_change(d, &left).into_iter().map(|(_, hidden)| hidden));
let n = pass.run(d, &ids);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(label, e))?;
Ok(n)
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(cmd, e))?;
Ok((n, not_changed))
})?;
Ok(json!({ "changed": n }))
let mut out = json!({ "changed": n });
not_changed.report(&mut out);
Ok(out)
}
/// The objects a recolor of `roots` leaves out of the art the user meant to recolor, each with
/// whether it is hidden (otherwise it is locked). When `roots` are exactly the objects Select All
/// takes (in isolation mode, those of the isolated group), these are the objects beside them that
/// Select All skips: hidden or locked objects, the objects of hidden or locked layers and
/// sublayers, and, outside isolation mode, objects on locked artboards (counted as locked). The art
/// of template layers and the objects inside a group are not listed. With any other `roots`, none.
pub(crate) fn left_out(d: &Document, iso: Option<NodeId>, roots: &[NodeId]) -> Vec<(NodeId, bool)> {
fn visit(n: &Node, hidden: bool, locked: bool, all: &HashSet<NodeId>, board_locked: &dyn Fn(&Node) -> bool, out: &mut Vec<(NodeId, bool)>) {
for c in n.children().into_iter().flatten() {
if c.is_template() {
continue;
}
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
if c.is_layer() {
visit(c, hidden, locked, all, board_locked, out);
} else if !all.contains(&c.id) && (hidden || locked || board_locked(c)) {
out.push((c.id, hidden));
}
}
}
let all: HashSet<NodeId> = super::select::selectable(d, iso).into_iter().collect();
let picked: HashSet<NodeId> = roots.iter().copied().collect();
if picked.is_empty() || picked != all {
return vec![];
}
let mut out = vec![];
match iso.and_then(|i| d.node(i)) {
Some(c) => visit(c, false, false, &all, &|_| false, &mut out),
None => {
let boards = d.locked_artboards();
let board_locked = |n: &Node| !boards.is_empty() && boards.holds(n);
for l in d.layers.iter().filter(|l| !l.is_template()) {
visit(l, !l.visible, l.locked, &all, &board_locked, &mut out);
}
}
}
out
}
/// How many locked and hidden objects a recolor left out ([`left_out`]) although it would have
/// changed their colors. An object both hidden and locked counts as hidden.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct NotChanged {
pub locked: usize,
pub hidden: usize,
}
impl NotChanged {
/// The counts of objects given by whether each is hidden.
pub(crate) fn of(hidden: impl IntoIterator<Item = bool>) -> Self {
hidden.into_iter().fold(Self::default(), |n, h| if h { Self { hidden: n.hidden + 1, ..n } } else { Self { locked: n.locked + 1, ..n } })
}
/// Add `notChanged` to reply `out`, and a `warning`, which the app shows in its status bar,
/// when any object is counted.
pub(crate) fn report(self, out: &mut Value) {
out["notChanged"] = json!({ "locked": self.locked, "hidden": self.hidden });
if let Some(w) = self.warning() {
out["warning"] = json!(w);
}
}
fn warning(self) -> Option<String> {
let part = |n: usize, kind: &str| match n {
0 => None,
1 => Some(format!("1 {kind} object")),
n => Some(format!("{n} {kind} objects")),
};
match (part(self.locked, "locked"), part(self.hidden, "hidden")) {
(Some(locked), Some(hidden)) => Some(format!("Recolor completed; {locked} and {hidden} were left unchanged")),
(Some(objects), None) | (None, Some(objects)) if self.locked + self.hidden == 1 => {
Some(format!("Recolor completed; {objects} was left unchanged"))
}
(Some(objects), None) | (None, Some(objects)) => Some(format!("Recolor completed; {objects} were left unchanged")),
(None, None) => None,
}
}
}
fn saturate(s: &mut Session, p: &Value) -> Result<Value> {
let i = (f64_req(p, "intensity", "edit.colors.saturate")?.clamp(-100.0, 100.0) / 100.0) as f32;
recolor(s, p, "Saturate", &move |c| {
recolor(s, p, "edit.colors.saturate", "Saturate", &move |c| {
let [h, sat, v] = c.to_hsb();
let to = (sat * (1.0 + i)).clamp(0.0, 1.0);
// A color whose saturation stays the same is returned as it is, so it keeps its swatch link.
@@ -416,12 +570,12 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
(*tint, *c) = (t, base.tinted(t));
true
};
return run_pass(s, p, "Adjust Colors", Recolor::links(Scope::of(p), &shift));
return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift));
}
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
};
let convert = bool_or(p, "convert", false);
recolor(s, p, "Adjust Colors", &move |c| {
recolor(s, p, C, "Adjust Colors", &move |c| {
let out = adjust(c);
if convert { out } else { keep_model(c, out) }
})
+2 -1
View File
@@ -287,7 +287,8 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
/// How Document Color Mode converts neutral RGB greys (R = G = B) to CMYK (the `grays` param).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Grays {
/// Through the CMYK profile like any colour: four-colour greys and a rich black.
/// Through the CMYK profile like any colour: light grays in cyan, magenta and yellow only, darker
/// grays in four inks, and a rich black.
#[default]
Profile,
/// On the black plate only: K is the grey's ink percentage (as Convert to Grayscale and then
+327
View File
@@ -0,0 +1,327 @@
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
//! font of its own. Type names a composite font as its family, and the font menus list them first.
//! The font database holds the active document's composite fonts ([`sync`]); a file exported here
//! carries them to another document.
//!
//! Behavior reference (public documentation):
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts};
use vectorcraft_text::FontDb;
use super::fileio::{read_file_head, write_file};
use super::textstyles::each_text_mut;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param};
/// The extension of the files Export writes and Import reads.
pub const EXTS: &[&str] = &["vccomposite"];
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
/// The keys a part may give.
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "type.compositeFonts.list",
"Composite Fonts",
[],
None,
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}",
has_doc,
list
),
cmd!(
"type.compositeFonts.set",
"Composite Fonts…",
["Type"],
None,
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
has_doc,
set
),
cmd!(
query "type.compositeFonts.export",
"Export Composite Fonts",
[],
None,
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}",
has_doc,
export
),
cmd!(
"type.compositeFonts.import",
"Import Composite Fonts",
[],
None,
"{path: .vccomposite file | data: its text | dataBase64: its bytes (at most 4 MB), apply?: bool = true} read the composite fonts a file holds (type.compositeFonts.export writes them); with apply they join the active document's, a font of the same name (any case) replaced, as one undo step, none when nothing changes; apply false only reads them → {fonts, imported: [name]}",
has_doc,
import
),
]
}
/// Register the active document's composite fonts in the font database, and remove the ones the
/// other open documents (or an earlier active document) defined. Run after each command and when
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
/// switch draws type in the active document's own composite fonts, and type naming one it does
/// not define shows as missing. The lowercased names of the composite fonts added, changed or
/// removed.
pub(crate) fn sync(s: &mut Session) -> Vec<String> {
let db = FontDb::global();
let mut names = Vec::new();
let mut changed = Vec::new();
for f in s.active().map(|d| d.doc.composite_fonts.to_vec()).unwrap_or_default() {
let name = f.name.to_lowercase();
if db.set_composite_font(&f) {
changed.push(name.clone());
}
names.push(name);
}
let others = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
let stale: Vec<String> = s.composite_names.iter().cloned().chain(others).filter(|n| !names.contains(n)).collect();
for gone in stale {
if db.remove_composite_font(&gone) {
changed.push(gone);
}
}
s.composite_names_registered.extend(names.iter().chain(&changed).cloned());
s.composite_names = names;
changed
}
/// The lowercased names of the composite fonts the open documents define, the font database holds
/// and the session has registered before: the names type may have been laid out in.
pub(crate) fn names_in_use(s: &Session) -> std::collections::HashSet<String> {
let defined = s.docs.iter().flat_map(|d| d.doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
let held = FontDb::global().composite_font_names().into_iter().map(|n| n.to_lowercase());
defined.chain(held).chain(s.composite_names_registered.iter().cloned()).collect()
}
/// Leave out a file's unusable composite fonts before registering and measuring its type.
pub(crate) fn filter_loaded(doc: &mut vectorcraft_doc::Document) {
let db = FontDb::global();
if let Some(kept) = CompositeFont::usable(&doc.composite_fonts) {
*doc.composite_fonts = kept;
}
doc.composite_fonts.retain(|f| !db.has_installed_family(&f.name));
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "fonts": *s.doc()?.doc.composite_fonts }))
}
/// Composite font `v` from command parameters or a file: its name trimmed, each part left out a
/// copy of the Kanji part, and keys or values a part can't take refused.
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) {
return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
let name = CompositeFont::clean_name(raw)
.ok_or_else(|| bad(c, format!("`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
let parts = o.get("parts").and_then(Value::as_object).ok_or_else(|| bad(c, format!("`{name}`: parts must be an object")))?;
if let Some(k) = parts.keys().find(|k| !CharClass::ALL.iter().any(|c| c.key() == k.as_str())) {
return Err(bad(c, format!("`{name}`: unknown class `{k}`; the classes are kanji, kana, punctuation, symbols, roman and numerals")));
}
let part = |class: CharClass| -> Result<Option<CompositePart>> {
let Some(p) = parts.get(class.key()) else { return Ok(None) };
let po = p.as_object().ok_or_else(|| bad(c, format!("`{name}`: {} must be an object", class.key())))?;
if let Some(k) = po.keys().find(|k| !PART_KEYS.contains(&k.as_str())) {
return Err(bad(c, format!("`{name}`: unknown key `{k}` in {}", class.key())));
}
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
};
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) };
for class in CharClass::ALL.into_iter().skip(1) {
if let Some(p) = part(class)? {
*f.parts.get_mut(class) = p;
}
}
f.check().map_err(|e| bad(c, format!("`{}`: {e}", f.name)))?;
Ok(f)
}
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
if fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
let db = FontDb::global();
let mut names = std::collections::HashSet::new();
for f in fonts {
if !names.insert(f.name.to_lowercase()) {
return Err(bad(c, format!("two composite fonts are named `{}`", f.name)));
}
if db.has_installed_family(&f.name) {
return Err(bad(c, format!("`{}` is the name of an installed font", f.name)));
}
}
for f in fonts {
for class in CharClass::ALL {
let font = &f.parts.get(class).font;
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key())));
}
}
}
Ok(())
}
/// Make `after` the active document's composite fonts, as one undo step named `label` (none when
/// they are what it has). The font database forgets the ones taken out, and type set in a font
/// that changed is measured again.
fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()> {
let before = s.doc()?.doc.composite_fonts.to_vec();
if before == after {
return Ok(());
}
let changed: Vec<String> =
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
// listed here that the document doesn't define.
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
let db = FontDb::global();
for f in &before {
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
db.remove_composite_font(&f.name);
}
}
for f in &after {
db.set_composite_font(f);
}
let r = s.edit(label, |d, _| {
*d.composite_fonts = after.clone();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
});
sync(s);
r
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.set";
let list = p.get("fonts").and_then(Value::as_array).ok_or_else(|| bad(C, "give fonts: [{name, parts}…]"))?;
let fonts = list.iter().map(|v| parse_font(v, C)).collect::<Result<Vec<_>>>()?;
check_set(&fonts, C)?;
replace(s, "Composite Fonts", fonts.clone())?;
Ok(json!({ "fonts": fonts }))
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.export";
let path = text_param(p, "path", C)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(C, "path is empty"));
}
let all = match p.get("fonts") {
None | Some(Value::Null) => s.doc()?.doc.composite_fonts.to_vec(),
Some(Value::Array(list)) => {
let fonts = list.iter().map(|v| parse_font(v, C)).collect::<Result<Vec<_>>>()?;
check_set(&fonts, C)?;
fonts
}
Some(_) => return Err(bad(C, "fonts must be a list of composite fonts")),
};
let fonts = match p.get("names") {
None | Some(Value::Null) => all,
Some(Value::Array(names)) => {
let mut out = Vec::with_capacity(names.len());
for n in names {
let n = n.as_str().ok_or_else(|| bad(C, "names must be strings"))?;
let f = all
.iter()
.find(|f| CompositeFont::same_name(&f.name, n.trim()))
.ok_or_else(|| bad(C, format!("no composite font named `{n}`")))?;
if !out.contains(f) {
out.push(f.clone());
}
}
out
}
Some(_) => return Err(bad(C, "names must be a list of names")),
};
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
None => Ok(json!({ "data": text, "count": fonts.len() })),
}
}
/// The composite fonts in the bytes of an exported file.
fn read_fonts(bytes: &[u8], c: &str) -> Result<Vec<CompositeFont>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?;
let list = v.get("compositeFonts").and_then(Value::as_array).ok_or_else(|| bad(c, "not a composite fonts file: no compositeFonts list"))?;
if list.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("the file holds more than {COMPOSITE_FONTS_MAX} composite fonts")));
}
list.iter().map(|f| parse_font(f, c)).collect()
}
fn import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.import";
let apply = switch_or(p, "apply", true, C)?;
let given = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
let too_large = || bad(C, "the file is larger than 4 MB");
let bytes = match given {
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
(None, Some(text), None) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => {
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
return Err(too_large());
}
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(C, "dataBase64 is not base64"))?
}
_ => return Err(bad(C, "give one of path, data or dataBase64")),
};
if bytes.len() > MAX_FILE_BYTES {
return Err(too_large());
}
let fonts = read_fonts(&bytes, C)?;
if fonts.is_empty() {
return Err(bad(C, "the file holds no composite fonts"));
}
let mut names = std::collections::HashSet::new();
if let Some(f) = fonts.iter().find(|f| !names.insert(f.name.to_lowercase())) {
return Err(bad(C, format!("the file holds two composite fonts named `{}`", f.name)));
}
if apply {
let mut after = s.doc()?.doc.composite_fonts.to_vec();
for f in &fonts {
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
}
check_set(&after, C)?;
replace(s, "Import Composite Fonts", after)?;
} else {
check_set(&fonts, C)?;
}
let imported: Vec<&str> = fonts.iter().map(|f| f.name.as_str()).collect();
Ok(json!({ "fonts": fonts, "imported": imported }))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,646 @@
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use crate::Session;
/// A composite font named `name`: Source Sans 3 for the base, JetBrains Mono at half size for
/// Roman, Inter for numerals.
fn font(name: &str) -> Value {
json!({"name": name, "parts": {
"kanji": {"font": "Source Sans 3"},
"roman": {"font": "JetBrains Mono", "size": 50, "baseline": 10},
"numerals": {"font": "Inter", "hScale": 80},
}})
}
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// A scratch folder of the test's own.
fn folder(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("vectorcraft-composite-fonts-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// Composite Fonts' OK replaces the document's composite fonts as one undo step (none when nothing
/// changes); parts left out copy the Kanji part; they are saved with the document and undone with
/// it.
#[test]
fn composite_fonts_are_set_as_one_undo_step_and_saved() {
let mut s = session();
let before = steps(&s);
let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font(" CF Saved A "), font("CF Saved B")]})).unwrap();
assert_eq!(r["fonts"][0]["name"], "CF Saved A");
assert_eq!(names(&s), ["CF Saved A", "CF Saved B"]);
assert_eq!(steps(&s), before + 1);
let f = &s.doc().unwrap().doc.composite_fonts[0];
assert_eq!((f.parts.kana.font.as_str(), f.parts.roman.size, f.parts.numerals.h_scale), ("Source Sans 3", 50.0, 80.0));
// The same fonts again change nothing.
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Saved A"), font("CF Saved B")]})).unwrap();
assert_eq!(steps(&s), before + 1);
let listed = s.execute("type.compositeFonts.list", &json!({})).unwrap();
assert_eq!(listed["fonts"].as_array().map(Vec::len), Some(2));
// They travel with the file.
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
s.execute("edit.undo", &json!({})).unwrap();
assert!(names(&s).is_empty());
}
/// Bad fonts are refused with an error and no undo step: a name that is empty, shared (in any
/// case) or an installed font's; a part set in a composite font; an unknown class or key; a value
/// out of range, of the wrong type, or on a class that can't take it; no Kanji part.
#[test]
fn bad_composite_fonts_are_refused() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Refused Base")]})).unwrap();
let before = steps(&s);
let with = |f: &dyn Fn(&mut Value)| {
let mut v = font("CF Refused");
f(&mut v);
json!({"fonts": [v]})
};
for bad in [
json!({}),
json!({"fonts": "CF"}),
json!({"fonts": [font(" ")]}),
json!({"fonts": [font("CF Twice"), font("cf twice")]}),
json!({"fonts": [font("Source Sans 3")]}),
json!({"fonts": [font("Tab\tName")]}),
with(&|v| v["parts"]["roman"]["font"] = json!("CF Refused Base")),
with(&|v| v["parts"]["roman"]["font"] = json!("CF Refused")),
with(&|v| v["parts"]["hangul"] = json!({"font": "Inter"})),
with(&|v| v["parts"]["Roman"] = json!({"font": "Inter"})),
with(&|v| v["parts"]["roman"]["width"] = json!(3)),
with(&|v| v["parts"]["roman"]["size"] = json!(5)),
with(&|v| v["parts"]["roman"]["size"] = json!("50")),
with(&|v| v["parts"]["roman"]["baseline"] = json!(-120)),
with(&|v| v["parts"]["kanji"]["hScale"] = json!(90)),
with(&|v| v["parts"]["punctuation"] = json!({"font": "Inter", "vScale": 90})),
with(&|v| v["parts"]["roman"]["scaleAtCenter"] = json!(true)),
with(&|v| v["parts"]["kana"] = json!({"font": "Inter", "scaleAtCenter": "yes"})),
with(&|v| v["parts"]["roman"]["font"] = json!("")),
with(&|v| v["extra"] = json!(1)),
with(&|v| {
v["parts"].as_object_mut().unwrap().remove("kanji");
}),
] {
assert!(s.execute("type.compositeFonts.set", &bad).is_err(), "accepted {bad}");
assert_eq!(names(&s), ["CF Refused Base"]);
assert_eq!(steps(&s), before);
}
// Kana scaled at the center is allowed.
let ok = with(&|v| v["parts"]["kana"] = json!({"font": "Inter", "vScale": 80, "scaleAtCenter": true}));
s.execute("type.compositeFonts.set", &ok).unwrap();
assert_eq!(names(&s), ["CF Refused"]);
}
/// Type set in a composite font names it and is not missing; each class is drawn in its part's
/// font; changing the font measures the type again, and taking it out leaves the type naming it,
/// shown as missing.
#[test]
fn type_set_in_a_composite_font_follows_it() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Type")]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Type"})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
let t = text(&s, id);
assert_eq!(t.runs[0].style.font_family, "CF Type");
let db = vectorcraft_text::FontDb::global();
let face = |family: &str| db.face(family, "Regular").unwrap().id();
let lay = vectorcraft_text::layout(db, &t);
let fonts: Vec<u32> = lay.glyphs.iter().map(|g| g.font_id).collect();
assert_eq!(fonts, [face("JetBrains Mono"), face("JetBrains Mono"), face("Inter"), face("Inter")]);
let missing = |s: &mut Session| s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count();
assert_eq!(missing(&mut s), 0);
// Roman at full size makes the type wider, measured again in the same step.
let wide = t.cached_bounds.unwrap().width();
let mut full = font("CF Type");
full["parts"]["roman"]["size"] = json!(100);
let before = steps(&s);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
assert_eq!(steps(&s), before + 1);
assert!(text(&s, id).cached_bounds.unwrap().width() > wide + 1.0);
s.execute("edit.undo", &json!({})).unwrap();
assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6);
assert_eq!(db.composite_font("CF Type").unwrap().parts.roman.size, 50.0);
// Taken out, the type keeps the name, now missing; undone, the font is back.
s.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
assert!(db.composite_font("CF Type").is_none());
assert_eq!(text(&s, id).runs[0].style.font_family, "CF Type");
assert_eq!(missing(&mut s), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(db.composite_font("CF Type").is_some());
assert_eq!(missing(&mut s), 0);
}
/// Type in a symbol's art is measured again too when the composite font it names changes.
#[test]
fn type_in_symbol_art_follows_its_composite_font() {
fn width(s: &Session) -> f64 {
fn find(n: &vectorcraft_doc::Node) -> Option<f64> {
if let NodeKind::Text(t) = &n.kind {
return t.cached_bounds.map(|b| b.width());
}
n.children().into_iter().flatten().find_map(|c| find(c))
}
s.doc().unwrap().doc.symbols.iter().find_map(|sym| find(&sym.art)).unwrap()
}
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Symbol")]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Symbol"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.new", &json!({"name": "CF Mark", "ids": [id]})).unwrap();
let narrow = width(&s);
let mut full = font("CF Symbol");
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
assert!(width(&s) > narrow + 1.0);
}
/// The font database forgets a composite font once no open document defines it: after the step
/// that added it is undone, and after its document closes.
#[test]
fn composite_fonts_no_document_defines_are_forgotten() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Forgotten Undo")]})).unwrap();
assert!(db.composite_font("CF Forgotten Undo").is_some());
s.execute("edit.undo", &json!({})).unwrap();
assert!(db.composite_font("CF Forgotten Undo").is_none());
s.execute("edit.redo", &json!({})).unwrap();
assert!(db.composite_font("CF Forgotten Undo").is_some());
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Forgotten Close")]})).unwrap();
s.execute("file.close", &json!({})).unwrap();
assert!(db.composite_font("CF Forgotten Close").is_none());
assert!(db.composite_font("CF Forgotten Undo").is_some());
}
/// SVG and legacy `.ai` write type in a composite font as its outlines, since a reader can't find
/// the font by its name.
#[test]
fn exports_outline_type_in_a_composite_font() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Export")]})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab1", "size": 20, "font": "CF Export"})).unwrap();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
assert!(!svg.contains("CF Export") && !svg.contains("<text") && svg.contains("<path"), "{svg}");
let ai = vectorcraft_eps::export_legacy_ai(&s.doc().unwrap().doc, &vectorcraft_eps::LegacyAiOptions::default()).unwrap();
assert!(!String::from_utf8_lossy(&ai.bytes).contains("CF Export"));
}
/// A document exported without a session (whose composite fonts the font database doesn't hold),
/// or while another document defines the name differently, still has its type in a composite font
/// written as outlines, drawn in its own definition's parts: SVG
/// writes the outlines the same type set in the part's font writes, PDF embeds the part's font, and
/// legacy `.ai` doesn't name the composite font.
#[test]
fn exports_draw_composite_fonts_of_a_document_without_a_session() {
let mut s = session();
let mono = json!({"name": "CF Standalone", "parts": {"kanji": {"font": "JetBrains Mono"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [mono]})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab1", "size": 20, "font": "CF Standalone"})).unwrap()["id"].as_u64().unwrap();
let doc = (*s.doc().unwrap().doc).clone();
// The font database forgets the font; the copy of the document still defines it.
s.execute("type.compositeFonts.set", &json!({"fonts": []})).unwrap();
let db = vectorcraft_text::FontDb::global();
assert!(db.composite_font("CF Standalone").is_none());
let paths = |svg: &str| svg.split(" d=\"").skip(1).filter_map(|p| p.split('"').next().map(str::to_string)).collect::<Vec<_>>();
let svg = vectorcraft_svg::export(&doc, &vectorcraft_svg::ExportOptions::default());
assert!(!svg.contains("CF Standalone") && !svg.contains("<text"), "{svg}");
s.execute("text.setStyle", &json!({"ids": [id], "font": "JetBrains Mono"})).unwrap();
let plain = vectorcraft_svg::export(&s.doc().unwrap().doc, &vectorcraft_svg::ExportOptions { outline_text: true, ..Default::default() });
assert!(!paths(&svg).is_empty());
assert_eq!(paths(&svg), paths(&plain));
let pdf = vectorcraft_pdf::export(&doc, &vectorcraft_pdf::PdfOptions::uncompressed()).unwrap();
assert!(String::from_utf8_lossy(&pdf).contains("JetBrainsMono"));
let ai = vectorcraft_eps::export_legacy_ai(&doc, &vectorcraft_eps::LegacyAiOptions::default()).unwrap();
assert!(!String::from_utf8_lossy(&ai.bytes).contains("CF Standalone"));
// The fonts lent for the exports are forgotten again.
assert!(db.composite_font("CF Standalone").is_none());
// With the front document defining the name differently, the exported document's own
// definition draws its type, and the front document's is put back.
let inter = json!({"name": "CF Standalone", "parts": {"kanji": {"font": "Inter"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [inter]})).unwrap();
let svg = vectorcraft_svg::export(&doc, &vectorcraft_svg::ExportOptions::default());
assert_eq!(paths(&svg), paths(&plain));
assert_eq!(db.composite_font("CF Standalone").unwrap().parts.kanji.font, "Inter");
}
/// Replace Font and Replace Missing Fonts set type in a composite font by the font's own name,
/// not its Kanji part's, and keep the type's style.
#[test]
fn replacing_a_font_with_a_composite_font_names_it() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Replace")]})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.replaceFont", &json!({"from": {"family": "Source Serif 4"}, "to": {"family": "cf replace"}})).unwrap();
assert_eq!(r["runs"], 1, "{r}");
assert!(r.get("warning").is_none(), "{r}");
let t = text(&s, id);
assert_eq!((t.runs[0].style.font_family.as_str(), t.runs[0].style.font_style.as_str()), ("CF Replace", "Regular"));
let gone = s
.execute("text.create", &json!({"x": 10, "y": 90, "text": "Lost", "size": 20, "font": "No Such Font Family", "style": "Bold"}))
.unwrap()["id"]
.as_u64()
.unwrap();
let r = s.execute("addon.cleanup.replaceFonts", &json!({"font": "CF Replace"})).unwrap();
assert_eq!((r["runs"].as_u64(), r["font"].as_str()), (Some(1), Some("CF Replace")), "{r}");
let t = text(&s, gone);
assert_eq!((t.runs[0].style.font_family.as_str(), t.runs[0].style.font_style.as_str()), ("CF Replace", "Bold"));
}
/// When a part's font is missing, though the Kanji part's is installed, text.missingFonts names
/// that part's font for type with characters in that part, text.fonts shows the composite font as
/// missing (resolved in the fallback font that draws that part), and setting type in it warns;
/// missingGlyphs counts the characters that the font of their part lacks. Each run is checked on
/// its own, as layout splits it.
#[test]
fn font_inventory_checks_the_part_of_each_character() {
let mut s = session();
let mut f = font("CF Inventory");
f["parts"]["kanji"]["font"] = json!("Source Serif 4");
f["parts"]["roman"]["font"] = json!("No Such Part Font");
s.execute("type.compositeFonts.set", &json!({"fonts": [f]})).unwrap();
// Numerals are drawn in Inter: nothing is missing.
let r = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "12", "size": 20, "font": "CF Inventory"})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
assert_eq!(s.execute("text.missingFonts", &json!({})).unwrap()["count"], 0);
// Roman letters are drawn in the missing font.
let r = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Ab", "size": 20, "font": "CF Inventory"})).unwrap();
assert!(r["warning"].as_str().is_some_and(|w| w.contains("No Such Part Font")), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
let names: Vec<&str> = missing["fonts"].as_array().unwrap().iter().filter_map(|f| f["family"].as_str()).collect();
assert_eq!(names, ["No Such Part Font"], "{missing}");
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let row = fonts.as_array().unwrap().iter().find(|r| r["family"] == "CF Inventory").cloned().unwrap();
assert_eq!((&row["missing"], &row["status"]), (&json!(true), &json!("missing")), "{row}");
assert_eq!(row["resolved"]["family"], vectorcraft_text::FALLBACK_FAMILY, "{row}");
// A run that starts with a combining mark after a run ending in kana: the mark is Roman.
let boundary = json!({"name": "CF Boundary", "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "No Such Part Font"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [boundary]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 170, "text": "\u{304B}\u{301}", "size": 20, "font": "CF Boundary"})).unwrap()["id"]
.as_u64()
.unwrap();
let row =
|s: &mut Session| s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().find(|r| r["family"] == "CF Boundary").cloned();
assert_eq!(row(&mut s).unwrap()["status"], "exact");
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 5, "size": 30})).unwrap();
assert_eq!(text(&s, id).runs.len(), 2);
assert_eq!(row(&mut s).unwrap()["status"], "missing");
// A symbol the Kanji part's font draws but the Symbols part's font lacks.
let db = vectorcraft_text::FontDb::global();
let (mono, sans) = (db.face("JetBrains Mono", "Regular").unwrap(), db.face("Source Sans 3", "Regular").unwrap());
let c = ('\u{2190}'..='\u{2BFF}').find(|c| mono.covers(*c) && !sans.covers(*c)).expect("a symbol only JetBrains Mono draws");
let glyphs = json!({"name": "CF Glyphs", "parts": {"kanji": {"font": "JetBrains Mono"}, "symbols": {"font": "Source Sans 3"}}});
s.execute("type.compositeFonts.set", &json!({"fonts": [glyphs]})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 130, "text": c.to_string(), "size": 20, "font": "CF Glyphs"})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let row = fonts.as_array().unwrap().iter().find(|r| r["family"] == "CF Glyphs").cloned().unwrap();
assert_eq!(row["missingGlyphs"], 1, "{row}");
}
/// The Glyphs panel's alternates of a character in a composite font come from the font of the
/// part its grapheme cluster falls in.
#[test]
fn glyph_alternates_of_composite_type_come_from_the_characters_part() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Glyph Part")]})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Glyph Part"})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 2})).unwrap();
assert_eq!(r["font"], "Inter", "{r}");
let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 0})).unwrap();
assert_eq!(r["font"], "JetBrains Mono", "{r}");
// A combining mark is drawn in the part of the character it follows.
let id = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "1\u{301}", "size": 20, "font": "CF Glyph Part"})).unwrap()["id"]
.as_u64()
.unwrap();
let r = s.execute("text.glyphAlternates", &json!({"id": id, "start": 1})).unwrap();
assert_eq!(r["font"], "Inter", "{r}");
}
/// With two documents defining one name differently, the type is drawn in the front document's.
#[test]
fn the_front_document_defines_a_shared_name() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Front")]})).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let mut other = font("CF Front");
other["parts"]["roman"]["size"] = json!(75);
s.execute("type.compositeFonts.set", &json!({"fonts": [other]})).unwrap();
let db = vectorcraft_text::FontDb::global();
assert_eq!(db.composite_font("CF Front").unwrap().parts.roman.size, 75.0);
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(db.composite_font("CF Front").unwrap().parts.roman.size, 50.0);
}
/// A composite font only a document in the back defines is not available in the front one, where
/// type naming it shows as missing; a click on the back document's tab brings it back.
#[test]
fn a_font_only_a_back_document_defines_is_missing_in_front() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Only")]})).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(db.composite_font("CF Back Only").is_none());
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Back Only"})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
assert!(fonts.as_array().unwrap().iter().any(|f| f["missing"] == true), "{fonts}");
assert!(s.set_active(0));
assert!(db.composite_font("CF Back Only").is_some());
}
/// A newly opened document measures a missing font without using the previous tab's composite
/// font of the same name.
#[test]
fn opened_document_measures_missing_composite_font_as_missing() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Previous Tab")]})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Previous Tab"})).unwrap()["id"].as_u64().unwrap();
let mut doc = (*s.doc().unwrap().doc).clone();
doc.composite_fonts.clear();
if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind {
t.cached_bounds = None;
}
s.add_document(doc, None);
assert!(s.set_active(0));
assert!(s.set_active(1));
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// The native file of a document whose composite font `name` sets Roman at full size, with type
/// "Ab12" set in it → (the file, the type's id, its width).
fn full_roman_file(name: &str) -> (Vec<u8>, u64, f64) {
let mut s = session();
let mut full = font(name);
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": name})).unwrap()["id"].as_u64().unwrap();
let width = text(&s, id).cached_bounds.unwrap().width();
(vectorcraft_format::save_file(&s.doc().unwrap().doc), id, width)
}
/// Type in a missing font that no composite font is named after keeps the bounds it was measured
/// with when its file was read: opening the document does not lay it out again.
#[test]
fn opening_leaves_type_in_an_unrelated_missing_font_as_measured() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Unrelated")]})).unwrap();
let id =
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "No Such Family CF"})).unwrap()["id"].as_u64().unwrap();
let mut doc = (*s.doc().unwrap().doc).clone();
let kept = vectorcraft_geom::Rect::new(1.0, 2.0, 3.0, 4.0);
if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind {
t.cached_bounds = Some(kept);
}
s.add_document(doc, None);
assert_eq!(text(&s, id).cached_bounds, Some(kept));
}
/// Text holding an inline graphic whose symbol's art is type in a composite font is measured with
/// the graphic at the size the opened document's own definition gives it.
#[test]
fn opening_measures_inline_graphics_of_composite_type_in_its_own_definition() {
let mut s = session();
let mut full = font("CF Inline");
full["parts"]["roman"]["size"] = json!(100);
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
let art = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Inline"})).unwrap()["id"].as_u64().unwrap();
s.execute("symbol.new", &json!({"name": "CF Inline Mark", "ids": [art]})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Inline Mark"})).unwrap();
let width = text(&s, id).cached_bounds.unwrap().width();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Inline")]})).unwrap();
let file = crate::cmd::fileio::read_for_open("inline.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
crate::cmd::fileio::open_read(&mut s, file).unwrap();
assert!((text(&s, id).cached_bounds.unwrap().width() - width).abs() < 1e-6);
}
/// Type read for opening while a composite font of its name was registered is measured again when
/// it opens, even after the document that defined the font has closed in between.
#[test]
fn opening_measures_type_read_in_a_composite_font_closed_since() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Gone"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Gone")]})).unwrap();
let file = crate::cmd::fileio::read_for_open("gone.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
assert!(s.close_document(1));
crate::cmd::fileio::open_read(&mut s, file).unwrap();
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// A file read for opening lays out its type in the composite fonts registered then (the front
/// document's, which defines the name with Roman at half size); once the file opens, its type is
/// measured again in its own.
#[test]
fn an_opened_file_measures_its_type_in_its_own_composite_fonts() {
let (bytes, id, width) = full_roman_file("CF Opened");
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Opened")]})).unwrap();
let file = crate::cmd::fileio::read_for_open("opened.vectorcraft", &bytes, None, &json!({}), false, false).unwrap();
crate::cmd::fileio::open_read(&mut s, file).unwrap();
let actual = text(&s, id);
assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// A document replaced while in the back (File › Revert) is measured in its own composite fonts
/// when it comes to the front, not in the front document's.
#[test]
fn a_document_replaced_in_the_back_is_measured_in_its_own_composite_fonts() {
let (bytes, id, width) = full_roman_file("CF Replaced");
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Replaced")]})).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Replaced")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert!(s.set_active(0));
let actual = text(&s, id);
assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// So is one that comes to the front because the front document closes.
#[test]
fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
let (bytes, id, width) = full_roman_file("CF Closed");
let mut s = session();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Closed")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
assert!(s.close_document(1));
let actual = text(&s, id);
assert!((actual.cached_bounds.unwrap().width() - width).abs() < 1e-6);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// A failed batch takes back the composite fonts it set, in the font database too.
#[test]
fn a_failed_batch_takes_back_its_composite_fonts() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
let steps = json!([
{"command": "type.compositeFonts.set", "params": {"fonts": [font("CF Failed Batch")]}},
{"command": "no.such.command"},
]);
assert!(s.execute("command.batch", &json!({"commands": steps})).is_err());
assert!(names(&s).is_empty());
assert!(db.composite_font("CF Failed Batch").is_none());
}
/// A composite font whose edit is refused, because it makes selected type too wide for the canvas,
/// is not left in the font database.
#[test]
fn a_refused_edit_takes_back_its_new_composite_font() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
let x = crate::MAX_COORD - 1000.0;
s.execute("text.create", &json!({"x": x, "y": 50, "text": "MMMMMMMM", "size": 100, "font": "CF Refused Edit"})).unwrap();
let wide = json!({"name": "CF Refused Edit", "parts": {"kanji": {"font": "Source Sans 3", "size": 400}}});
let e = s.execute("type.compositeFonts.set", &json!({"fonts": [wide]})).unwrap_err().to_string();
assert!(e.contains("exceed the canvas"), "{e}");
assert!(names(&s).is_empty());
assert!(db.composite_font("CF Refused Edit").is_none());
}
/// A loaded composite font cannot replace an installed family used by existing type.
#[test]
fn loaded_composite_font_cannot_take_an_installed_family_name() {
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
let mut doc = (*s.doc().unwrap().doc).clone();
doc.composite_fonts.push(vectorcraft_doc::CompositeFont::new("Inter", "Source Sans 3", "Regular"));
if let NodeKind::Text(t) = &mut doc.node_mut(NodeId(id)).unwrap().kind {
t.cached_bounds = None;
}
s.add_document(doc, None);
assert!(names(&s).is_empty());
assert!(vectorcraft_text::FontDb::global().composite_font("Inter").is_none());
let actual = text(&s, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
assert_eq!(actual.cached_bounds, Some(expected));
}
/// A file's composite fonts that Composite Fonts… would refuse (a value out of range, a name used
/// twice) are left out when the file opens.
#[test]
fn unusable_composite_fonts_in_a_file_are_left_out() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
let mut doc = (*s.doc().unwrap().doc).clone();
let mut wild = vectorcraft_doc::CompositeFont::new("CF Wild", "Source Sans 3", "Regular");
wild.parts.roman.size = 5000.0;
let good = vectorcraft_doc::CompositeFont::new("CF Kept", "Source Sans 3", "Regular");
let twice = vectorcraft_doc::CompositeFont::new("cf kept", "Inter", "Regular");
*doc.composite_fonts = vec![wild, good, twice];
s.add_document(doc, None);
assert_eq!(names(&s), ["CF Kept"]);
s.execute("document.activate", &json!({"index": 1})).unwrap();
assert!(db.composite_font("CF Wild").is_none());
assert_eq!(db.composite_font("CF Kept").unwrap().parts.roman.font, "Source Sans 3");
}
/// Export writes the document's composite fonts (all, or those named) to a file; Import reads it:
/// with apply false it only returns them, otherwise they join the document's, replacing a font of
/// the same name, as one undo step.
#[test]
fn composite_fonts_export_and_import() {
let dir = folder("io");
let path = dir.join("Mixed fonts (日本).vccomposite");
let path = path.to_str().unwrap();
let mut s = session();
assert!(s.execute("type.compositeFonts.export", &json!({"path": path})).is_err(), "nothing to export");
let mut slash = font("CF IO a/b: \"quoted\" 日本");
slash["parts"]["kana"] = json!({"font": "Inter", "vScale": 80, "scaleAtCenter": true});
s.execute("type.compositeFonts.set", &json!({"fonts": [slash, font("CF IO Other")]})).unwrap();
assert!(s.execute("type.compositeFonts.export", &json!({"path": path, "names": ["CF IO Nope"]})).is_err());
let r = s
.execute("type.compositeFonts.export", &json!({"path": path, "names": ["cf io a/b: \"quoted\" 日本", "CF IO a/b: \"quoted\" 日本"]}))
.unwrap();
assert_eq!(r["count"], 1);
let saved = s.doc().unwrap().doc.composite_fonts[0].clone();
let mut t = session();
let mut mine = font("CF IO a/b: \"quoted\" 日本");
mine["parts"]["roman"]["size"] = json!(90);
t.execute("type.compositeFonts.set", &json!({"fonts": [mine, font("CF IO Kept")]})).unwrap();
let before = steps(&t);
let read = t.execute("type.compositeFonts.import", &json!({"path": path, "apply": false})).unwrap();
assert_eq!(read["fonts"].as_array().map(Vec::len), Some(1));
assert_eq!(steps(&t), before);
t.execute("type.compositeFonts.import", &json!({"path": path})).unwrap();
assert_eq!(steps(&t), before + 1);
assert_eq!(names(&t), ["CF IO a/b: \"quoted\" 日本", "CF IO Kept"]);
assert_eq!(t.doc().unwrap().doc.composite_fonts[0], saved);
// The same file again changes nothing.
t.execute("type.compositeFonts.import", &json!({"path": path})).unwrap();
assert_eq!(steps(&t), before + 1);
// Files that aren't composite fonts, or are too large, are refused.
for (file, bytes) in [
("bad.vccomposite", b"not json".to_vec()),
("empty.vccomposite", br#"{"compositeFonts": []}"#.to_vec()),
("twice.vccomposite", format!(r#"{{"compositeFonts": [{}, {}]}}"#, font("CF Dup"), font("cf dup")).into_bytes()),
("large.vccomposite", vec![b' '; (4 << 20) + 1]),
] {
let p = dir.join(file);
std::fs::write(&p, bytes).unwrap();
assert!(t.execute("type.compositeFonts.import", &json!({"path": p.to_str().unwrap()})).is_err(), "{file}");
assert_eq!(steps(&t), before + 1);
}
assert!(t.execute("type.compositeFonts.import", &json!({"path": path, "apply": "no"})).is_err());
assert!(t.execute("type.compositeFonts.import", &json!({"path": ""})).is_err());
assert!(t.execute("type.compositeFonts.import", &json!({"path": path, "data": "{}"})).is_err());
assert!(t.execute("type.compositeFonts.import", &json!({"dataBase64": "%%%"})).is_err());
// Without a path, Export gives the file's text, which Import takes as data.
let data = s.execute("type.compositeFonts.export", &json!({"names": ["CF IO Other"]})).unwrap();
assert_eq!(data["count"], 1);
let mut u = session();
let r = u.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap();
assert_eq!(r["imported"], json!(["CF IO Other"]));
assert_eq!(names(&u), ["CF IO Other"]);
// Fonts given are written in place of the document's; bad ones are refused.
let given = s.execute("type.compositeFonts.export", &json!({"fonts": [font("CF IO Given")]})).unwrap();
assert!(given["data"].as_str().unwrap().contains("CF IO Given"));
assert!(s.execute("type.compositeFonts.export", &json!({"fonts": [font("")]})).is_err());
assert!(s.execute("type.compositeFonts.export", &json!({"fonts": []})).is_err());
assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
+3 -3
View File
@@ -189,7 +189,7 @@ fn make(s: &mut Session, p: &Value) -> Result<Value> {
/// that has a shape. A shape taken from inside a group, or from the art of a blend, an envelope or
/// a warped group, also takes that object's opacity and blend mode.
fn top_style(d: &Document, n: &Node, hook: effects::OutlineHook) -> Option<Style> {
if let Some(art) = effects::shape_art(n, Some(hook)) {
if let Some(art) = effects::shape_art(Some(d), n, Some(hook)) {
let mut lv = vec![];
pf_leaves(d, &art, &mut lv);
let inside = matches!(art.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !art.is_compound_shape();
@@ -199,7 +199,7 @@ fn top_style(d: &Document, n: &Node, hook: effects::OutlineHook) -> Option<Style
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } if !n.is_compound_shape() => {
children.iter().rev().find_map(|c| top_style(d, c, hook)).map(|s| s.within(n))
}
NodeKind::SymbolInstance { .. } => effects::member_leaves(n, Some(hook)).last().map(style_of),
NodeKind::SymbolInstance { .. } => effects::member_leaves(Some(d), n, Some(hook)).last().map(style_of),
_ => {
let mut lv = vec![];
pf_leaves(d, n, &mut lv);
@@ -267,7 +267,7 @@ fn expand(s: &mut Session, _: &Value) -> Result<Value> {
for id in &shapes {
let shape = d.node(*id).cloned().ok_or(EngineError::NoNode(*id))?;
let hook = |c: &Node| effects::outline_object(Some(d), c);
let area = effects::compound_shape_area(&shape, Some(&hook))
let area = effects::compound_shape_area(Some(d), &shape, Some(&hook))
.ok_or_else(|| EngineError::Other("the compound shape is too complex to expand".into()))?;
if area.is_empty() {
return Err(EngineError::Other(format!("{LABEL} produced an empty result")));
+1 -1
View File
@@ -743,7 +743,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
if p.get("font").is_some() || p.get("style").is_some() {
let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => t.runs.iter().map(|r| super::fonts::font_of(&r.style)).collect(),
Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(),
_ => Default::default(),
};
if let Some(w) = super::fonts::set_font_warning(runs) {
+3 -2
View File
@@ -283,6 +283,7 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
/// only where an effect gives them a shape.
fn own_patterns<'a>(
d: &Document,
n: &'a Node,
members: &HashSet<*const Node>,
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
@@ -296,7 +297,7 @@ fn own_patterns<'a>(
// The patterns an image's shaped fills and strokes paint (their effects can transform the
// pattern, so they are matched by name).
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| {
vectorcraft_render::effects::image_paint(n)
vectorcraft_render::effects::image_paint(Some(d), n)
.into_iter()
.filter_map(|(_, _, item)| match item.paint() {
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
@@ -415,7 +416,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
// The patterns this object's fills and strokes use, each once.
let mut used_patterns: Vec<&str> = vec![];
let painted_runs = painted_runs(d, n);
for pattern in own_patterns(n, &members, painted_runs.as_ref()) {
for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) {
patterns.insert(pattern.to_string());
used_patterns.push(pattern);
}
+1 -1
View File
@@ -256,7 +256,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Color Mode",
["File", "Document Color Mode"],
None,
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
"{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}",
has_doc,
super::colormgmt::convert_mode
),
+28 -11
View File
@@ -157,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut); refused while an object of a symbol instance's art is selected",
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
has_selection_guides_or_artboard_tool,
cut
),
@@ -166,7 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -794,11 +794,14 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let mut doc = Document::clone(chosen.as_ref().unwrap_or(&st.doc));
let (imported_from, import_losses, opened_by) = (st.imported_from.clone(), st.import_losses.clone(), st.opened_by.clone());
if let Some(path) = st.path.as_deref() {
let base = super::links::LinkBase::of(st);
if base.doc.is_some() {
// Files are looked for within the asking caller's roots, else within those of the caller that opened the source.
let roots = crate::file_access::current().or_else(|| opened_by.clone());
crate::file_access::confine(roots.as_ref(), || super::links::with_found_paths(&mut doc, path));
crate::file_access::confine(roots.as_ref(), || super::links::with_found_paths(&mut doc, base));
}
// The copy's links keep their relative paths, which name places from the same file.
let links_from = base.relative.map(str::to_string);
doc.drop_edit_modes();
if doc.pattern_edit.is_some() {
super::patterncmds::finish_edit(&mut doc, &mut vectorcraft_doc::Selection::default())?;
@@ -815,6 +818,7 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc_mut()?;
st.imported_from = imported_from;
st.import_losses = import_losses;
st.links_from = links_from;
st.opened_by = st.opened_by.take().or(opened_by);
st.mark_unsaved();
Ok(json!({ "index": i, "title": st.title() }))
@@ -942,15 +946,27 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
Ok((direct, roots))
}
/// The params edit.copy and edit.cut pass on to `artboard.copy` and `artboard.cut`.
fn artboard_clipboard_params(p: &Value) -> Value {
p.get("lockedAndHidden").map_or_else(|| json!({}), |v| json!({ "lockedAndHidden": v }))
/// Copy or Cut takes artboards: the Artboard tool is chosen, or the journal recorded the artboards
/// it took then.
fn takes_artboards(s: &Session, p: &Value) -> bool {
s.tool_id() == "artboard" || p.get("selectedArtboards").is_some()
}
/// Copy or Cut of artboards: `selectedArtboards`, `art` and `lockedAndHidden` of `p`, or their
/// defaults from the Artboard tool, which the journal entry records.
fn copy_artboards(s: &mut Session, p: &Value, cut: bool) -> Result<Value> {
let given: serde_json::Map<String, Value> =
["selectedArtboards", "art", "lockedAndHidden"].into_iter().filter_map(|key| p.get(key).map(|v| (key.to_string(), v.clone()))).collect();
let given = Value::Object(given);
super::panelcmds::boards_and_art_noted(s, &given, if cut { "edit.cut" } else { "edit.copy" })?;
super::panelcmds::artboard_copy(s, &given, cut)
}
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
switch_or(p, "art", false, "edit.copy")?;
// The Artboard tool copies its artboard (and the art on it).
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), false);
if takes_artboards(s, p) {
return copy_artboards(s, p, false);
}
// With an object of a dynamic symbol instance's art selected, the instance is copied.
let (direct, targets) = copy_cut_targets(s)?;
@@ -990,8 +1006,9 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
}
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if s.tool_id() == "artboard" {
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), true);
switch_or(p, "art", false, "edit.cut")?;
if takes_artboards(s, p) {
return copy_artboards(s, p, true);
}
refuse_symbol_part(s)?;
// Ruler guides selected on their own: Copy takes them, Clear removes them.
+17 -4
View File
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"3D Lighting Preset",
[],
None,
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index; one undo step → {ids}",
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}",
has_doc,
lighting_preset
),
@@ -505,6 +505,13 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
if !effect.is_some_and(|e| effects::is_three_d(&e.id)) {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
}
// Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options.
if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) {
return Err(bad(
C,
format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0),
));
}
}
let mut options = p.clone();
let map = options.as_object_mut().ok_or_else(|| bad(C, "parameters must be an object"))?;
@@ -516,7 +523,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
/// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
/// fit. → `{ids}`.
/// fit; a hidden one has its given values checked. → `{ids}`.
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.setParams";
let index = index_param(p, "index", C)?;
@@ -574,7 +581,6 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(e) = effect
&& effects::is_three_d(&e.id)
&& visible != Some(false)
{
let to = kind.unwrap_or(&e.id);
let mut prospective =
@@ -582,7 +588,14 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, &params)) {
cur.extend(new);
}
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
if visible != Some(false) {
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
} else {
// Hidden, the effect draws nothing, so its object need not fit. The values given are
// checked, and after a change of 3D type so is every value it keeps.
let checked = if to == e.id { effects::upgrade_params(to, &params) } else { prospective };
effects::validate_three_d_params(to, &checked).map_err(|e| bad(C, e))?;
}
}
}
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
@@ -91,3 +91,27 @@ fn lighting_presets_reject_a_mixed_selection_before_changing_any_effect() {
assert_eq!(s.doc().unwrap().history.undo.len(), history);
assert!(!s.doc().unwrap().is_dirty());
}
#[test]
fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection_unchanged() {
let (mut s, first) = setup("threeD.rotate", Value::Null);
let classic = s.execute("shape.rectangle", &json!({"x":250,"y":100,"width":80,"height":80})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect":"threeD.classicExtrude","item":null,"params":{"surface":"diffuse","lightRotation":40}})).unwrap();
for ids in [vec![classic], vec![first.0, classic]] {
for preset in LIGHTING_PRESETS {
s.doc_mut().unwrap().mark_saved();
let before = s.doc().unwrap().doc.clone();
let history = s.doc().unwrap().history.undo.len();
let p = json!({"ids":ids,"index":0,"item":null,"preset":preset.id});
let err = s.execute("effect.lightingPreset", &p).unwrap_err().to_string();
assert!(err.contains(&format!("object {classic}: Extrude & Bevel (Classic) at index 0 has no lighting presets")), "{err}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), history);
assert!(!s.doc().unwrap().is_dirty());
}
}
// Its lights are set with its own parameters instead.
s.execute("effect.setParams", &json!({"ids":[classic],"index":0,"item":null,"params":{"lightRotation":135,"lightHeight":45}})).unwrap();
let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params;
assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0)));
}
+50
View File
@@ -46,6 +46,56 @@ fn revolve_commands_keep_profile_live_edit_options_expand_and_undo() {
assert_eq!(effects_for_test(&s, id), before);
}
/// `effect.setParams` checks the values it is given for a 3D effect when the same edit hides it:
/// a bad value is refused and the document is left as it was, and good values are stored.
#[test]
fn hiding_a_3d_effect_still_checks_its_new_values() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let rect = |s: &mut Session, x: u32| {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap())
};
let classic = rect(&mut s, 20);
s.execute("effect.apply", &json!({"effect": effects::CLASSIC_EXTRUDE, "ids": [classic.0], "item": null})).unwrap();
let extrude = rect(&mut s, 120);
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [extrude.0], "item": null})).unwrap();
let profile = NodeId(s.execute("path.create", &json!({"d": "M 300 40 L 330 60 L 330 140 L 300 160"})).unwrap()["id"].as_u64().unwrap());
s.execute("effect.apply", &json!({"effect": effects::REVOLVE, "ids": [profile.0], "item": null})).unwrap();
for (id, params, why) in [
(classic, json!({"depth": 2001}), "`depth` must be between 0 and 2000"),
(classic, json!({"surface": "glossy"}), "`surface` must be one of"),
(classic, json!({"bevel": "wavy"}), "bevel must be none or one of"),
(extrude, json!({"lights": []}), "lights must contain one to ten lights"),
(extrude, json!({"lightColor": "red"}), "lightColor must be an opaque RGB color"),
(profile, json!({"edge": "top"}), "Revolve edge must be left or right"),
] {
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"ids": [id.0], "index": 0, "item": null, "params": params, "visible": false});
let e = s.execute("effect.setParams", &p).unwrap_err().to_string();
assert!(e.contains(why), "{params}: {e}");
assert_eq!(s.doc().unwrap().doc, before, "{params}");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{params}");
}
// A hidden switch of 3D type checks the values given with it for the new type.
let before = s.doc().unwrap().doc.clone();
let p = json!({"ids": [extrude.0], "index": 0, "item": null, "threeDType": "inflate", "params": {"lights": []}, "visible": false});
let e = s.execute("effect.setParams", &p).unwrap_err().to_string();
assert!(e.contains("lights must contain one to ten lights"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
// Hiding alone checks nothing.
s.execute("effect.setParams", &json!({"ids": [extrude.0], "index": 0, "item": null, "visible": false})).unwrap();
assert!(!node(&s, extrude).appearance.effects[0].visible);
s.execute("effect.setParams", &json!({"ids": [classic.0], "index": 0, "item": null, "params": {"depth": 2000}, "visible": false})).unwrap();
let e = &node(&s, classic).appearance.effects[0];
assert_eq!((e.params["depth"].as_f64(), e.visible), (Some(2000.0), false));
// A value the effect already holds is not checked again: a key it does not take, as a file
// can carry, does not stop a hidden edit of another value.
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(classic).unwrap().appearance.effects[0].params["extra"] = json!(1);
s.execute("effect.setParams", &json!({"ids": [classic.0], "index": 0, "item": null, "params": {"depth": 10}, "visible": false})).unwrap();
assert_eq!(node(&s, classic).appearance.effects[0].params["depth"].as_f64(), Some(10.0));
}
/// Extrude & Bevel, Inflate and Rotate: applied by command, saved and reopened, edited,
/// exported, expanded and undone; one 3D effect per object.
#[test]
+99 -28
View File
@@ -393,12 +393,21 @@ fn expand_gradient_fills(s: &mut Session, to: GradientTo) -> Result<()> {
/// Path `l` with each gradient fill turned into art, in appearance order: the other items stay
/// on plain copies of the path. The path's geometry effects ([`reshaped`]) and each fill's own
/// ([`fill_shape`]) shape the outline the art fills first, as on the canvas. `None` when no
/// gradient fill can be expanded.
/// gradient fill can be expanded. A path that live-effect plug-ins paint is expanded piece by piece
/// ([`expand_pieces`]).
fn expand_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option<Node> {
if vectorcraft_render::effects::has_painted_effects(l) {
return expand_pieces(d, l, usize::MAX, |d, piece, _| expand_piece_fills(d, piece, to));
}
expand_piece_fills(d, l, to)
}
/// [`expand_fills`] of a path with no live-effect plug-in that paints what it returns.
fn expand_piece_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option<Node> {
if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !l.appearance.items.iter().any(|i| gradient_fill(i).is_some()) {
return None;
}
let reshaped = reshaped(l);
let reshaped = reshaped(d, l);
let l = reshaped.as_ref().unwrap_or(l);
let (path, _) = node_path(l)?;
let bounds = path.bounds()?;
@@ -408,7 +417,7 @@ fn expand_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option<Node> {
for item in &l.appearance.items {
// Items that paint nothing go; a gradient that can't be expanded stays.
let art = gradient_fill(item).and_then(|_| {
let (fl, path, bounds, moved) = fill_shape(l, item, &path, bounds)?;
let (fl, path, bounds, moved) = fill_shape(d, l, item, &path, bounds)?;
let (f, g) = gradient_fill(&moved)?;
gradient_art(d, &fl, &path, bounds, f, g, to)
});
@@ -467,16 +476,57 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
Some(art)
}
/// Path `l`, which live-effect plug-ins paint, as the art the canvas draws
/// ([`reshape`](vectorcraft_render::effects::reshape)) with ids of its own, each piece of the art
/// replaced by what `expand` makes of it (`expand` gets the piece and how many objects it may become;
/// `None` keeps the piece with its own paints). `None` when the art would hold more than `budget`
/// objects or no piece expands.
fn expand_pieces(d: &mut Document, l: &Node, budget: usize, mut expand: impl FnMut(&mut Document, &Node, usize) -> Option<Node>) -> Option<Node> {
let art = vectorcraft_render::effects::reshape(Some(d), l, None)?;
let mut art = d.reid(&art);
art.locked = l.locked;
let mut left = budget.checked_sub(art.count_with_masks())?;
let mut expanded = false;
expand_piece_leaves(d, &mut art, &mut left, &mut expanded, &mut expand);
expanded.then_some(art)
}
/// Replace each path and compound path under `n` (`n` included) by what `expand` makes of it, in
/// paint order. `left` is how many more objects the art may hold, and `expanded` is set when a path
/// is replaced.
fn expand_piece_leaves(
d: &mut Document,
n: &mut Node,
left: &mut usize,
expanded: &mut bool,
expand: &mut impl FnMut(&mut Document, &Node, usize) -> Option<Node>,
) {
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
let room = *left + n.count_with_masks();
if let Some(new) = expand(d, n, room) {
*left = room.saturating_sub(new.count_with_masks());
*n = new;
*expanded = true;
}
return;
}
for c in n.children_mut().into_iter().flatten() {
expand_piece_leaves(d, Arc::make_mut(c), left, expanded, expand);
}
}
/// Path `l` as the canvas paints its fills and strokes: its visible geometry effects applied to its
/// path (a plain path then), and every geometry effect of its own removed. `None` when it has no
/// visible geometry effect.
fn reshaped(l: &Node) -> Option<Node> {
/// visible geometry effect. The swatches and patterns that live-effect plug-ins painting their
/// pieces name are looked up in `doc`. This merges the pieces of such a plug-in into one path, so a
/// path that one paints goes through [`expand_pieces`] instead.
pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> {
use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, is_geometry};
if !has_geometry(&l.appearance.effects) {
return None;
}
let (path, _) = node_path(l)?;
let (g, carry) = apply_geometry_carrying(&l.appearance.effects, &path, path.bounds()?, &GeomContext::of(l));
let (g, carry) = apply_geometry_carrying(&l.appearance.effects, &path, path.bounds()?, &GeomContext { doc: Some(doc), ..GeomContext::of(l) });
let mut m = with_path(l, g);
// Its gradients move with the outline, as the canvas paints them.
if carry.moves(&m.appearance) {
@@ -490,13 +540,19 @@ fn reshaped(l: &Node) -> Option<Node> {
/// outline, box and fill: when the fill has visible geometry effects, `l` with the outline they
/// make of `path` as a plain path, that outline's box, and the fill with its gradient moved along
/// with the outline.
fn fill_shape(l: &Node, item: &AppearanceItem, path: &PathData, bounds: Rect) -> Option<(Node, PathData, Rect, AppearanceItem)> {
pub(crate) fn fill_shape(
doc: &Document,
l: &Node,
item: &AppearanceItem,
path: &PathData,
bounds: Rect,
) -> Option<(Node, PathData, Rect, AppearanceItem)> {
use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry};
if !has_geometry(item.effects()) {
return Some((l.clone(), path.clone(), bounds, item.clone()));
}
// In the fill's context, as drawing runs them: a plug-in effect is told which fill it is on.
let (outline, carry) = apply_geometry_carrying(item.effects(), path, bounds, &GeomContext::of(l).item(item));
let (outline, carry) = apply_geometry_carrying(item.effects(), path, bounds, &GeomContext { doc: Some(doc), ..GeomContext::of(l) }.item(item));
let b = outline.bounds()?;
let mut one = Appearance { items: vec![item.clone()], ..Default::default() };
if carry.moves(&one) {
@@ -698,7 +754,7 @@ fn expand_live_with_transparent_image_patterns(
let Some(n) = d.node(*id) else { continue };
// Random Transform effects take their seed from the ids: bake them first ([`bake_seeded`]),
// and leave the object live when that can't be done.
let Some(mut g) = bake_seeded(&vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue };
let Some(mut g) = bake_seeded(d, &vectorcraft_render::effects::expand_live_deep(Some(d), n)) else { continue };
// An object whose art would take the expanded art past the budget stays live.
let size = g.count_with_masks();
if size > budget - made.get() {
@@ -781,14 +837,23 @@ fn expand_patterns(d: &mut Document, l: &Node) -> Option<Node> {
}
/// [`expand_patterns`] for only the pattern fills `which` picks: the others stay like the other
/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects.
/// items, as does a pattern fill whose tiles would take the tiles of `l` past `budget` objects. A
/// path that live-effect plug-ins paint is expanded piece by piece ([`expand_pieces`]).
fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option<Node> {
if vectorcraft_render::effects::has_painted_effects(l) {
return expand_pieces(d, l, budget, |d, piece, room| expand_piece_patterns(d, piece, &which, room));
}
expand_piece_patterns(d, l, which, budget)
}
/// [`expand_patterns_where`] of a path with no live-effect plug-in that paints what it returns.
fn expand_piece_patterns(d: &mut Document, l: &Node, which: impl Fn(&Document, &AppearanceItem) -> bool, budget: usize) -> Option<Node> {
if !matches!(l.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|| !l.appearance.items.iter().any(|i| pattern_fill(d, i).is_some() && which(d, i))
{
return None;
}
let reshaped = reshaped(l);
let reshaped = reshaped(d, l);
let l = reshaped.as_ref().unwrap_or(l);
let (path, _) = node_path(l)?;
let bounds = path.bounds()?;
@@ -820,7 +885,7 @@ fn expand_patterns_where(d: &mut Document, l: &Node, which: impl Fn(&Document, &
later -= usize::from(fill.is_some());
let room = if later > 0 { left.saturating_sub(l.count() + 1) } else { left };
let tiles = fill.filter(|_| !full).and_then(|(f, def, xf)| {
let (fl, _, bounds, _) = fill_shape(l, item, &path, bounds)?;
let (fl, _, bounds, _) = fill_shape(d, l, item, &path, bounds)?;
let Some(t) = pattern_tiles(d, &def, xf, bounds, room) else {
full = true;
return None;
@@ -867,7 +932,7 @@ fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, b
if !moves_only(xf) && def.art.iter().any(|a| has_instances(a)) {
return Some(vec![]);
}
let Some(def) = seeds_baked(def) else {
let Some(def) = seeds_baked(d, def) else {
return Some(vec![]);
};
let brushes = vectorcraft_brush::library(d);
@@ -900,13 +965,14 @@ fn pattern_tiles(d: &mut Document, def: &PatternDef, xf: Affine, bounds: Rect, b
/// effect baked into filled art ([`bake_appearance`](vectorcraft_render::effects::bake_appearance))
/// while it keeps its own id: the effect takes its seed from the id, and the canvas draws the art
/// with those ids for every tile, while the tiles get ids of their own. `None` when something
/// other than a path has such an effect.
fn seeds_baked(def: &PatternDef) -> Option<std::borrow::Cow<'_, PatternDef>> {
/// other than a path has such an effect. The swatches and patterns that live-effect plug-ins
/// painting their pieces name are looked up in `d`.
fn seeds_baked<'a>(d: &Document, def: &'a PatternDef) -> Option<std::borrow::Cow<'a, PatternDef>> {
if !def.art.iter().any(|a| has_seeded(a)) {
return Some(std::borrow::Cow::Borrowed(def));
}
let mut def = def.clone();
def.art = def.art.iter().map(|a| bake_seeded(a).map(Arc::new)).collect::<Option<_>>()?;
def.art = def.art.iter().map(|a| bake_seeded(d, a).map(Arc::new)).collect::<Option<_>>()?;
Some(std::borrow::Cow::Owned(def))
}
@@ -996,10 +1062,13 @@ fn moves_only(a: Affine) -> bool {
(m0 - 1.0).abs() <= eps && m1.abs() <= eps && m2.abs() <= eps && (m3 - 1.0).abs() <= eps
}
/// Is `e` a visible Transform effect with Random on (which takes its seed from the object's id)?
pub(crate) fn seeded(e: &vectorcraft_doc::Effect) -> bool {
e.visible && e.id == "distort.transform" && e.params.get("random").and_then(Value::as_bool) == Some(true)
}
/// Does `n` have a visible Transform effect with Random on, its own or a fill's or stroke's?
fn seeded_here(n: &Node) -> bool {
let seeded =
|e: &vectorcraft_doc::Effect| e.visible && e.id == "distort.transform" && e.params.get("random").and_then(Value::as_bool) == Some(true);
n.appearance.effects.iter().any(seeded) || n.appearance.items.iter().any(|i| i.effects().iter().any(seeded))
}
@@ -1012,8 +1081,9 @@ pub(crate) fn has_seeded(n: &Node) -> bool {
}
/// `n` with the paths in it that have a random Transform effect baked ([`seeds_baked`]). `None`
/// when something else has one.
fn bake_seeded(n: &Node) -> Option<Node> {
/// when something else has one. The swatches and patterns that live-effect plug-ins painting their
/// pieces name are looked up in `d`.
fn bake_seeded(d: &Document, n: &Node) -> Option<Node> {
if !has_seeded(n) {
return Some(n.clone());
}
@@ -1021,17 +1091,17 @@ fn bake_seeded(n: &Node) -> Option<Node> {
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
return None;
}
vectorcraft_render::effects::bake_appearance(n)?
vectorcraft_render::effects::bake_appearance(Some(d), n)?
} else {
n.clone()
};
if !matches!(n.kind, NodeKind::Compound { .. }) {
for c in n.children_mut().into_iter().flatten() {
*c = Arc::new(bake_seeded(c)?);
*c = Arc::new(bake_seeded(d, c)?);
}
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
m.art = Arc::new(bake_seeded(&m.art)?);
m.art = Arc::new(bake_seeded(d, &m.art)?);
}
Some(n)
}
@@ -1052,7 +1122,7 @@ fn has_unbakeable_effects(n: &Node) -> bool {
/// paths baked ([`baked`], [`outline_brushed`]) and its live shapes turned into plain paths (a
/// stretch would rebuild their corners round), in its opacity masks too.
fn prepared(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &Node) -> Node {
let mut t = baked(n);
let mut t = baked(d, n);
outline_brushed(d, brushes, &mut t);
drop_live(&mut t);
prepare_masks(d, brushes, &mut t);
@@ -1093,14 +1163,15 @@ fn scales_evenly(a: Affine) -> bool {
}
/// `n` with the strokes and geometry effects of each path in it baked into filled art
/// ([`bake_appearance`](vectorcraft_render::effects::bake_appearance)).
fn baked(n: &Node) -> Node {
if let Some(b) = vectorcraft_render::effects::bake_appearance(n) {
/// ([`bake_appearance`](vectorcraft_render::effects::bake_appearance)), with the swatches and
/// patterns that live-effect plug-ins painting their pieces name looked up in `d`.
fn baked(d: &Document, n: &Node) -> Node {
if let Some(b) = vectorcraft_render::effects::bake_appearance(Some(d), n) {
return b;
}
let mut n = n.clone();
for c in n.children_mut().into_iter().flatten() {
*c = Arc::new(baked(c));
*c = Arc::new(baked(d, c));
}
n
}
+15 -7
View File
@@ -17,6 +17,8 @@
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
//! - `metafile`: EMF and WMF export, open and place.
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
//! built-in format reads).
//! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`).
//!
//! [`FORMATS`] is the single list of formats (append-only); open dialogs use [`open_filters`],
@@ -31,6 +33,8 @@ mod encode;
pub mod eps;
mod export;
pub(crate) mod imagemap;
mod importer;
pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
@@ -89,16 +93,17 @@ pub use save::{
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
templates_folder,
};
pub(crate) use screens::{
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
};
pub use screens::{
PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS,
PRESETS as SCREEN_PRESETS, SHARED_KEYS as SCREEN_SETTINGS_KEYS, ScreenExport, ScreenExportPreset, ScreenSize,
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
preset_rows as screen_preset_rows,
};
pub(crate) use screens::{
check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings,
with_export_preset as with_screen_export_preset,
};
pub use svg::options_map as svg_options;
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
/// file it replaces), for the apps' own writers too.
@@ -135,9 +140,10 @@ pub(crate) use export_names::{
use export_names::{distinct_names_by, write_encoded};
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
pub use formats::{
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, export_extensions, extension,
file_stem, format, format_for_name, has_own_title, library_open_filters, open_filters, place_filters, plugin_formats, read_extensions,
readable_format, readable_format_for_name, titled_for_export, writable_format,
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
open_filters, opens_as_other, opens_with_importer, place_filters, plugin_formats, read_extensions, readable_format, readable_format_for_name,
titled_for_export, writable_format,
};
#[cfg(test)]
@@ -203,6 +209,8 @@ mod tests_pdfoutput;
#[cfg(test)]
mod tests_tiffbmp;
#[cfg(test)]
mod tests_jxlread;
#[cfg(test)]
mod tests_pdfx;
#[cfg(test)]
+480 -32
View File
@@ -120,7 +120,7 @@ const ONE_FILE_WARNING: &str = "each data set saves over the same file, which ke
/// `path`; a Save step without a `path` when the document has a file of its own (saved, and not
/// converted from an older version or restored by Data Recovery) and the step gives no `format` or
/// the document's own; an Export for Screens step whose `folder`, given or from its
/// `exportPreset`, names a folder, whatever the overrides.
/// `exportPreset`, names a folder, when Override Export does not give each data set its own folder.
/// Other steps return their data instead of writing a file.
pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
if p.get("source").and_then(Value::as_str) != Some("datasets") {
@@ -150,8 +150,8 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
"document.export" | "document.exportSelection" => !export && path,
// The batch does not point these exports into `destinationFolder`.
"document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path,
// Override Export sets `path`, which Export for Screens does not read: its `folder` stays.
"document.exportForScreens" => super::screens::with_preset(s, &params).is_ok_and(|p| names(p.get("folder"))),
// Override Export gives Export for Screens a folder for each data set; otherwise its `folder` stays.
"document.exportForScreens" => !export && super::screens::with_preset(s, &params).is_ok_and(|p| names(p.get("folder"))),
_ => false,
}
})
@@ -196,14 +196,29 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
if files.is_empty() {
return Err(bad(cmd, "no readable files in the folder"));
}
// Each file's name without its extension, through [`source_stem`] (`a..svg` gives `a`, the
// folder Windows makes for `a.`, and `a\b.svg` keeps `a\b` where `\` is not a separator), with
// `-2`, `-3`… after a name an earlier file used (`a.svg` and `sub/a.svg`, or `a.svg` and `a.ai`) or after a name whose files or folder an earlier file
// wrote ([`StemPicker`]), as data set names are numbered. A file's stem is picked once it is
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
// source file in the destination folder, other than that file's own output, or of a subfolder
// of the destination folder that holds source files.
let steps = filter_steps(run.steps, override_open, false);
let run = Run { steps: &steps, ..*run };
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
let mut picker =
StemPicker { stems: std::collections::HashSet::new(), written: in_dest.iter().flatten().map(|(name, _)| name.clone()).collect() };
let mut processed = Vec::new();
let mut failed = 0usize;
for path in &files {
let stem = std::path::Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("file");
for (path, place) in files.iter().zip(&in_dest) {
let ext = super::extension(path);
match process_one_file(s, &run, path, stem, &ext) {
let base = source_stem(std::path::Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or(""));
let own = place.as_ref().filter(|(_, own)| *own).map(|(name, _)| name.clone());
let pick = |doc: &vectorcraft_doc::Document| {
let outputs = dataset_output_extensions(&run, doc, &ext);
picker.pick(&base, |stem| output_names(run.dest_folder, stem, &outputs, doc), own.as_deref())
};
match process_one_file(s, &run, path, &ext, pick) {
Ok(row) => processed.push(row),
Err(e) => {
failed += 1;
@@ -260,6 +275,68 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
Ok(json!({"processed": processed, "count": processed.len(), "failed": failed, "stopped": false}))
}
/// The output stem for a source file's name without its extension: without trailing periods and
/// spaces and with `-` after a Windows device name ([`super::screens::name_without_device`]), and
/// "file" when nothing is left. Other characters stay, so `a\b` and `a:b` keep their names on Linux
/// and macOS.
#[cfg(not(target_arch = "wasm32"))]
fn source_stem(stem: &str) -> String {
let stem = super::screens::name_without_device(stem);
if stem.is_empty() { "file".to_string() } else { stem }
}
/// The names in lower case of the files and folders that a source with the stem `stem` writes
/// into the destination folder ([`dataset_output_paths`]), artboard files included.
#[cfg(not(target_arch = "wasm32"))]
fn output_names(folder: Option<&str>, stem: &str, outputs: &[DatasetOutput], doc: &vectorcraft_doc::Document) -> Vec<String> {
dataset_output_paths(folder, stem, outputs, doc)
.iter()
.filter_map(|path| path.file_name().and_then(|name| name.to_str()).map(str::to_lowercase))
.collect()
}
/// When the file at `path` is inside `folder`: the name in lower case of the file, when it is
/// directly inside, or of the subfolder of `folder` that holds it, and whether it is the file's own.
#[cfg(not(target_arch = "wasm32"))]
fn name_in_folder(path: &str, folder: Option<&str>) -> Option<(String, bool)> {
let folder = std::fs::canonicalize(folder?).ok()?;
let path = std::fs::canonicalize(path).ok()?;
let mut parts = path.strip_prefix(&folder).ok()?.components();
let first = parts.next()?.as_os_str().to_str()?.to_lowercase();
Some((first, parts.next().is_none()))
}
/// Picks the stem of each folder source in turn: its name, with `-2`, `-3`… after it when an
/// earlier source used it or when one of the files or the folder it writes has the name of a file
/// or folder an earlier source wrote (`a.svg` writes the file `a.svg`, so the Export for Screens
/// folder of `a.svg.svg` is `a.svg-2`) or a name in `written` from the start (the source files and
/// subfolders in the destination folder) other than its own file's. Names are compared without case.
#[cfg(not(target_arch = "wasm32"))]
struct StemPicker {
stems: std::collections::HashSet<String>,
written: std::collections::HashSet<String>,
}
#[cfg(not(target_arch = "wasm32"))]
impl StemPicker {
/// `names` gives the names in lower case of what a stem writes; `own` is the source's own name.
fn pick(&mut self, base: &str, names: impl Fn(&str) -> Vec<String>, own: Option<&str>) -> String {
let mut name = base.to_string();
let mut n = 1usize;
loop {
let lower = name.to_lowercase();
let outputs = names(&name);
if !self.stems.contains(&lower) && outputs.iter().all(|f| !self.written.contains(f) || own == Some(f.as_str())) {
self.stems.insert(lower);
self.written.extend(outputs);
return name;
}
n += 1;
name = format!("{base}-{n}");
}
}
}
/// Drop Open (and optionally Close) steps when the batch supplies the file itself.
#[cfg(not(target_arch = "wasm32"))]
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value> {
@@ -279,12 +356,19 @@ fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value>
}
#[cfg(not(target_arch = "wasm32"))]
fn process_one_file(s: &mut Session, run: &Run<'_>, path: &str, stem: &str, ext: &str) -> Result<Value> {
fn process_one_file(
s: &mut Session,
run: &Run<'_>,
path: &str,
ext: &str,
stem_for: impl FnOnce(&vectorcraft_doc::Document) -> String,
) -> Result<Value> {
s.execute("document.open", &json!({"path": path}))?;
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, stem, ext);
let stem = stem_for(&s.doc()?.doc);
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, &stem, ext);
let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?;
// Folder sources open a file per pass: close after Save and Close / Folder.
finish_destination(s, run, stem, ext, path, true)?;
finish_destination(s, run, &stem, ext, path, true)?;
Ok(json!({"path": path, "result": batch}))
}
@@ -349,10 +433,12 @@ fn dataset_stems(names: &[String], doc_stem: &str, naming: &str, run: &Run<'_>,
"fileNumber" => ordinal,
"dataSetName" if !safe_data_set.is_empty() => safe_data_set,
"dataSetName" => ordinal,
_ => format!("{doc_stem}_{safe}"),
// Without trailing periods and spaces, which Windows drops from a folder name, so the
// Export for Screens folders of `Set.` and `Set` are numbered apart.
_ => safe_file_name(&format!("{doc_stem}_{safe}")),
}
});
let outputs = dataset_output_extensions(run, doc);
let outputs = dataset_output_extensions(run, doc, "vectorcraft");
let mut taken = std::collections::HashSet::new();
let mut reserved = std::collections::HashSet::new();
let mut stems = Vec::with_capacity(bases.len());
@@ -384,30 +470,39 @@ struct DatasetOutput {
ext: String,
artboards: bool,
joiner: &'static str,
/// An Export for Screens or Export Assets step writes into the folder `{stem}` instead.
folder: bool,
}
/// Lists step output extensions and reserves artboard file names for saves with any artboard or
/// exports with multiple artboards. Per-artboard names count for vectorcraft, template, AI and AIT
/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports.
/// saves and SVG, SVGZ, EPS, raster, DXF, EMF, WMF and AI exports. An Export for Screens or Export
/// Assets step reserves the folder `{stem}` ([`rewrite_paths`]). A step without a format and the
/// Folder destination write `default_ext` (`vectorcraft` when it is empty).
#[cfg(not(target_arch = "wasm32"))]
fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) -> Vec<DatasetOutput> {
fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, default_ext: &str) -> Vec<DatasetOutput> {
let default_ext = if default_ext.is_empty() { "vectorcraft" } else { default_ext };
let mut outputs = Vec::new();
if run.destination == "folder" {
outputs.push(DatasetOutput { ext: "vectorcraft".into(), artboards: false, joiner: "-" });
outputs.push(DatasetOutput { ext: default_ext.into(), artboards: false, joiner: "-", folder: false });
}
for step in run.steps {
let id = step.get("command").and_then(Value::as_str).unwrap_or("");
if run.override_export && matches!(id, "document.exportForScreens" | "assets.export") {
outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true });
continue;
}
let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
|| (run.override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection"));
|| (run.override_export && matches!(id, "document.export" | "document.exportSelection"));
if writes {
let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty());
let ext = match format {
Some(format) if super::format(format).is_some() => format_extension(format),
Some(_) => continue,
None => "vectorcraft".to_string(),
None => default_ext.to_string(),
};
if safe_extension(&ext) {
let format_id = format.and_then(super::format).map(|f| f.id).unwrap_or("vectorcraft");
let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft");
let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs");
let artboards = if is_save {
!doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait")
@@ -434,7 +529,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document) ->
| "ai"
)
};
outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" } });
outputs.push(DatasetOutput { ext, artboards, joiner: if format_id == "eps" { "_" } else { "-" }, folder: false });
}
}
}
@@ -463,6 +558,10 @@ fn dataset_output_paths(folder: Option<&str>, stem: &str, outputs: &[DatasetOutp
}
let mut paths = Vec::new();
for output in outputs {
if output.folder {
paths.extend(output_folder(folder, stem));
continue;
}
if !safe_extension(&output.ext) || super::format(&output.ext).is_none() {
continue;
}
@@ -497,6 +596,18 @@ fn output_path(folder: &str, stem: &str, ext: &str) -> Option<std::path::PathBuf
(path.parent() == Some(Path::new(folder))).then_some(path)
}
/// Returns the folder `stem` directly inside the destination folder, where an Export for Screens or
/// Export Assets step writes, for a safe stem.
#[cfg(not(target_arch = "wasm32"))]
fn output_folder(folder: &str, stem: &str) -> Option<std::path::PathBuf> {
use std::path::Path;
if stem.is_empty() || matches!(stem, "." | "..") || stem.contains(std::path::is_separator) {
return None;
}
let path = Path::new(folder).join(stem);
(path.parent() == Some(Path::new(folder))).then_some(path)
}
/// Save when the extension is a Save format; otherwise export (PNG, JPEG…).
/// `as_copy`: `file.saveCopy` so the open document keeps its path (data-set batches).
#[cfg(not(target_arch = "wasm32"))]
@@ -513,7 +624,9 @@ fn write_result(s: &mut Session, path: &str, ext: &str, as_copy: bool) -> Result
}
/// Point Save / Export steps at `dest_folder/{stem}.{ext}` when overrides are on: `ext` is the
/// extension of the step's `format` ([`format_extension`]), else `default_ext`.
/// extension of the step's `format` ([`format_extension`]), else `default_ext`. Export for Screens
/// and Export Assets steps get `dest_folder/{stem}` as their `folder`, one folder for each source
/// file or data set, and name the files in it themselves.
#[cfg(not(target_arch = "wasm32"))]
fn rewrite_paths(
steps: &[Value],
@@ -532,21 +645,26 @@ fn rewrite_paths(
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
let mut c = c.clone();
let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs"))
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection"));
|| (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export"));
if !rewrite {
return c;
}
let params = c.get("params").cloned().unwrap_or(json!({}));
let mut params = params.as_object().cloned().unwrap_or_default();
let ext = match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) {
Some(f) => format_extension(f),
None => default_ext.to_string(),
};
if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) {
return c;
if matches!(id, "document.exportForScreens" | "assets.export") {
let Some(dir) = output_folder(folder, stem) else { return c };
params.insert("folder".into(), json!(dir.to_string_lossy()));
} else {
let ext = match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) {
Some(f) => format_extension(f),
None => default_ext.to_string(),
};
if params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()).is_some_and(|f| super::format(f).is_none()) {
return c;
}
let Some(file) = output_path(folder, stem, &ext) else { return c };
params.insert("path".into(), json!(file.to_string_lossy()));
}
let Some(file) = output_path(folder, stem, &ext) else { return c };
params.insert("path".into(), json!(file.to_string_lossy()));
if let Some(o) = c.as_object_mut() {
o.insert("params".into(), Value::Object(params));
}
@@ -610,12 +728,12 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve
#[cfg(not(target_arch = "wasm32"))]
fn is_openable(path: &str) -> bool {
use super::{FORMATS, OPEN_EXTS, extension};
use super::{FORMATS, extension, open_extensions};
let ext = extension(path);
if ext.is_empty() {
return false;
}
OPEN_EXTS.iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext))
open_extensions().iter().any(|e| *e == ext) || FORMATS.iter().any(|f| f.read && f.extensions.iter().any(|e| *e == ext))
}
#[cfg(test)]
@@ -723,6 +841,15 @@ mod tests {
assert_eq!(file_names(&dest), ["a\\b.svg"], "{r}");
}
/// A source stem keeps `\`, `:` and the other characters Windows does not allow in a name, which
/// only reach the batch where the file system allows them, and loses trailing periods and spaces.
#[test]
fn source_stem_keeps_characters_the_file_system_allowed() {
for (stem, want) in [("a\\b", "a\\b"), ("a:b", "a:b"), ("a.", "a"), ("a. ", "a"), ("CON", "CON-"), ("...", "file"), ("", "file")] {
assert_eq!(source_stem(stem), want, "{stem:?}");
}
}
#[test]
fn output_path_accepts_only_platform_file_name_separators() {
let folder = tmp("output-path");
@@ -806,6 +933,319 @@ mod tests {
assert!(file_names(&dest).is_empty(), "{r}");
}
/// Override Export writes an Export for Screens step's files into a folder for each source file
/// inside the destination folder, under the names the export gives them, whether the step names
/// a folder of its own, takes one from an export preset or names none. With Override Export off,
/// the files go to the step's folder.
#[test]
fn batch_override_export_sends_export_for_screens_files_to_the_destination_folder() {
let src = tmp("screens-src");
write_svg(&src, "a.svg", "#f00");
write_svg(&src, "b.svg", "#0f0");
let own = tmp("screens-own");
let svg = json!([{"format": "svg"}]);
let preset = json!({"name": "Own Folder", "settings": {"formats": svg, "folder": own.to_string_lossy()}});
let steps = [json!({"folder": own.to_string_lossy(), "formats": svg}), json!({"exportPreset": "Own Folder"}), json!({"formats": svg})];
for (i, params) in steps.into_iter().enumerate() {
let dest = tmp(&format!("screens-out-{i}"));
let mut s = Session::new();
s.execute("document.exportPresets.save", &preset).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.exportForScreens", "params": params}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{params}: {r}");
assert_eq!(file_names(&dest), ["a", "b"], "{params}: {r}");
for stem in ["a", "b"] {
assert_eq!(file_names(&dest.join(stem)), ["Artboard-1.svg"], "{params}: {r}");
}
assert!(file_names(&own).is_empty(), "{params}: {r}");
}
let dest = tmp("screens-out-off");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destinationFolder": dest.to_string_lossy(),
"overrideExport": false,
"commands": [{"command": "document.exportForScreens", "params": {"folder": own.to_string_lossy(), "formats": svg}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&own), ["Artboard-1.svg"], "{r}");
assert!(file_names(&dest).is_empty(), "{r}");
}
/// Two source files with the same name in different subfolders get Export for Screens folders of
/// their own: the second one's folder is numbered, as a repeated data set name is.
#[test]
fn batch_override_export_numbers_export_for_screens_folders_of_files_with_the_same_name() {
let src = tmp("screens-same-src");
std::fs::create_dir_all(src.join("sub")).unwrap();
write_svg(&src, "a.svg", "#f00");
write_svg(&src.join("sub"), "a.svg", "#0f0");
let dest = tmp("screens-same-out");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"includeSubdirs": true,
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
for folder in file_names(&dest) {
println!("{folder}/: {:?}", file_names(&dest.join(&folder)));
}
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["a", "a-2"], "{r}");
for (folder, fill) in [("a", "#ff0000"), ("a-2", "#00ff00")] {
assert_eq!(file_names(&dest.join(folder)), ["Artboard-1.svg"], "{r}");
let svg = std::fs::read_to_string(dest.join(folder).join("Artboard-1.svg")).unwrap();
assert!(svg.contains(fill), "{folder}: {svg}");
}
}
/// A source file whose name without its extension ends in a period (`a..svg`) gets the folder
/// name without it, numbered after the folder of `a.svg`: Windows drops the period from a folder
/// name, so `a.` and `a` would be one folder there.
#[test]
fn batch_override_export_numbers_folders_that_differ_by_a_trailing_period() {
let src = tmp("screens-period-src");
write_svg(&src, "a.svg", "#f00");
write_svg(&src, "a..svg", "#0f0");
let dest = tmp("screens-period-out");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["a", "a-2"], "{r}");
for folder in ["a", "a-2"] {
assert_eq!(file_names(&dest.join(folder)), ["Artboard-1.svg"], "{r}");
}
}
/// A source file's Export for Screens folder does not take the name of a file the Folder
/// destination saved for an earlier source: `a.svg` is saved as `a.svg`, so the folder of
/// `a.svg.svg` is numbered.
#[test]
fn batch_override_export_numbers_folders_named_like_a_saved_file() {
let src = tmp("screens-file-src");
write_svg(&src, "a.svg", "#f00");
write_svg(&src, "a.svg.svg", "#0f0");
let dest = tmp("screens-file-out");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destination": "folder",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["a", "a.svg", "a.svg-2", "a.svg-2.svg"], "{r}");
for folder in ["a", "a.svg-2"] {
assert_eq!(file_names(&dest.join(folder)), ["Artboard-1.svg"], "{r}");
}
}
/// With the destination folder the same as the source folder, a file's output does not replace
/// another source file before Batch opens it: `a..svg` would be saved as `a.svg`, so it is saved
/// as `a-2.svg`, and `a.svg` is saved over itself.
#[test]
fn batch_does_not_save_over_another_source_file_in_the_destination_folder() {
let src = tmp("in-place");
write_svg(&src, "a..svg", "#f00");
write_svg(&src, "a.svg", "#0f0");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destination": "folder",
"destinationFolder": src.to_string_lossy(),
"commands": [{"command": "object.unlockAll", "params": {}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&src), ["a-2.svg", "a..svg", "a.svg"], "{r}");
for (file, fill) in [("a-2.svg", "#ff0000"), ("a.svg", "#00ff00")] {
let svg = std::fs::read_to_string(src.join(file)).unwrap();
assert!(svg.contains(fill), "{file}: {svg}");
}
}
/// With the destination folder the same as the source folder and `includeSubdirs`, an Export for
/// Screens folder does not take the name of a subfolder that holds source files: the folder of
/// `a.svg` is `a-2`, so `a/Artboard-1.svg` is opened as it was.
#[test]
fn batch_does_not_export_into_a_source_subfolder() {
let src = tmp("in-place-sub");
std::fs::create_dir_all(src.join("a")).unwrap();
write_svg(&src, "a.svg", "#f00");
write_svg(&src.join("a"), "Artboard-1.svg", "#0f0");
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"includeSubdirs": true,
"destinationFolder": src.to_string_lossy(),
"commands": [{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
let source = std::fs::read_to_string(src.join("a").join("Artboard-1.svg")).unwrap();
assert!(source.contains("fill=\"#0f0\""), "{r}: {source}");
let export = std::fs::read_to_string(src.join("a-2").join("Artboard-1.svg")).unwrap();
assert!(export.contains("#ff0000"), "{r}: {export}");
}
/// With the destination folder the same as the source folder, a save's artboard files do not
/// replace another source file: `a.vectorcraft` would also write `a-Artboard-1.vectorcraft`, so
/// it is saved as `a-2`.
#[test]
fn batch_does_not_save_artboard_files_over_another_source_file() {
let src = tmp("in-place-artboards");
let mut s = Session::new();
for (name, width) in [("a.vectorcraft", 20), ("a-Artboard-1.vectorcraft", 30)] {
s.execute("file.new", &json!({"width": width, "height": 20, "artboards": 1})).unwrap();
s.execute("document.save", &json!({"path": src.join(name).to_string_lossy()})).unwrap();
}
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destinationFolder": src.to_string_lossy(),
"commands": [{"command": "document.save", "params": {"separateArtboards": true}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(
file_names(&src),
["a-2-Artboard-1.vectorcraft", "a-2.vectorcraft", "a-Artboard-1-Artboard-1.vectorcraft", "a-Artboard-1.vectorcraft", "a.vectorcraft"],
"{r}"
);
s.execute("document.open", &json!({"path": src.join("a-Artboard-1.vectorcraft").to_string_lossy()})).unwrap();
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 30.0, "{r}");
}
/// Data sets whose names differ only by a trailing period (`a` and `a.`) get Export Assets
/// folders of their own: the second one's folder is numbered.
#[test]
fn batch_override_export_numbers_data_set_folders_that_differ_by_a_trailing_period() {
let dest = tmp("assets-period-out");
let mut s = with_data_sets(&["a", "a."]);
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("assets.add", &json!({"ids": [id], "name": "Logo"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "assets.export", "params": {"formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["Untitled_a", "Untitled_a-2"], "{r}");
for folder in ["Untitled_a", "Untitled_a-2"] {
assert_eq!(file_names(&dest.join(folder)), ["Logo.svg"], "{r}");
}
}
/// Two source files with the same name in different subfolders are saved under names of their
/// own, by Override Save and by the Folder destination: the second one's name is numbered.
#[test]
fn batch_numbers_saved_files_of_source_files_with_the_same_name() {
let src = tmp("save-same-src");
std::fs::create_dir_all(src.join("sub")).unwrap();
write_svg(&src, "a.svg", "#f00");
write_svg(&src.join("sub"), "a.svg", "#0f0");
let save = json!([{"command": "file.saveAs", "params": {"format": "svg"}}]);
let unlock = json!([{"command": "object.unlockAll", "params": {}}]);
for (tag, destination, commands) in [("save", "none", save), ("folder", "folder", unlock)] {
let dest = tmp(&format!("save-same-{tag}"));
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"includeSubdirs": true,
"destination": destination,
"destinationFolder": dest.to_string_lossy(),
"commands": commands
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{tag}: {r}");
assert_eq!(file_names(&dest), ["a-2.svg", "a.svg"], "{tag}: {r}");
for (file, fill) in [("a.svg", "#ff0000"), ("a-2.svg", "#00ff00")] {
let svg = std::fs::read_to_string(dest.join(file)).unwrap();
assert!(svg.contains(fill), "{tag}: {file}: {svg}");
}
}
}
/// Override Export writes an Export Assets step's files into a folder for each data set inside
/// the destination folder, under the assets' names.
#[test]
fn batch_override_export_sends_asset_export_files_to_the_destination_folder() {
let own = tmp("assets-own");
let dest = tmp("assets-out");
let mut s = with_data_sets(&["a", "b"]);
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("assets.add", &json!({"ids": [id], "name": "Logo"})).unwrap();
let r = s
.execute(
"action.batch",
&json!({
"source": "datasets",
"destinationFolder": dest.to_string_lossy(),
"commands": [{"command": "assets.export", "params": {"folder": own.to_string_lossy(), "formats": [{"format": "svg"}]}}]
}),
)
.unwrap();
assert_eq!(r["failed"], 0, "{r}");
assert_eq!(file_names(&dest), ["Untitled_a", "Untitled_b"], "{r}");
for stem in ["Untitled_a", "Untitled_b"] {
assert_eq!(file_names(&dest.join(stem)), ["Logo.svg"], "{r}");
}
assert!(file_names(&own).is_empty(), "{r}");
}
/// Override Save names each file with the extension of the format the step names, also over
/// data sets.
#[test]
@@ -1258,7 +1698,7 @@ mod tests {
assert!(!dataset_output_exists(
Some(&folder),
"../outside",
&[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-" }],
&[DatasetOutput { ext: "svg".into(), artboards: false, joiner: "-", folder: false }],
&vectorcraft_doc::Document::new(100.0, 80.0),
));
}
@@ -1525,7 +1965,15 @@ mod tests {
assert!(!batch_overwrites_one_file(&saved, &save(Some("svg"))), "another format without a path: the data comes back");
assert!(!with(json!({"commands": [{"command": "file.saveCopy", "params": {"folder": "/x"}}]})), "a folder alone: the data comes back");
let screens = json!([{"command": "document.exportForScreens", "params": {"folder": "/x"}}]);
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": screens})), "Override Export leaves its folder");
assert!(
!with(json!({"destination": "folder", "destinationFolder": "/out", "commands": screens})),
"Override Export gives each data set its own folder"
);
assert!(
with(json!({"destination": "folder", "destinationFolder": "/out", "overrideExport": false, "commands": screens})),
"without Override Export the step keeps its folder"
);
assert!(with(json!({"commands": screens})), "without a destination folder the step keeps its folder");
assert!(!with(json!({"commands": [{"command": "document.exportForScreens", "params": {}}]})));
let preset = json!([{"command": "document.exportForScreens", "params": {"exportPreset": "Logo Package"}}]);
assert!(!with(json!({"commands": preset})), "a preset without a folder: the data comes back");
+8 -8
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferen Line truncated
always,
load::open
),
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Serialize Document",
[],
None,
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]",
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
has_doc,
export::serialize
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path",
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
has_doc,
export::export
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Selection…",
["File"],
None,
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export",
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
has_selection,
export::export_selection
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export for Screens",
["File", "Export"],
None,
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step)",
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]}; no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
has_doc,
screens::export_for_screens
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Export Preset",
[],
None,
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused → {name, created, settings}",
"{name, settings: {formats, settings, preset, name, prefix, counterStart, counterPer, folders, subfolders, includeBleed, includeArtboardFill, antiAlias, folder, fullDocument} (as document.exportForScreens; its other keys are left out)} save (or replace) a batch export preset, kept with the preferences; built-in names are refused, and so are the keys document.exportForScreens refuses, in settings and in its format rows and settings → {name, created, settings}",
always,
screens::presets_save
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"File Formats",
[],
None,
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…], unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}",
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}",
always,
formats
),
+2 -2
View File
@@ -21,14 +21,14 @@ pub fn specs() -> Vec<CommandSpec> {
"Export DXF",
[],
None,
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}",
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
has_doc,
export_dxf
)]
}
/// The DXF options `document.formats` lists.
pub(super) const OPTIONS: &[FormatOption] = &[
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
super::ARTBOARDS,
super::RANGE,
+2 -2
View File
@@ -32,14 +32,14 @@ pub fn specs() -> Vec<CommandSpec> {
"Export EPS",
[],
None,
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}",
"{path?, level?: 2|3 (default; PostScript language level: 3 writes smooth gradients and masks transparent image pixels out, 2 steps gradients and writes those pixels white), previewFormat?: none|tiffBw|tiffColor (default: a TIFF preview other apps show), transparentPreview?: true (else on white), overprints?: preserve (default)|discard, flattenerPreset?: \"medium\" (default; high, low or a saved preset: flattener.presets.list), flattener?: {the options of object.flattenTransparency over the preset}, embedFonts?: true (type is always written as outlines, so no fonts are needed), includeLinkedFiles?: false (the embedded document keeps linked images whole, not just their previews), thumbnails?: true (a PNG thumbnail in the file), cmykPostScript?: true (RGB documents written in CMYK), compatibleGradients?: false (stepped gradients at level 3 too), selectedOnly?: false, useArtboards?: true (one file per chosen artboard, artboards?/range?, {stem}_{artboard}.eps, the bounding box the artboard; with two or more, also the central file {stem}.eps first: the whole document, the bounding box the visible art; none when no art shows) | false (one file, the bounding box the visible art, y up from the first artboard's bottom-left corner, even when artboards are named; the default when none are named), format?: \"eps\", artboard?: i | artboards?: [i…] | range?: \"1-3, 5\" (the artboards written; naming them without useArtboards works as useArtboards: true)} → {path, bytes, warnings, files?}; no path → {dataBase64, …}. Transparency is flattened with the preset (EPS has none); the native document rides along in comments, for reopening the file as it was. Same as document.export {format: eps}. A key EPS doesn't take, and an unknown key inside flattener, are refused",
has_doc,
export_eps
)]
}
/// The EPS options `document.formats` lists.
pub(super) const OPTIONS: &[FormatOption] = &[
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
super::ARTBOARDS,
super::RANGE,
+142 -25
View File
@@ -505,6 +505,8 @@ pub const FORMATS: &[Format] = &[
reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true),
// HEVC-coded HEIF still images, decoded to PNG; image sequences are not read.
reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true),
// jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it.
reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true),
];
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
@@ -544,6 +546,7 @@ pub const OPEN_EXTS: &[&str] = &[
"psd",
"pdd",
"psb",
"jxl",
"vctemplate",
"dxf",
"emf",
@@ -558,12 +561,12 @@ pub const OPEN_EXTS: &[&str] = &[
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000 or HEIC/HEIF type, nor one for the `.pns`, `.dib` and `.rle` names of
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
pub const UNASSOCIATED_EXTS: &[&str] = &[
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
"heic", "heif",
"heic", "heif", "jxl",
];
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
@@ -632,6 +635,7 @@ pub const PLACE_EXTS: &[&str] = &[
"psd",
"pdd",
"psb",
"jxl",
"vctemplate",
"dxf",
"emf",
@@ -659,11 +663,12 @@ pub fn read_extensions(f: &Format) -> &'static [&'static str] {
READ_ALIASES.iter().find(|(id, _)| *id == f.id).map_or(f.extensions, |(_, exts)| *exts)
}
/// The readable format of extension `ext` (any case, leading dot allowed): [`format`]'s when it
/// reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP).
/// The built-in readable format of extension `ext` (any case, leading dot allowed): [`format`]'s
/// when it reads, else the one [`READ_ALIASES`] gives it (`.dib` is BMP). Importer plug-ins are
/// not looked at ([`importer_formats`]).
pub fn readable_format(ext: &str) -> Option<&'static Format> {
let k = ext.trim_start_matches('.').to_ascii_lowercase();
format(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| format(id)))
builtin(&k).filter(|f| f.read).or_else(|| READ_ALIASES.iter().find(|(_, exts)| exts.contains(&k.as_str())).and_then(|(id, _)| builtin(id)))
}
/// The readable format a file name's extension names ([`readable_format`]).
@@ -676,18 +681,110 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
}
/// Open-dialog filters: "All readable files" first, then one per readable format, then swatch
/// libraries (which open in the library panel), Libraries panel libraries, flattener, PDF, print
/// and export presets (imported), scripts (checked without running them) and plug-ins (installed).
/// Whether a file named `name` can only be read by an importer plug-in: an installed importer lists
/// its extension and File › Place does not read that extension.
pub fn opens_with_importer(name: &str) -> bool {
let ext = extension(name);
!ext.is_empty() && !PLACE_EXTS.contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty()
}
/// Whether File › Open opens a file of extension `ext` (lower case) as something other than a
/// document: a plug-in (installed), a shortcut set, a script (checked), flattener, PDF, print,
/// perspective grid or export presets or composite fonts (imported), a Libraries panel library, or a
/// swatch or graphic style library.
pub fn opens_as_other(ext: &str) -> bool {
[
crate::cmd::plugin::EXTS,
crate::cmd::shortcutset::EXTS,
crate::cmd::scripts::EXTS,
crate::cmd::flatten::PRESET_EXTS,
crate::cmd::pdfcmds::PRESET_EXTS,
crate::cmd::printpresets::PRESET_EXTS,
crate::cmd::perspgrid::PRESET_EXTS,
screens::PRESET_FILE_EXTS,
crate::cmd::compositefonts::EXTS,
crate::cmd::library::LIBRARY_EXTS,
crate::cmd::swatchlib::LIBRARY_EXTS,
std::slice::from_ref(&vectorcraft_doc::style_libs::STYLES_EXT),
]
.iter()
.any(|exts| exts.contains(&ext))
}
/// File › Open's extensions and filters for the installed importer plug-ins.
type ImporterPart = (&'static [&'static str], Vec<(&'static str, &'static [&'static str])>);
/// File › Open's part for the installed importer plug-ins: the extensions of "All readable files"
/// ([`OPEN_EXTS`], then the importers' extensions in plug-in id order) and one filter per importer
/// that has extensions left, under its name. An importer's extensions leave out those a built-in
/// format reads, which File › Open reads with that format, and those File › Open opens as something
/// else ([`opens_as_other`]). Made once for each set of installed plug-ins, so it lives as long as
/// the dialogs that hold it.
fn importer_open_part() -> ImporterPart {
use vectorcraft_plugins::registry;
static MADE: std::sync::Mutex<Option<(u64, ImporterPart)>> = std::sync::Mutex::new(None);
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
let revision = registry::revision();
if let Some((r, part)) = made.as_ref()
&& *r == revision
{
return part.clone();
}
let mut exts: Vec<&'static str> = OPEN_EXTS.to_vec();
let mut filters = Vec::new();
for f in importer_formats() {
let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect();
if own.is_empty() {
continue;
}
for &e in &own {
if !exts.contains(&e) {
exts.push(e);
}
}
let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) };
filters.push((f.label, own));
}
let exts: &'static [&'static str] = if exts.len() == OPEN_EXTS.len() { OPEN_EXTS } else { Box::leak(exts.into_boxed_slice()) };
let part = (exts, filters);
*made = Some((revision, part.clone()));
part
}
/// Every extension File › Open reads as a document: [`OPEN_EXTS`], then the extensions the
/// installed importer plug-ins list that no built-in format reads and that File › Open doesn't open
/// as something else ([`opens_as_other`]), in plug-in id order.
pub fn open_extensions() -> &'static [&'static str] {
importer_open_part().0
}
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
/// swatch libraries (which open in the library panel), Libraries panel libraries, flattener, PDF,
/// print and export presets (imported), scripts (checked without running them) and plug-ins
/// (installed).
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("All readable files", OPEN_EXTS))
.chain(format_filters())
.chain(std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS)))
let (all, importers) = importer_open_part();
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
}
/// [`open_filters`] without the importer plug-ins: "All readable files" lists [`OPEN_EXTS`]. For
/// open dialogs whose files the built-in readers read (New from Template, Load Styles, a document
/// picked for its swatches, symbols, brushes or graphic styles).
pub fn builtin_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("All readable files", OPEN_EXTS)).chain(format_filters()).chain(other_open_filters())
}
/// The open-dialog filters after the document formats: swatch libraries, Libraries panel
/// libraries, presets, composite fonts, shortcut sets, scripts and plug-ins.
fn other_open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once(("Swatch libraries", crate::cmd::swatchlib::LIBRARY_EXTS))
.chain(std::iter::once(("Libraries", crate::cmd::library::LIBRARY_EXTS)))
.chain(std::iter::once(("Flattener presets", crate::cmd::flatten::PRESET_EXTS)))
.chain(std::iter::once(("PDF presets", crate::cmd::pdfcmds::PRESET_EXTS)))
.chain(std::iter::once(("Print presets", crate::cmd::printpresets::PRESET_EXTS)))
.chain(std::iter::once(("Export presets", screens::PRESET_FILE_EXTS)))
.chain(std::iter::once(("Composite fonts", crate::cmd::compositefonts::EXTS)))
.chain(std::iter::once(("Shortcut sets", crate::cmd::shortcutset::EXTS)))
.chain(std::iter::once(("Scripts", crate::cmd::scripts::EXTS)))
.chain(std::iter::once(("Plug-ins", crate::cmd::plugin::EXTS)))
@@ -696,12 +793,13 @@ pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
/// Open-dialog filters for Swatch Libraries and Graphic Style Libraries Other Library… and Locate
/// Library…. The library formats come first so Linux file portals (which grey out files that don't
/// match the default filter) still list `.ase` and the other library extensions; then the same
/// filters as [`open_filters`] so a document can be picked for its swatches or graphic styles.
/// filters as [`builtin_open_filters`] so a document can be picked for its swatches or graphic
/// styles.
pub fn library_open_filters(
library_label: &'static str,
library_exts: &'static [&'static str],
) -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
std::iter::once((library_label, library_exts)).chain(open_filters())
std::iter::once((library_label, library_exts)).chain(builtin_open_filters())
}
/// File → Place dialog filters: "All placeable files", then one per placeable format, then text,
@@ -715,26 +813,40 @@ pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
}
/// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in
/// one, else one an exporter plug-in adds ([`plugin_formats`]). A built-in format keeps its
/// extension, so an exporter that lists it too is found by its format id.
/// one, else one a plug-in adds ([`plugin_formats`]), an exporter's before an importer's for an
/// extension both list. A built-in format keeps its extension, so an exporter or importer that
/// lists it too is found by its format id.
pub fn format(id_or_ext: &str) -> Option<&'static Format> {
let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase();
FORMATS.iter().find(|f| f.id == k).or_else(|| FORMATS.iter().find(|f| f.extensions.contains(&k.as_str()))).or_else(|| {
builtin(&k).or_else(|| {
let added = plugin_formats();
added.iter().find(|f| f.id.eq_ignore_ascii_case(&k)).or_else(|| added.iter().find(|f| f.extensions.contains(&k.as_str()))).copied()
let by_ext = |f: &&&Format| f.extensions.contains(&k.as_str());
added
.iter()
.find(|f| f.id.eq_ignore_ascii_case(&k))
.or_else(|| added.iter().filter(|f| f.write).find(by_ext))
.or_else(|| added.iter().find(by_ext))
.copied()
})
}
/// The formats the installed exporter plug-ins add ([`vectorcraft_plugins::export`]), by plug-in
/// id: write only, with the plug-in's name as the label and its extensions. Each is made once for
/// each installation of its plug-in, its strings interned, so formats live as long as the catalogues
/// A built-in format by id or extension (lower case, without the dot).
fn builtin(k: &str) -> Option<&'static Format> {
FORMATS.iter().find(|f| f.id == k).or_else(|| FORMATS.iter().find(|f| f.extensions.contains(&k)))
}
/// The formats the installed exporter and importer plug-ins add ([`vectorcraft_plugins::export`],
/// [`vectorcraft_plugins::import`]), by plug-in id: an exporter's write only and an importer's read
/// only, with the plug-in's name as the label and its extensions. Each is made once for each
/// installation of its plug-in, its strings interned, so formats live as long as the catalogues
/// that hold them.
pub fn plugin_formats() -> Vec<&'static Format> {
use vectorcraft_plugins::{export, registry};
use vectorcraft_plugins::{Kind, export, registry};
static MADE: std::sync::Mutex<Vec<(u64, &'static Format)>> = std::sync::Mutex::new(Vec::new());
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
export::installed()
registry::list()
.iter()
.filter(|p| matches!(p.manifest().kind, Kind::Exporter | Kind::Importer))
.map(|p| {
if let Some((_, f)) = made.iter().find(|(serial, _)| *serial == p.serial()) {
return *f;
@@ -746,8 +858,8 @@ pub fn plugin_formats() -> Vec<&'static Format> {
label: registry::intern(&m.name),
extensions: Box::leak(extensions.into_boxed_slice()),
mime: "application/octet-stream",
read: false,
write: true,
read: m.kind == Kind::Importer,
write: m.kind == Kind::Exporter,
raster: false,
options: &[],
}));
@@ -757,6 +869,11 @@ pub fn plugin_formats() -> Vec<&'static Format> {
.collect()
}
/// The formats the installed importer plug-ins add ([`plugin_formats`] that read), by plug-in id.
pub fn importer_formats() -> Vec<&'static Format> {
plugin_formats().into_iter().filter(|f| f.read).collect()
}
/// The lower-case extension of a file name or path (empty when it has none).
pub fn extension(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
@@ -845,7 +962,7 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
"formats": all().map(listed).collect::<Vec<_>>(),
"readable": ids(|f| f.read),
"writable": ids(|f| f.write),
"openExtensions": OPEN_EXTS,
"openExtensions": open_extensions(),
"unsupported": UNSUPPORTED.iter().map(Unsupported::to_json).collect::<Vec<_>>(),
}))
}
+170
View File
@@ -0,0 +1,170 @@
//! `document.open` of the files importer plug-ins read ([`vectorcraft_plugins::import`]).
//!
//! A file opens with an importer when `importer` names one (its format id, `plugin.<id>`), which
//! must list the file's extension, or when no built-in format reads the file, by its content or by
//! its extension, and an importer lists its extension (the one whose id sorts first, when several
//! do). A built-in format that can't read a damaged file reports its own error: the file is not
//! handed to an importer instead. Place reads only the built-in formats.
//!
//! The importer is given the file's bytes, at most [`import::MAX_INPUT_BYTES`] of them: a file
//! named by `path` that only an importer can read is read no further than that. Its objects become
//! a new document whose artboard is their bounds, and nothing opens when the importer fails,
//! declines, is cancelled or returns objects that don't pass the checks a filter's output does.
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::{Document, MAX_COORD};
use vectorcraft_geom::Rect;
use vectorcraft_plugins::{Plugin, export, import, objects};
use super::super::{Result, bad, str_param};
use super::load::{Loaded, detect, file_name};
use super::{err, extension, file_stem, format};
use crate::EngineError;
const C: &str = "document.open";
/// The importer `document.open`'s params `p` name (`importer`), if any; a value that isn't a
/// string is an error.
fn named(p: &Value) -> Result<Option<&str>> {
match p.get("importer").filter(|v| !v.is_null()) {
None => Ok(None),
Some(v) => v.as_str().map(Some).ok_or_else(|| bad(C, "`importer` must be a plug-in format id (see document.formats)")),
}
}
/// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the
/// one `importer` names, which must list the file's extension; else, when no built-in format reads
/// the file, the first installed importer that lists its extension; else `None`.
pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plugin>>> {
let ext = extension(name);
if let Some(id) = named(p)? {
let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?;
let m = plugin.manifest();
if !m.extensions.contains(&ext) {
let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
let exts: Vec<String> = m.extensions.iter().map(|e| format!(".{e}")).collect();
return Err(bad(C, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name))));
}
return Ok(Some(plugin));
}
if detect(name, bytes).is_some() {
return Ok(None);
}
Ok(import::for_extension(&ext).into_iter().next())
}
/// How much of a file [`detect`] is given: more than its content checks read.
const SNIFF_BYTES: usize = 64 << 10;
/// Refuses `document.open`'s `dataBase64` in `p` before it is decoded when it holds a file past
/// [`import::MAX_INPUT_BYTES`] that only an importer reads, by the rule of `read_path`.
pub(super) fn check_data(p: &Value) -> Result<()> {
let Some(b64) = str_param(p, "dataBase64") else {
return Ok(());
};
let name = str_param(p, "name").unwrap_or("Untitled");
let ext = extension(name);
let explicit = named(p)?.is_some();
let built_in = !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty());
if built_in || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 {
return Ok(());
}
if !explicit {
let start: Vec<u8> = b64.bytes().filter(|b| !b.is_ascii_whitespace()).take(SNIFF_BYTES / 3 * 4).collect();
let head = std::str::from_utf8(&start).ok().and_then(vectorcraft_format::base64_decode);
if head.is_some_and(|head| detect(name, &head).is_some()) {
return Ok(());
}
}
Err(err(format!("can't open `{}`: {}", file_name(name), import::too_large())))
}
/// The file at `path` for `document.open`'s params `p`. A file that only an importer reads (one
/// `importer` names, or an extension no built-in format reads that an importer lists) is read up
/// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a
/// built-in format and no importer was named, which is read whole as any other file is. A file past
/// the limit that isn't read whole is reported from its size, without reading it.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn read_path(path: &str, p: &Value) -> Result<Vec<u8>> {
let ext = extension(path);
let explicit = named(p)?.is_some();
if !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) {
return super::read_file(path);
}
let head = super::read_file_head(path, SNIFF_BYTES)?;
if head.len() < SNIFF_BYTES {
return Ok(head);
}
if !explicit && detect(path, &head).is_some() {
return super::read_file(path);
}
let too_large = || err(format!("can't open `{}`: {}", file_name(path), import::too_large()));
let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len();
if size > import::MAX_INPUT_BYTES as u64 {
return Err(too_large());
}
// The file can grow after the size is read.
let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?;
if file.len() > import::MAX_INPUT_BYTES {
return Err(too_large());
}
Ok(file)
}
#[cfg(target_arch = "wasm32")]
pub(super) fn read_path(path: &str, _: &Value) -> Result<Vec<u8>> {
super::read_file(path)
}
/// The file `name` holding `bytes` read by importer `plugin` with `document.open`'s params `p`
/// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what
/// the importer returned.
pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result<Loaded> {
let m = plugin.manifest();
let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?;
let (ext, stem) = (extension(name), file_stem(name));
let source = import::Source { extension: &ext, name: &stem };
let params = p.get("params").cloned().unwrap_or(Value::Null);
let imported = import::run(plugin, bytes, &params, source).map_err(|e| match e {
vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled,
vectorcraft_plugins::Error::Params(why) => bad(C, why),
e => err(format!("can't open `{}`: {e}", file_name(name))),
})?;
let mut doc = Document::new(1.0, 1.0);
let layer = doc.layers.first().map(|l| l.id);
let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n);
let ids =
objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
board.rect = artboard_rect(bounds);
}
doc.title = file_name(name);
Ok(Loaded {
doc,
format,
warnings: imported.warnings,
restored: false,
converted: false,
preview_only: false,
editing_data: false,
native_pdf_compatible: None,
})
}
/// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high
/// about its center (the artboard of a single line or point). A side that would pass the edge
/// moves inward, so art at the edge keeps an artboard the document's edits accept.
fn artboard_rect(r: Rect) -> Rect {
let side = |lo: f64, hi: f64| {
let (lo, hi) = (lo.max(-MAX_COORD), hi.min(MAX_COORD));
if hi - lo >= 1.0 {
return (lo, hi);
}
let mid = ((lo + hi) / 2.0).clamp(-MAX_COORD + 0.5, MAX_COORD - 0.5);
(mid - 0.5, mid + 0.5)
};
let ((x0, x1), (y0, y1)) = (side(r.x0, r.x1), side(r.y0, r.y1));
Rect::new(x0, y0, x1, y1)
}
+273
View File
@@ -0,0 +1,273 @@
//! Reading JPEG XL images (`.jxl`, ISO/IEC 18181) for File › Open and File › Place, with the
//! jxl-oxide decoder: the bare codestream and the ISOBMFF container. The first frame of an
//! animation is read, with the orientation its header gives applied.
//!
//! Colors come back as sRGB whenever the decoder converts them without a color management
//! system: XYB-encoded images, every color space a JPEG XL header names, and embedded ICC
//! profiles that describe one of them. Any other image with an embedded RGB ICC profile comes
//! back with its samples as stored, as PNG and JPEG files with an embedded profile are drawn, and
//! with the profile. Gray images, and images whose profile is not an RGB one, are refused when the
//! decoder cannot convert their ICC profile. 16-bit and floating-point samples become 8 bits, alpha comes back straight,
//! and CMYK images are refused. The file is untrusted: the decoder is given only a container's
//! image boxes, the image's size is checked from its header before any pixels are decoded, and the
//! decoder's image buffers are capped.
use jxl_color::ColorTransform;
use jxl_oxide::color::{ColourEncoding, TransferFunction};
use jxl_oxide::{AllocTracker, ColorEncodingWithProfile, EnumColourEncoding, HdrType, InitializeResult, JxlImage, NullCms, RenderingIntent};
/// A bare JPEG XL codestream starts with these bytes.
const CODESTREAM: [u8; 2] = [0xff, 0x0a];
/// The signature box an ISOBMFF JPEG XL container starts with.
const CONTAINER: [u8; 12] = [0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a];
/// How many bytes the decoder is given first to read the header. Each later try gives it twice as
/// many bytes, and each try decodes the embedded ICC profile from its start again.
const HEAD: usize = 4096;
/// The most the decoder's buffers may take while it reads the header. Its `AllocTracker` counts the
/// image buffers only: an embedded ICC profile is decoded into buffers of its own, which jxl-color
/// limits to 256 MiB.
const HEADER_BUFFERS: usize = 16 << 20;
/// The most the decoder's buffers may take for the pixels: this many times the image's size as
/// RGBA, plus [`HEADER_BUFFERS`], and never more than the `max_alloc` of [`decode`], the limit the
/// `image` crate's decoders get in `raster_image`. The decoder keeps each channel as 32-bit
/// samples: a lossless 16-bit RGBA image of 1024 × 768 pixels took 12 times its size as RGBA.
const DECODER_BUFFERS: u64 = 16;
const TRUNCATED: &str = "the JPEG XL file is cut short";
/// Is `bytes` a JPEG XL image (a bare codestream or a container)?
pub fn is_jxl(bytes: &[u8]) -> bool {
bytes.starts_with(&CODESTREAM) || bytes.starts_with(&CONTAINER)
}
/// Resolution after the decoder applies the image header's orientation.
pub(crate) fn oriented_resolution(ppi: Option<(f64, f64)>, orientation: u32) -> Option<(f64, f64)> {
ppi.map(|(x, y)| if (5..=8).contains(&orientation) { (y, x) } else { (x, y) })
}
/// The first frame of a JPEG XL image as straight RGBA, with the embedded ICC profile its colors
/// are in when they are not converted to sRGB ([`output_profile`]), and the header orientation.
/// Fails, without decoding the
/// pixels, when the image would take more than `max_alloc` bytes as RGBA. The image is also too
/// large to draw when the decoder's buffers for its pixels need more than they are allowed. A
/// container whose selected boxes exceed `max_alloc` or [`HEADER_BUFFERS`], whichever is greater,
/// is refused with "the JPEG XL container is too large to read".
pub fn decode(bytes: &[u8], max_alloc: u64) -> Result<(image::RgbaImage, Option<Vec<u8>>, u32), String> {
let pixel_boxes = pixel_boxes(bytes, max_alloc.max(HEADER_BUFFERS as u64))?;
let bytes = pixel_boxes.as_deref().unwrap_or(bytes);
// The decoder reads the header first, with buffers for the header alone.
let (head, _) = header(bytes, HEADER_BUFFERS, None)?;
let (w, h) = (head.width(), head.height());
let rgba = u64::from(w) * u64::from(h) * 4;
if rgba > max_alloc {
return Err(too_large(w, h));
}
if head.pixel_format().has_black() {
return Err("CMYK JPEG XL images can't be read".into());
}
// Then it reads the file again until the first frame is loaded, with buffers for the pixels.
let budget = rgba.saturating_mul(DECODER_BUFFERS).saturating_add(HEADER_BUFFERS as u64).min(max_alloc);
let budget = usize::try_from(budget).unwrap_or(usize::MAX);
let size = Some((w, h));
let (mut image, mut at) = header(bytes, budget, size)?;
let mut end = at;
while image.num_loaded_keyframes() == 0 {
if end == bytes.len() {
return Err(TRUNCATED.into());
}
end = end.saturating_mul(2).max(HEAD).min(bytes.len());
at += image.feed_bytes(&bytes[at..end]).map_err(|e| failed(e, size))?;
}
let metadata = &image.image_header().metadata;
let associated = metadata.alpha().and_then(|i| metadata.ec_info.get(i)).and_then(|ec| ec.alpha_associated()) == Some(true);
let intent = RenderingIntent::Relative;
let srgb = if metadata.grayscale() { EnumColourEncoding::gray_srgb(intent) } else { EnumColourEncoding::srgb(intent) };
let profile = output_profile(metadata.xyb_encoded, metadata.grayscale(), image.original_icc())?;
let orientation = metadata.orientation;
// Premultiplied colors are divided by alpha in the encoding they are stored in, and converted
// to sRGB after that. XYB-encoded images come from the decoder in linear sRGB (tone mapped when
// they are HDR), which the sRGB transfer curve alone turns into sRGB.
let (request, convert) = match (to_srgb_without_cms(metadata.xyb_encoded, image.original_icc()), associated) {
(false, _) => (None, None),
(true, false) => (Some(srgb), None),
(true, true) if metadata.xyb_encoded => (Some(EnumColourEncoding { tf: TransferFunction::Linear, ..srgb }), Some(ToSrgb::Curve)),
(true, true) => {
let stored = match (&metadata.colour_encoding, image.original_icc()) {
(ColourEncoding::Enum(e), _) => ColorEncodingWithProfile::new(e.clone()),
(_, Some(icc)) => ColorEncodingWithProfile::with_icc(icc).map_err(unreadable)?,
(_, None) => return Err(unreadable("no color encoding")),
};
let mut builder = ColorTransform::builder();
builder.from_pq(image.hdr_type() == Some(HdrType::Pq));
let to = ColorEncodingWithProfile::new(srgb);
let t = builder.build(&stored, &to, &metadata.opsin_inverse_matrix, &metadata.tone_mapping, &NullCms).map_err(unreadable)?;
(None, Some(ToSrgb::Transform(t)))
}
};
if let Some(encoding) = request {
image.request_color_encoding(encoding);
}
let render = image.render_frame(0).map_err(|e| failed(e, size))?;
let mut stream = render.stream();
let channels = stream.channels() as usize;
if !(1..=4).contains(&channels) {
return Err(unreadable(format!("{channels} channels")));
}
let mut out = image::RgbaImage::new(stream.width(), stream.height());
let width = out.width() as usize;
let mut row = vec![0f32; width * channels];
let mut colors = [vec![0f32; width], vec![0f32; width], vec![0f32; width]];
for line in out.chunks_exact_mut((width * 4).max(4)) {
if stream.write_to_buffer(&mut row) != row.len() {
return Err(TRUNCATED.into());
}
to_rgba(&row, channels, associated, convert.as_ref(), &mut colors, line)?;
}
Ok((out, profile, orientation))
}
/// How colors whose alpha was divided out become sRGB.
pub(crate) enum ToSrgb {
/// A conversion from the encoding the colors are stored in.
Transform(ColorTransform),
/// The sRGB transfer curve, for colors in linear sRGB.
Curve,
}
/// One row of samples, `channels` to a pixel (gray or RGB, then alpha when there are 2 or 4), as
/// straight RGBA bytes in `out`: colors divided by alpha when it is `associated`, then converted
/// with `convert`. `colors` holds a row of red, green and blue; a gray sample goes into all three,
/// as jxl-render's `clone_gray` does before its own conversions.
pub(crate) fn to_rgba(
row: &[f32],
channels: usize,
associated: bool,
convert: Option<&ToSrgb>,
colors: &mut [Vec<f32>; 3],
out: &mut [u8],
) -> Result<(), String> {
let alpha = |s: &[f32]| if matches!(channels, 2 | 4) { s.last().map_or(1.0, |a| a.clamp(0.0, 1.0)) } else { 1.0 };
let gray = channels < 3;
for (x, s) in row.chunks_exact(channels).enumerate() {
let a = alpha(s);
for (i, plane) in colors.iter_mut().enumerate() {
let v = s.get(if gray { 0 } else { i }).copied().unwrap_or(0.0);
if let Some(c) = plane.get_mut(x) {
*c = if associated && a > 0.0 { v / a } else { v };
}
}
}
// The conversion leaves gray in the first row when it gives one channel.
let gray = match convert {
Some(ToSrgb::Transform(t)) => {
let mut planes: Vec<&mut [f32]> = colors.iter_mut().map(Vec::as_mut_slice).collect();
t.run(&mut planes).map_err(unreadable)? < 3
}
Some(ToSrgb::Curve) => {
colors.iter_mut().flatten().for_each(|v| *v = if *v <= 0.003_130_8 { *v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 });
gray
}
None => gray,
};
for (x, (px, s)) in out.as_chunks_mut::<4>().0.iter_mut().zip(row.chunks_exact(channels)).enumerate() {
let c = |i: usize| colors.get(if gray { 0 } else { i }).and_then(|p| p.get(x)).copied().unwrap_or(0.0);
*px = [byte(c(0)), byte(c(1)), byte(c(2)), byte(alpha(s))];
}
Ok(())
}
/// A container's signature and the boxes the decoder reads pixels from (`ftyp`, `jxll`, `jxlc` and
/// `jxlp`). Every other box is left out: Exif, XMP, JPEG reconstruction data and Brotli-compressed
/// `brob` boxes, which the decoder would otherwise store and unpack without a size limit. A box
/// cut short ends the file. Selected boxes exceeding `max_copy` are refused with "the JPEG XL
/// container is too large to read". `None` for a bare codestream.
pub(super) fn pixel_boxes(bytes: &[u8], max_copy: u64) -> Result<Option<Vec<u8>>, String> {
let Some(mut rest) = bytes.strip_prefix(&CONTAINER) else { return Ok(None) };
let mut out = CONTAINER.to_vec();
while let (Some(size), Some(ty)) = (rest.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()), rest.get(4..8)) {
let (head, len) = match u32::from_be_bytes(size) {
0 => (8, rest.len() as u64),
1 => match rest.get(8..16).and_then(|l| l.try_into().ok()) {
Some(l) => (16, u64::from_be_bytes(l)),
None => break,
},
n => (8, u64::from(n)),
};
if len < head {
break;
}
let len = usize::try_from(len).unwrap_or(usize::MAX).min(rest.len());
let (b, after) = rest.split_at(len);
if matches!(ty, b"ftyp" | b"jxll" | b"jxlc" | b"jxlp") {
if (out.len() as u64).saturating_add(b.len() as u64) > max_copy {
return Err("the JPEG XL container is too large to read".into());
}
out.try_reserve_exact(b.len()).map_err(|_| "the JPEG XL container is too large to read")?;
out.extend_from_slice(b);
}
rest = after;
}
Ok(Some(out))
}
/// A decoder whose buffers may take `buffers` bytes, given as few of `bytes` as it needs to read
/// the header → (the decoder, how many bytes it took). `size` is the image's size when it is
/// known, for the error when the buffers need more ([`failed`]).
fn header(bytes: &[u8], buffers: usize, size: Option<(u32, u32)>) -> Result<(JxlImage, usize), String> {
let mut uninit = JxlImage::builder().alloc_tracker(AllocTracker::with_limit(buffers)).build_uninit();
let (mut at, mut end) = (0, 0usize);
loop {
end = end.saturating_mul(2).max(HEAD).min(bytes.len());
at += uninit.feed_bytes(&bytes[at..end]).map_err(|e| failed(e, size))?;
match uninit.try_init().map_err(|e| failed(e, size))? {
InitializeResult::Initialized(image) => return Ok((image, at)),
InitializeResult::NeedMoreData(_) if end == bytes.len() => return Err(TRUNCATED.into()),
InitializeResult::NeedMoreData(more) => uninit = more,
}
}
}
/// Does the decoder convert to sRGB without a color management system? It does for XYB-encoded
/// images and the color spaces a header names; for an embedded ICC profile, only when the profile
/// describes one of those.
fn to_srgb_without_cms(xyb: bool, icc: Option<&[u8]>) -> bool {
xyb || icc.is_none_or(|icc| ColorEncodingWithProfile::with_icc(icc).is_ok_and(|p| p.icc_profile().is_empty()))
}
/// The embedded RGB profile when the decoder leaves colors in it. Gray colors without a
/// conversion to sRGB cannot be stored as RGB without changing their profile, and neither can
/// colors left in a profile that is not an RGB one.
pub(crate) fn output_profile(xyb: bool, grayscale: bool, icc: Option<&[u8]>) -> Result<Option<Vec<u8>>, String> {
let converts = to_srgb_without_cms(xyb, icc);
if grayscale && !converts {
return Err(unreadable("unsupported grayscale ICC profile"));
}
if !converts && icc.and_then(|icc| icc.get(16..20)) != Some(b"RGB ") {
return Err(unreadable("unsupported ICC profile color space"));
}
Ok(icc.filter(|_| !converts).map(<[u8]>::to_vec))
}
/// The decoder's error `e` as a message. When the decoder's buffers needed more than they were
/// allowed and the image's `size` is known, the image is too large to draw. Otherwise the file
/// can't be read.
fn failed(e: Box<dyn std::error::Error + Send + Sync>, size: Option<(u32, u32)>) -> String {
let first: &(dyn std::error::Error + 'static) = &*e;
let out_of_memory = std::iter::successors(Some(first), |c| c.source()).any(|c| c.is::<jxl_grid::OutOfMemory>());
match size {
Some((w, h)) if out_of_memory => too_large(w, h),
_ => unreadable(e),
}
}
fn too_large(w: u32, h: u32) -> String {
format!("an image of {w} × {h} pixels is too large to draw")
}
fn unreadable(e: impl std::fmt::Display) -> String {
format!("the JPEG XL file can't be read: {e}")
}
fn byte(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
+60 -27
View File
@@ -9,7 +9,7 @@ use vectorcraft_render::effects::pixel::LoadedTexture;
use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param};
use super::pdfimport::LoadOptions;
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, psdread, read_file, readable_format_for_name};
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name};
use crate::cmd::links::Resolved;
use crate::{EngineError, Prefs};
@@ -102,6 +102,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if super::pxrread::is_pxr(bytes) {
return format("pxr");
}
if jxlread::is_jxl(bytes) {
return format("jxl");
}
if super::jp2read::is_jpeg2000(bytes) {
return format("jpeg2000");
}
@@ -181,7 +184,8 @@ fn through_editing_data(
) -> (Document, Vec<String>, bool) {
let Some(layers) = layers else { return (doc, warnings, false) };
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit);
let (doc, mut warnings, read) =
vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit, opts.legacy_names);
// The layers weren't read (or couldn't be): the notes of reading the PDF part still hold.
if !read {
return (doc, warnings, false);
@@ -206,12 +210,12 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
return None;
}
let private = opened.illustrator_data()?;
Some(editing_copy_alone(&private))
Some(editing_copy_alone(&private, opts))
}
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone(private)
fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone_with(private, opts.legacy_names)
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
@@ -244,7 +248,7 @@ fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: &EngineError) -> Option
return None;
}
let private = vectorcraft_pdf::illustrator_data_without_pdf_part(bytes, opts.password.as_deref())?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit).ok()?;
let (doc, warnings) = vectorcraft_eps::ai_alone_on_page(&private.data, private.trim, private.user_unit, opts.legacy_names).ok()?;
let notes = std::iter::once(format!("the PDF part couldn't be read ({e}): the file opened from its editing data")).chain(warnings).collect();
Some(outlined_if_asked(doc, notes, opts))
}
@@ -320,7 +324,7 @@ pub(crate) fn page_or_editing_data(
match read {
Ok((doc, notes)) => Ok((doc, notes, false)),
Err(e) if is_placeholder(&e) => {
let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), ..Default::default() })?;
let l = load_with(name, bytes, &LoadOptions { password: opts.password.clone(), legacy_names: opts.legacy_names, ..Default::default() })?;
Ok((l.doc, l.warnings, true))
}
Err(e) if page_index == 0 => match load_with(name, bytes, &LoadOptions { pages: None, ..opts.clone() }) {
@@ -349,7 +353,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
_ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => {
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
restore_or_import(editing, || {
let r = vectorcraft_eps::import_trusting(bytes, opts.editing_data, opts.trust_editing_data)
let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
.map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
Ok((r.document, r.warnings))
})?
@@ -388,7 +392,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) {
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
@@ -410,8 +414,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let copy_alone = || match &private {
Some(private) => Some(editing_copy_alone(private)),
None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)),
Some(private) => Some(editing_copy_alone(private, opts)),
None if layers.is_some() => {
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
}
None => None,
};
let alone = (r.only_text || empty)
@@ -564,13 +570,19 @@ impl ReadFile {
/// The first half of [`open_bytes_with`], which needs no session (an app may do it on another
/// thread): read and decode the file, read its linked files and lay out its type → what
/// [`open_read`] opens. The linked files are looked for from `path`, where the file was read from,
/// [`open_read`] opens. Type in the file's composite fonts is measured again once the document
/// opens and its composite fonts are registered. The linked files are looked for from `path`, where the file was read from,
/// and modified ones are read again when `update_links` (Preferences › File Handling › Update
/// Links set to Automatically; see [`crate::cmd::links::resolve`]).
/// Links set to Automatically; see [`crate::cmd::links::resolve`]). A file an importer plug-in
/// reads (`importer` in `p`, or an extension only an importer lists) is read by it
/// ([`super::importer`]).
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
let opts = LoadOptions::from_params("document.open", p)?;
let mut loaded = load_with(name, bytes, &opts)?;
let links = crate::cmd::links::resolve(&mut loaded.doc, path.as_deref(), update_links, low_res_proxy_eps);
let mut loaded = match super::importer::pick(name, bytes, p)? {
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
None => load_with(name, bytes, &opts)?,
};
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut loaded.doc);
Ok(ReadFile { loaded, opts, path, links })
}
@@ -590,7 +602,8 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
"only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first",
));
}
let links = crate::cmd::links::resolve(&mut loaded.doc, path, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
let base = crate::cmd::links::LinkBase::file(path);
let links = crate::cmd::links::resolve(&mut loaded.doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true)
}
@@ -629,6 +642,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
// writes .ai that way).
let partial = format.id == "pdf" && opts.is_partial();
let lossy_ai = format.id == "ai" && !restored;
let read_from = path.clone();
let path = path.filter(|_| !template && !partial && !lossy_ai && SAVE_FORMATS.contains(&format.id));
let saves_back = path.is_some();
let converted = saves_back && converted && s.prefs.append_converted;
@@ -648,6 +662,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
st.converted = converted;
st.imported_from = source_path;
st.import_losses = losses;
st.links_from = read_from;
let opened = &s.documents()[index];
let (title, file_info_title) = (opened.title(), opened.doc.title.clone());
Ok(super::merge(
@@ -677,7 +692,14 @@ pub(crate) fn source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
}
pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
let src = source(p, "document.open")?;
// A file only an importer plug-in reads is read up to the importer's input limit.
let src = match str_param(p, "path") {
Some(path) => Source { name: path, bytes: super::importer::read_path(path, p)?, path: Some(path) },
None => {
super::importer::check_data(p)?;
source(p, "document.open")?
}
};
// A relative path is the file in the working directory: its folder is where relative links
// are found (a bare file name has no folder of its own).
let path = src.path.map(super::absolute_path);
@@ -743,7 +765,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels
/// as RGBA, need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw.
/// A TIFF with more strips or tiles than the decoder can count
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw.
/// ([`vectorcraft_doc::cmyk::oversized_tiff`]) is refused as too large to draw. JPEG XL images are
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
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) {
@@ -751,25 +774,29 @@ 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)?, ppi);
return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi);
}
if jxlread::is_jxl(bytes) {
let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?;
return as_png(img, icc, jxlread::oriented_resolution(ppi, orientation));
}
if super::jp2read::is_jpeg2000(bytes) {
return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
if super::heifread::is_heif(bytes) {
// The EXIF resolution describes the stored pixels; a quarter turn swaps its axes.
let ppi = ppi.map(|(x, y)| if super::heifread::quarter_turned(bytes) { (y, x) } else { (x, y) });
return as_png(super::heifread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
return as_png(super::heifread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
if super::pxrread::is_pxr(bytes) {
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(err)?;
if reader.format().is_none() && super::tgaread::is_targa(bytes) {
reader.set_format(image::ImageFormat::Tga);
}
if reader.format().is_none() && super::pcxread::is_pcx(bytes) {
return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
return as_png(super::pcxread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, None, ppi);
}
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
@@ -815,7 +842,7 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
if f.id == "tga" {
super::tgaread::fix_alpha(bytes, &mut img);
}
as_png(img, ppi)
as_png(img, None, ppi)
}
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
@@ -826,11 +853,17 @@ pub(crate) fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientat
decoder.orientation().ok().filter(|o| *o != image::metadata::Orientation::NoTransforms)
}
/// `img` stored as a PNG that keeps the file's resolution.
fn as_png(img: image::RgbaImage, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
/// colors are in.
pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
use image::ImageEncoder as _;
let size = img.dimensions();
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(err)?;
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
encoder.set_icc_profile(icc).map_err(err)?;
}
img.write_with_encoder(encoder).map_err(err)?;
let png = match ppi {
Some(r) => super::ppi::with_png_resolution(&png, r),
None => png,
+16 -3
View File
@@ -21,7 +21,7 @@ const C: &str = "document.exportPdf";
pub use vectorcraft_pdf::DEFAULT_PRESET;
/// The PDF options `document.formats` lists; `document.exportPdf` documents every field.
pub(super) const OPTIONS: &[FormatOption] = &[
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
super::ARTBOARDS,
super::RANGE,
@@ -50,6 +50,19 @@ pub(super) const OPTIONS: &[FormatOption] = &[
default: "true",
description: "embed the native document so VectorCraft reopens the PDF editable (the default preset's choice)",
},
FormatOption { name: "thumbnails", ty: "boolean", default: "false", description: "each page drawn as a /Thumb image, 106 px on its long side" },
FormatOption {
name: "fastWebView",
ty: "boolean",
default: "false",
description: "a linearized file: the first page shows while the rest downloads",
},
FormatOption {
name: "viewAfterSaving",
ty: "boolean",
default: "false",
description: "in the desktop app's document.exportPdf, the written file opens in the system viewer",
},
FormatOption { name: "compression", ty: "object", default: "null", description: "{color, gray, mono, compressText} (see document.exportPdf)" },
FormatOption { name: "marks", ty: "object", default: "null", description: "printer's marks (see document.exportPdf)" },
FormatOption {
@@ -109,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenR Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenR Line truncated
has_doc,
export_pdf
),
@@ -118,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
"PDF Settings",
[],
None,
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…)",
"{preset?, includeDocument?: false, …options of document.exportPdf} → {settings (the preset with the options applied), presets: [name…], changed: [{option: \"compression.compressText\", value}] (what differs from the preset), warnings}; includeDocument also exports the active document in memory and adds its warnings (knockout groups approximated, effects left out…). A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
always,
pdf_settings
),
+15 -3
View File
@@ -39,6 +39,9 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
pub native: bool,
@@ -57,6 +60,7 @@ impl Default for LoadOptions {
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
native: true,
}
}
@@ -65,8 +69,9 @@ impl Default for LoadOptions {
impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`) and `dxf`
/// (the DXF import options).
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
/// import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
None => None,
@@ -95,8 +100,15 @@ impl LoadOptions {
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
Some(v) => (v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true, false or \"always\""))?, false),
};
let legacy_names = match p.get("legacyNameEncoding").filter(|v| !v.is_null()) {
None => vectorcraft_eps::NameEncoding::default(),
Some(v) => v
.as_str()
.and_then(vectorcraft_eps::NameEncoding::from_label)
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, native: true })
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data, trust_editing_data, legacy_names, native: true })
}
/// Does the document read only part of the file, or read it differently (a page range, another
+29 -1
View File
@@ -1,5 +1,5 @@
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX
//! WebP and JPEG XL EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX
//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF
//! resolution tags. Place
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
@@ -17,6 +17,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
jpeg(bytes)
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
tiff(bytes)
} else if super::jxlread::is_jxl(bytes) {
jxl(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp(bytes)
} else if bytes.starts_with(b"BM") {
@@ -196,6 +198,32 @@ fn webp(b: &[u8]) -> Option<(f64, f64)> {
None
}
fn jxl(b: &[u8]) -> Option<(f64, f64)> {
if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) {
return None;
}
let mut at = 12;
while at < b.len() {
let size = be32(b, at)?;
let ty = slice(b, at.checked_add(4)?, 4)?;
let (header, len) = match size {
0 => (8, b.len().checked_sub(at)?),
1 => (16, usize::try_from(u64::from_be_bytes(bytes(b, at.checked_add(8)?)?)).ok()?),
_ => (8, size as usize),
};
if len < header {
return None;
}
let payload = slice(b, at.checked_add(header)?, len - header)?;
if ty == b"Exif" {
let offset = usize::try_from(be32(payload, 0)?).ok()?;
return tiff(payload.get(4usize.checked_add(offset)?..)?);
}
at = at.checked_add(len)?;
}
None
}
fn bmp(b: &[u8]) -> Option<(f64, f64)> {
// BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28.
if le32(b, 14)? < 40 {
+5 -2
View File
@@ -752,6 +752,8 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
/// file becomes the document's own; the live document gets them in [`SaveJob::finish`]). Bad
/// options fail here, before anything is encoded.
pub fn save_job(s: &mut Session, plan: SavePlan) -> Result<SaveJob> {
// A Shape Builder merge still being computed for a click is saved with the document.
s.finish_tool_edit_later()?;
// The web build, without a clock, leaves the dates unless given one.
let at = if plan.path.is_some() && plan.retargets() { clock_date(s, "modified", plan.modified) } else { None };
job_for_stamped(s, s.doc()?, plan, at)
@@ -777,7 +779,8 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
stamp_doc_dates(Arc::make_mut(&mut snapshot), at);
}
// A native file records its links' paths relative to where it is written.
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, p));
let base = crate::cmd::links::LinkBase::of(st);
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, base, p));
let doc = relative.map_or(own, Arc::new);
let mut params = plan.options.clone();
if is_svg(plan.format) {
@@ -1101,7 +1104,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
+42 -3
View File
@@ -174,7 +174,13 @@ pub(super) fn file_part(s: &str) -> String {
/// every platform. Spaces between the device name and the period are dropped (`CON .png` becomes
/// `CON-.png`).
pub(crate) fn safe_file_name(s: &str) -> String {
let name = file_part(s);
name_without_device(&file_part(s))
}
/// [`safe_file_name`] without [`file_part`]: drops trailing periods and spaces and puts `-` after a
/// Windows device name, and keeps every other character, so a source file name with `\` or `:` keeps
/// it where the file system allows it.
pub(super) fn name_without_device(name: &str) -> String {
let name = name.trim_end_matches(['.', ' ']);
let (base, rest) = name.split_at(name.find('.').unwrap_or(name.len()));
// Windows ignores spaces before the extension, so `CON .png` is the CON device too.
@@ -187,7 +193,10 @@ pub(crate) fn safe_file_name(s: &str) -> String {
}
/// Keys of a format row that aren't encoder options.
const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
/// The writable formats a format row can't name.
pub(crate) const UNWRITTEN_FORMATS: [&str; 5] = ["template", "txt", "dxf", "emf", "wmf"];
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
struct Row {
@@ -208,7 +217,7 @@ impl Row {
return Err(bad(C, "each format is an object {format, scale?, suffix?}"));
}
let format = writable(C, Some(str_param(row, "format").unwrap_or("png")), None)?;
if matches!(format.id, "template" | "txt" | "dxf" | "emf" | "wmf") {
if UNWRITTEN_FORMATS.contains(&format.id) {
return Err(bad(C, "Export for Screens writes png, png8, jpg, webp, gif, tiff, bmp, tga, psd, svg, svgz, pdf, eps, ai or vectorcraft"));
}
// Vector formats have no pixel size: it doesn't apply and adds no @2x suffix (not even one
@@ -279,6 +288,36 @@ impl Row {
/// or where to.
pub const SHARED_KEYS: [&str; 6] = ["formats", "preset", "settings", "prefix", "subfolders", "antiAlias"];
/// The keys `document.exportForScreens` reads: those of [`ScreenParams`], the formats and their
/// settings, `antiAlias`, `exportPreset` and `openLocation`, which the app reads.
pub(crate) const PARAM_KEYS: [&str; 25] = [
"artboard",
"artboards",
"range",
"folder",
"zip",
"fullDocument",
"includeBleed",
"includeArtboardFill",
"subfolders",
"preset",
"prefix",
"assets",
"layers",
"selection",
"name",
"counterStart",
"counterPer",
"date",
"folders",
"pdfs",
"formats",
"settings",
"antiAlias",
"exportPreset",
"openLocation",
];
/// What `document.exportForScreens` reads besides the formats.
#[derive(Default, Deserialize)]
#[serde(default, rename_all = "camelCase")]
+25 -2
View File
@@ -377,8 +377,8 @@ fn open_exts_cover_every_readable_format() {
assert_eq!(filters[0], ("All readable files", OPEN_EXTS));
assert_eq!(
filters.len(),
10 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch libraries, libraries, flattener, PDF, print and export presets, shortcut sets, scripts, plug-ins"
11 + FORMATS.iter().filter(|f| f.read).count(),
"and swatch libraries, libraries, flattener, PDF, print and export presets, composite fonts, shortcut sets, scripts, plug-ins"
);
assert!(filters.contains(&("Export presets", SCREEN_EXPORT_PRESET_EXTS)), "File › Open imports export presets");
assert!(filters.contains(&("Scripts", crate::cmd::scripts::EXTS)), "File › Open checks scripts");
@@ -891,3 +891,26 @@ fn a_photo_places_the_way_its_exif_orientation_says() {
let red = |p: &image::Rgb<u8>| p[0] > 150 && p[1] < 80;
assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12)), "the left half is on top");
}
/// With `importer` named, a file up to the importer's limit is read whole and a larger one is an
/// error, whatever its content.
#[test]
fn read_path_for_a_named_importer_stops_at_the_limit() {
let limit = vectorcraft_plugins::import::MAX_INPUT_BYTES as u64;
let dir = tmp_dir("read-path-limit");
let path = dir.join("drawing.tuv");
let name = path.to_string_lossy().into_owned();
let named = json!({"importer": "plugin.test.notinstalled"});
let sized = |len: u64| {
std::fs::write(&path, b"\x89PNG\r\n\x1a\n").unwrap();
std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(len).unwrap();
};
for len in [8, 64 << 10, 70_000, limit] {
sized(len);
assert_eq!(importer::read_path(&name, &named).unwrap().len() as u64, len);
}
sized(limit + 1);
let e = importer::read_path(&name, &named).unwrap_err();
assert!(e.to_string().contains("larger than") && e.to_string().contains("drawing.tuv"), "{e}");
let _ = std::fs::remove_dir_all(&dir);
}
+50 -2
View File
@@ -445,6 +445,39 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3)], "{r}");
}
/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other
/// Library… in the Symbols panel lists them in the list's order.
#[test]
fn a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols() {
let symbol = |name: &str, x: f64| {
format!(
"%AI14_BeginSymbol\n({name})\n0 A\n0 Xw\n0 Ae\nu\n0 1 1 0 1 0 0 Xa\n{x} 0 m\n{x} 4 L\n{} 4 L\n{} 0 L\nf\nU\n\
%_/ArtDictionary :\n%_5 /Int (AI13PatternRegistrationType) ,\n%_;\n%_\n9 () XW\n%AI10_EndSymbol\n",
x + 4.0,
x + 4.0
)
};
let symbols = format!(
"%AI5_Begin_NonPrinting\n{}{}{}%AI5_End_NonPrinting--\n%AI24_BeginSymbolList\n(Star)\n(Leaf)\n(Arrow)\n%AI24_EndSymbolList\n",
symbol("Arrow", 0.0),
symbol("Leaf", 10.0),
symbol("Star", 20.0)
);
let data = ai::editing_data(200.0, 100.0, &symbols);
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "shapes.ai"});
let r = s.execute("symbol.loadLibrary", &p).unwrap();
assert_eq!((&r["name"], &r["count"]), (&json!("shapes"), &json!(3)), "{r}");
let lib = s.execute("symbol.library", &json!({"library": r["library"]})).unwrap();
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Star", "Leaf", "Arrow"], "{lib}");
let r = open(&mut s, "shapes.ai", &file, json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let names: Vec<&str> = doc.symbols.iter().map(|g| g.name.as_str()).collect();
assert_eq!(names, ["Star", "Leaf", "Arrow"], "{r}");
}
/// A 1-bit RGB image opens from the editing data in the colors its PDF part shows.
#[test]
fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() {
@@ -720,7 +753,7 @@ fn a_file_whose_pdf_part_cant_be_read_outlines_its_type_when_asked() {
assert!(paths > 0, "the outlines are there: {r}");
}
/// An image too large to read from the editing data of a file whose PDF part can't be read is
/// An image whose data is cut short in the editing data of a file whose PDF part can't be read is
/// left out, and both notes say so.
#[test]
fn a_file_whose_pdf_part_cant_be_read_notes_an_image_left_out() {
@@ -729,7 +762,7 @@ fn a_file_whose_pdf_part_cant_be_read_notes_an_image_left_out() {
let mut s = Session::new();
let e = open(&mut s, name, &file, json!({"editingData": false})).unwrap_err().to_string();
let r = open(&mut s, name, &file, json!({})).unwrap();
assert_eq!(r["warnings"], json!([unread_pdf_part(&e), "an image too large to read from the editing data was left out"]), "{r}");
assert_eq!(r["warnings"], json!([unread_pdf_part(&e), "an image whose data is cut short was left out"]), "{r}");
}
/// A copied file whose PDF part can't be read pastes the objects of its editing data when asked
@@ -989,6 +1022,21 @@ fn an_ai_file_saved_without_its_pdf_part_pastes_from_its_editing_data() {
assert!(e.contains("placeholder"), "{e}");
}
/// `file.place` reads a `.ai` saved without its PDF part in the `legacyNameEncoding` it is given.
#[test]
fn an_ai_file_saved_without_its_pdf_part_places_in_the_encoding_picked() {
let mut data = ai::sample_data();
let at = data.windows(4).position(|w| w == b"Pair").unwrap();
// 빨강 in code page 949.
data.splice(at..at + 4, br"\273\241\260\255".iter().copied());
let file = vectorcraft_format::base64_encode(&ai::ai(&compressed(&data), PLACEHOLDER));
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("file.place", &json!({"name": "art.ai", "dataBase64": file, "link": false, "legacyNameEncoding": "windows-949"})).unwrap();
let placed = s.doc().unwrap().doc.layers[0].children().unwrap()[0].clone();
assert_eq!(names(&placed.children().unwrap()[1..]), ["빨강", "Ring", "Window"], "{r}");
}
#[test]
fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
let [sample, damaged, plain] = placeholder_files();
@@ -184,6 +184,41 @@ showpage
assert!(e.contains("junk.eps"), "{e}");
}
/// `legacyNameEncoding` picks the code page of a legacy `.ai`'s layer names that aren't UTF-8; by
/// default they come in as Windows-1252, with a warning naming them. An encoding it doesn't know is
/// refused.
#[test]
fn legacy_ai_layer_names_open_in_the_encoding_picked() {
let mut s = Session::new();
// A layer named 레이어 1 in Windows code page 949.
let ai = b"%!PS-Adobe-3.0\n%%BoundingBox: 0 0 100 100\n%%DocumentNeededResources: procset Adobe_IllustratorA_AI3 1.0 0\n%AI3_TemplateBox: 50 50 50 50\n%%EndComments\n\
%%BeginProlog\n%%IncludeResource: procset Adobe_IllustratorA_AI3 1.0 0\n%%EndProlog\n%%BeginSetup\nAdobe_IllustratorA_AI3 /initialize get exec\n%%EndSetup\n\
%AI5_BeginLayer\n1 1 1 1 0 0 2 0 0 0 Lb\n(\\267\\271\\300\\314\\276\\356 1) Ln\n0 0 0 1 K\n0 i 1 w\n10 10 m\n90 90 L\nS\nLB\n%AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n";
let open_as = |s: &mut Session, encoding: Option<&str>| {
let mut p = json!({"name": "korean.ai", "dataBase64": vectorcraft_format::base64_encode(ai)});
if let Some(e) = encoding {
p["legacyNameEncoding"] = json!(e);
}
s.execute("document.open", &p)
};
let r = open_as(&mut s, None).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].name.as_deref(), Some("·¹À̾î 1"));
assert_eq!(
r["warnings"],
json!(["the name `·¹À̾î 1` isn't UTF-8 and was read as windows-1252: if it looks wrong, open the file with another legacyNameEncoding"])
);
for encoding in ["windows-949", "EUC-KR"] {
let r = open_as(&mut s, Some(encoding)).unwrap();
assert_eq!(s.doc().unwrap().doc.layers[0].name.as_deref(), Some("레이어 1"), "{encoding}");
assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("`레이어 1`") && w.contains("windows-949")), "{r}");
}
let e = open_as(&mut s, Some("utf-16")).unwrap_err();
assert!(
matches!(&e, EngineError::BadParams { msg, .. } if msg == "legacyNameEncoding must be one of windows-1252, macintosh, windows-949, shift_jis, gbk, big5"),
"{e}"
);
}
#[test]
fn eps_files_place_as_one_group_clipped_to_their_bounding_box() {
let mut s = rich();
Loaded 100 of 536 files, more files were not shown because too many files have changed in this diff. Show more