mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-21 01:44:57 +01:00
M2.1: merge current main and keep path-deletion evidence (#3380)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
3deac491ca
372 files changed
+29977
-1928
No files matched your search
Generated
+192
-14
@@ -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=c365d75c48b0e47f4b43cdb6592d0cdc39d2d52e#c365d75c48b0e47f4b43cdb6592d0cdc39d2d52e"
|
||||
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]]
|
||||
@@ -6384,6 +6565,7 @@ dependencies = [
|
||||
name = "vectorcraft-js"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
]
|
||||
@@ -8039,7 +8221,6 @@ dependencies = [
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8054,18 +8235,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 +8265,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"
|
||||
|
||||
+11
-1
@@ -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 = "c365d75c48b0e47f4b43cdb6592d0cdc39d2d52e", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -105,6 +105,16 @@ gif = { version = "0.14", default-features = false, features = ["std", "raii_no_
|
||||
# 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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -245,6 +245,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>"]
|
||||
|
||||
@@ -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 ([`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)
|
||||
}
|
||||
@@ -87,12 +88,18 @@ 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. 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 (`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.
|
||||
///
|
||||
@@ -102,7 +109,8 @@ pub(crate) fn titlebar_from_env() -> bool {
|
||||
/// ([`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
|
||||
/// 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
|
||||
/// ([`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,7 +132,8 @@ 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. 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
|
||||
@@ -133,7 +142,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
/// 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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
+28
-15
@@ -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
|
||||
@@ -437,7 +438,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 +654,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 +680,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 +872,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 +1217,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 +1237,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
|
||||
|
||||
@@ -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.
|
||||
@@ -682,6 +685,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]
|
||||
|
||||
@@ -117,9 +117,9 @@ 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;
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -23,10 +23,10 @@ pub use composite::{
|
||||
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};
|
||||
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,
|
||||
@@ -86,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`].
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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::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};
|
||||
|
||||
@@ -90,6 +90,7 @@ 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,
|
||||
|
||||
@@ -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.
|
||||
@@ -322,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,
|
||||
@@ -353,6 +358,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
..
|
||||
@@ -377,6 +383,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
}
|
||||
@@ -405,6 +412,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
..
|
||||
@@ -428,6 +436,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_type,
|
||||
roman_hanging,
|
||||
kashida,
|
||||
}
|
||||
@@ -492,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
|
||||
|
||||
@@ -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)]
|
||||
|
||||
+26
-23
@@ -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
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, ¶ms);
|
||||
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:?}");
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 })
|
||||
@@ -240,17 +263,32 @@ impl Carry {
|
||||
/// 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_positioned_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),
|
||||
}
|
||||
}
|
||||
@@ -340,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
@@ -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) {
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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, gives_image_shape, 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_meshes_of, 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,
|
||||
};
|
||||
@@ -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`]).
|
||||
|
||||
@@ -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()
|
||||
|
||||
+287
-67
@@ -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
|
||||
@@ -163,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() {
|
||||
@@ -286,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,
|
||||
@@ -303,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();
|
||||
@@ -323,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;
|
||||
@@ -433,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -480,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(),
|
||||
@@ -494,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) => {
|
||||
@@ -532,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);
|
||||
@@ -596,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
|
||||
@@ -629,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;
|
||||
@@ -658,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, ¶ms, 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, ¶ms, 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);
|
||||
@@ -707,7 +762,8 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
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;
|
||||
}
|
||||
@@ -717,8 +773,12 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], budget: Budget, apart: b
|
||||
return;
|
||||
};
|
||||
used = used.minus(before).plus(Budget::of(&out));
|
||||
if follows && !boxes && leaf.appearance.has_positioned_gradient() {
|
||||
crate::Carry::of(&e.id, ¶ms, 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, ¶ms, bounds, path.bounds(), None, seed);
|
||||
if carry.moves(&leaf.appearance) {
|
||||
carry.apply(&mut leaf.appearance);
|
||||
}
|
||||
}
|
||||
set_geometry(leaf, out, rule);
|
||||
});
|
||||
@@ -734,8 +794,8 @@ 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 that its bounds measure 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() {
|
||||
@@ -773,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 {
|
||||
@@ -835,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
|
||||
@@ -858,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 };
|
||||
@@ -887,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;
|
||||
};
|
||||
@@ -915,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, ¶ms, &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, ¶ms, ctx.seed);
|
||||
let options = crate::distort::TransformOptions::of(¶ms);
|
||||
let map = crate::distort::transform_affine(tb, ¶ms, ctx.seed);
|
||||
@@ -928,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() {
|
||||
@@ -947,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() {
|
||||
@@ -965,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, ¶ms, seed);
|
||||
@@ -979,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));
|
||||
@@ -1051,7 +1260,7 @@ 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
|
||||
/// 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);
|
||||
|
||||
@@ -1068,7 +1277,7 @@ 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_positioned_gradient() {
|
||||
if is_member_group(c) && (c.appearance.has_positioned_gradient() || c.appearance.has_unplaced_gradient()) {
|
||||
out.push((at.clone(), b, h));
|
||||
}
|
||||
at.pop();
|
||||
@@ -1222,6 +1431,10 @@ 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,
|
||||
@@ -1264,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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> {
|
||||
@@ -476,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));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
+29
-11
@@ -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") };
|
||||
@@ -491,7 +509,7 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
|
||||
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);
|
||||
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();
|
||||
@@ -500,7 +518,7 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -531,7 +549,7 @@ fn edited_freeform_points_follow_a_transform_effect_and_free_distort() {
|
||||
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);
|
||||
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);
|
||||
@@ -607,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));
|
||||
|
||||
@@ -634,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");
|
||||
|
||||
@@ -642,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");
|
||||
|
||||
@@ -650,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");
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -356,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 ----------
|
||||
|
||||
@@ -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);
|
||||
@@ -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<_>>() }))
|
||||
}
|
||||
|
||||
@@ -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), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), 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)
|
||||
),
|
||||
|
||||
@@ -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(¶ms, &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() {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -30,7 +30,7 @@ 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, "edit.colors.invert", "Invert Colors", &invert)
|
||||
),
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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, "edit.colors.toCMYK", "Convert to CMYK", &to_cmyk)
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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, "edit.colors.toRGB", "Convert to RGB", &|c| {
|
||||
@@ -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(©.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>,
|
||||
@@ -342,19 +407,107 @@ pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str,
|
||||
}
|
||||
|
||||
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
|
||||
/// errors name the command `cmd`.
|
||||
/// 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 = match ids_param(p, "ids", cmd)? {
|
||||
Some(v) => v,
|
||||
None => selected_roots(s)?,
|
||||
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(cmd, e))?;
|
||||
Ok(n)
|
||||
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> {
|
||||
|
||||
@@ -71,24 +71,39 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// 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. Whether a composite font was added, changed or removed.
|
||||
pub(crate) fn sync(s: &mut Session) -> bool {
|
||||
/// 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 = false;
|
||||
let mut changed = Vec::new();
|
||||
for f in s.active().map(|d| d.doc.composite_fonts.to_vec()).unwrap_or_default() {
|
||||
changed |= db.set_composite_font(&f);
|
||||
names.push(f.name.to_lowercase());
|
||||
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 {
|
||||
changed |= db.remove_composite_font(&gone);
|
||||
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();
|
||||
@@ -172,6 +187,9 @@ fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()
|
||||
}
|
||||
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)) {
|
||||
|
||||
@@ -395,6 +395,150 @@ fn opened_document_measures_missing_composite_font_as_missing() {
|
||||
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() {
|
||||
|
||||
@@ -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")));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -946,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)?;
|
||||
@@ -994,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.
|
||||
|
||||
@@ -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, ¶ms)) {
|
||||
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, ¶ms) } 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)));
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -135,9 +139,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 +208,8 @@ mod tests_pdfoutput;
|
||||
#[cfg(test)]
|
||||
mod tests_tiffbmp;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_jxlread;
|
||||
#[cfg(test)]
|
||||
mod tests_pdfx;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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, ¶ms).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, ¶ms).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");
|
||||
|
||||
@@ -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), 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 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)",
|
||||
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
|
||||
),
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<_>>(),
|
||||
}))
|
||||
}
|
||||
@@ -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, ¶ms, 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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -567,10 +570,15 @@ impl ReadFile {
|
||||
/// [`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 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 })
|
||||
@@ -681,7 +689,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);
|
||||
@@ -747,7 +762,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) {
|
||||
@@ -755,25 +771,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);
|
||||
@@ -819,7 +839,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
|
||||
@@ -830,11 +850,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,
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Reading JPEG XL images: the bare codestream and the container, alpha, 16-bit samples, the size
|
||||
//! check before decoding, and damaged files refused without a panic.
|
||||
|
||||
use serde_json::json;
|
||||
use zune_core::bit_depth::BitDepth;
|
||||
use zune_core::colorspace::ColorSpace;
|
||||
use zune_core::options::EncoderOptions;
|
||||
|
||||
use super::jxlread::{ToSrgb, decode, is_jxl, oriented_resolution, output_profile, pixel_boxes, to_rgba};
|
||||
use super::*;
|
||||
|
||||
/// A lossless JPEG XL codestream of `w` × `h` pixels: `samples` in `space`, 8-bit, or 16-bit in
|
||||
/// native byte order.
|
||||
fn jxl(w: usize, h: usize, space: ColorSpace, depth: BitDepth, samples: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
zune_jpegxl::JxlSimpleEncoder::new(samples, EncoderOptions::new(w, h, space, depth)).encode(&mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// `codestream` in the ISOBMFF container: the signature box, `ftyp` and a `jxlc` box holding it.
|
||||
fn container(codestream: &[u8]) -> Vec<u8> {
|
||||
let mut f = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a];
|
||||
f.extend(20u32.to_be_bytes());
|
||||
f.extend(b"ftypjxl \0\0\0\0jxl ");
|
||||
f.extend((8 + codestream.len() as u32).to_be_bytes());
|
||||
f.extend(b"jxlc");
|
||||
f.extend(codestream);
|
||||
f
|
||||
}
|
||||
|
||||
/// A 3 × 2 RGBA image: opaque red, green and blue, then half-transparent, clear and opaque gray.
|
||||
const RGBA: [[u8; 4]; 6] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [200, 100, 50, 128], [9, 9, 9, 0], [77, 77, 77, 255]];
|
||||
|
||||
fn rgba8() -> Vec<u8> {
|
||||
jxl(3, 2, ColorSpace::RGBA, BitDepth::Eight, RGBA.as_flattened())
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
vectorcraft_format::base64_encode(bytes)
|
||||
}
|
||||
|
||||
/// The pixels of the one image the active document holds.
|
||||
fn stored_pixels(s: &Session) -> Vec<[u8; 4]> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.images.len(), 1);
|
||||
let blob = doc.images.values().next().unwrap();
|
||||
assert_eq!(blob.mime, "image/png", "stored as PNG");
|
||||
image::load_from_memory(&blob.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jxl_images_open_and_place_with_their_pixels_and_alpha() {
|
||||
let bare = rgba8();
|
||||
let boxed = container(&bare);
|
||||
assert!(is_jxl(&bare) && is_jxl(&boxed) && !is_jxl(b"\xff\xd8\xff"));
|
||||
for (name, bytes) in [("bare.jxl", &bare), ("boxed.jxl", &boxed), ("named-wrong.png", &boxed)] {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": b64(bytes)})).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(r["format"], "jxl", "{name}: told by its content");
|
||||
let ab = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!((ab.width(), ab.height()), (3.0, 2.0), "{name}: 72 ppi, one point a pixel");
|
||||
assert_eq!(stored_pixels(&s), RGBA, "{name}");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": name, "dataBase64": b64(bytes)})).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(3.0), Some(2.0)), "{name}: {r}");
|
||||
assert_eq!(stored_pixels(&s), RGBA, "{name}: placed");
|
||||
}
|
||||
assert!(OPEN_EXTS.contains(&"jxl") && PLACE_EXTS.contains(&"jxl"));
|
||||
assert!(open_filters().any(|f| f == ("JPEG XL", &["jxl"][..])) && place_filters().any(|f| f == ("JPEG XL", &["jxl"][..])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_copy_stays_within_the_input_allowance() {
|
||||
let f = container(&[0; 128]);
|
||||
assert!(pixel_boxes(&f, 64).unwrap_err().contains("too large"));
|
||||
assert_eq!(pixel_boxes(&f, f.len() as u64).unwrap().unwrap(), f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_exif_resolution_sizes_open_and_place() {
|
||||
let bare = rgba8();
|
||||
let mut f = container(&[]);
|
||||
f.truncate(32);
|
||||
let mut exif = Vec::new();
|
||||
exif.extend(4u32.to_be_bytes());
|
||||
exif.extend(b"Exif");
|
||||
exif.extend(b"II*\0");
|
||||
exif.extend(8u32.to_le_bytes());
|
||||
exif.extend(3u16.to_le_bytes());
|
||||
for (tag, value) in [(282u16, 50u32), (283, 58), (296, 2)] {
|
||||
exif.extend(tag.to_le_bytes());
|
||||
exif.extend((if tag == 296 { 3u16 } else { 5 }).to_le_bytes());
|
||||
exif.extend(1u32.to_le_bytes());
|
||||
exif.extend(value.to_le_bytes());
|
||||
}
|
||||
exif.extend(0u32.to_le_bytes());
|
||||
for value in [144u32, 1, 72, 1] {
|
||||
exif.extend(value.to_le_bytes());
|
||||
}
|
||||
f.extend((8 + exif.len() as u32).to_be_bytes());
|
||||
f.extend(b"Exif");
|
||||
f.extend(&exif);
|
||||
f.extend((8 + bare.len() as u32).to_be_bytes());
|
||||
f.extend(b"jxlc");
|
||||
f.extend(&bare);
|
||||
assert_eq!(super::ppi::resolution(&f), Some((144.0, 72.0)));
|
||||
assert_eq!(super::ppi::resolution(&bare), None);
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "resolved.jxl", "dataBase64": b64(&f)})).unwrap();
|
||||
let rect = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!((rect.width(), rect.height()), (1.5, 2.0));
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "resolved.jxl", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(1.5), Some(2.0)));
|
||||
assert_eq!(super::ppi::resolution(&s.doc().unwrap().doc.images.values().next().unwrap().bytes), Some((144.0, 72.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jxl_axis_exchanging_orientations_swap_resolution() {
|
||||
let ppi = Some((144.0, 72.0));
|
||||
for orientation in 1..=8 {
|
||||
let expected = if orientation >= 5 { Some((72.0, 144.0)) } else { ppi };
|
||||
assert_eq!(oriented_resolution(ppi, orientation), expected, "orientation {orientation}");
|
||||
}
|
||||
assert_eq!(oriented_resolution(None, 6), None);
|
||||
}
|
||||
|
||||
/// A `.jxl` file copied in a file manager pastes as its image.
|
||||
#[test]
|
||||
fn a_copied_jxl_file_pastes_as_its_image() {
|
||||
use crate::cmd::clipboard::{FILE_HEAD, PASTE_ORDER, file_flavour};
|
||||
let f = container(&rgba8());
|
||||
let mime = file_flavour("copied.jxl", &f[..f.len().min(FILE_HEAD)], &PASTE_ORDER);
|
||||
assert_eq!(mime, Some("image/jxl"));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let r = s.execute("clipboard.importImage", &json!({"dataBase64": b64(&f), "mime": mime})).unwrap();
|
||||
assert_eq!((r["pixelWidth"].as_u64(), r["pixelHeight"].as_u64()), (Some(3), Some(2)), "{r}");
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(stored_pixels(&s), RGBA);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_samples_become_eight_bits() {
|
||||
let rgb: [[u16; 3]; 4] = [[0x0000, 0x8080, 0xffff], [0x1234, 0x80ff, 0x7f00], [0xff00, 0x00ff, 0x4000], [0xc000, 0x0101, 0xfefe]];
|
||||
let samples: Vec<u8> = rgb.as_flattened().iter().flat_map(|v| v.to_ne_bytes()).collect();
|
||||
let f = jxl(2, 2, ColorSpace::RGB, BitDepth::Sixteen, &samples);
|
||||
let to8 = |v: u16| (f64::from(v) / 65535.0 * 255.0).round() as u8;
|
||||
let want: Vec<[u8; 4]> = rgb.iter().map(|p| [to8(p[0]), to8(p[1]), to8(p[2]), 255]).collect();
|
||||
assert_eq!(decode(&f, 1 << 30).unwrap().0.pixels().map(|p| p.0).collect::<Vec<_>>(), want);
|
||||
// Gray, 16 bits, in the container, opened as a document.
|
||||
let gray: Vec<u8> = [0xffffu16, 0x8080, 0x0000, 0x4040].iter().flat_map(|v| v.to_ne_bytes()).collect();
|
||||
let f = container(&jxl(2, 2, ColorSpace::Luma, BitDepth::Sixteen, &gray));
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "gray.jxl", "dataBase64": b64(&f)})).unwrap();
|
||||
assert_eq!(stored_pixels(&s), [[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255], [64, 64, 64, 255]]);
|
||||
}
|
||||
|
||||
/// A bare codestream that is only a header: `w` × `h` pixels and default metadata.
|
||||
fn header_only(w: u32, h: u32) -> Vec<u8> {
|
||||
// Each field's bits, read from the lowest bit of each byte up: `div8`, the height as a U32
|
||||
// (selector 3: 1 + 30 bits), `ratio` 0, the width likewise, then `all_default` for the
|
||||
// metadata and `default_m` for the transform data.
|
||||
let fields = [(0, 1), (3, 2), (h - 1, 30), (0, 3), (3, 2), (w - 1, 30), (1, 1), (1, 1)];
|
||||
let (mut out, mut acc, mut n) = (vec![0xff, 0x0a], 0u64, 0);
|
||||
for (v, bits) in fields {
|
||||
acc |= u64::from(v) << n;
|
||||
n += bits;
|
||||
while n >= 8 {
|
||||
out.push(acc as u8);
|
||||
(acc, n) = (acc >> 8, n - 8);
|
||||
}
|
||||
}
|
||||
out.push(acc as u8);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_too_large_is_refused_from_its_header() {
|
||||
// The header of a 100000 × 100000 image (40 GB as RGBA), with no pixel data after it.
|
||||
let huge = header_only(100_000, 100_000);
|
||||
assert_eq!(decode(&huge, MAX_RASTER_ALLOC).unwrap_err(), "an image of 100000 × 100000 pixels is too large to draw");
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"name": "huge.jxl", "dataBase64": b64(&huge)})).unwrap_err().to_string();
|
||||
assert!(e.contains("too large to draw"), "{e}");
|
||||
// The allowance counts RGBA bytes: 3 × 2 pixels take 24.
|
||||
assert!(decode(&rgba8(), 23).unwrap_err().contains("too large"));
|
||||
assert!(decode(&rgba8(), 1 << 20).is_ok());
|
||||
}
|
||||
|
||||
/// The decoder's buffers take more than the image as RGBA. When they need more than the allowance,
|
||||
/// the image is too large to draw, as when its size alone is.
|
||||
#[test]
|
||||
fn an_image_whose_decoder_buffers_pass_the_allowance_is_too_large() {
|
||||
assert_eq!(decode(&rgba8(), 24).unwrap_err(), "an image of 3 × 2 pixels is too large to draw");
|
||||
let gray: Vec<u8> = (0..64 * 64).map(|i| (i % 251) as u8).collect();
|
||||
let f = container(&jxl(64, 64, ColorSpace::Luma, BitDepth::Eight, &gray));
|
||||
assert_eq!(decode(&f, 64 * 64 * 4).unwrap_err(), "an image of 64 × 64 pixels is too large to draw");
|
||||
assert!(decode(&f, 1 << 20).is_ok());
|
||||
// A file cut short is still reported as cut short or unreadable.
|
||||
let e = decode(&f[..f.len() - 3], 1 << 20).unwrap_err();
|
||||
assert!(!e.contains("too large"), "{e}");
|
||||
}
|
||||
|
||||
/// Premultiplied colors are divided by their alpha before they are converted to sRGB: a linear
|
||||
/// 0.25 at alpha 0.5 is a straight linear 0.5, which sRGB stores as 0.735 (188 of 255).
|
||||
#[test]
|
||||
fn associated_alpha_is_divided_out_before_the_color_conversion() {
|
||||
use jxl_oxide::{ColorEncodingWithProfile, EnumColourEncoding, NullCms, RenderingIntent};
|
||||
let srgb = EnumColourEncoding::srgb(RenderingIntent::Relative);
|
||||
let linear = EnumColourEncoding { tf: jxl_oxide::color::TransferFunction::Linear, ..srgb.clone() };
|
||||
let header = jxl_oxide::JxlImage::builder().read(&rgba8()[..]).unwrap();
|
||||
let m = &header.image_header().metadata;
|
||||
let to_srgb = ToSrgb::Transform(
|
||||
jxl_color::ColorTransform::new(
|
||||
&ColorEncodingWithProfile::new(linear),
|
||||
&ColorEncodingWithProfile::new(srgb),
|
||||
&m.opsin_inverse_matrix,
|
||||
&m.tone_mapping,
|
||||
&NullCms,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let mut colors = [vec![0.0; 2], vec![0.0; 2], vec![0.0; 2]];
|
||||
let mut out = [0u8; 8];
|
||||
for convert in [&to_srgb, &ToSrgb::Curve] {
|
||||
to_rgba(&[0.25, 0.25, 0.25, 0.5, 0.0, 0.0, 0.0, 0.0], 4, true, Some(convert), &mut colors, &mut out).unwrap();
|
||||
assert_eq!(out, [188, 188, 188, 128, 0, 0, 0, 0]);
|
||||
// Straight alpha is left as it is.
|
||||
to_rgba(&[0.25, 0.25, 0.25, 0.5, 1.0, 1.0, 1.0, 1.0], 4, false, Some(convert), &mut colors, &mut out).unwrap();
|
||||
assert_eq!(out, [137, 137, 137, 128, 255, 255, 255, 255]);
|
||||
}
|
||||
// Gray with another white point converts through three channels and comes back as gray.
|
||||
let gray_e = EnumColourEncoding {
|
||||
white_point: jxl_oxide::color::WhitePoint::E,
|
||||
tf: jxl_oxide::color::TransferFunction::Linear,
|
||||
..EnumColourEncoding::gray_srgb(RenderingIntent::Relative)
|
||||
};
|
||||
let gray_srgb = ColorEncodingWithProfile::new(EnumColourEncoding::gray_srgb(RenderingIntent::Relative));
|
||||
let to_gray =
|
||||
jxl_color::ColorTransform::new(&ColorEncodingWithProfile::new(gray_e), &gray_srgb, &m.opsin_inverse_matrix, &m.tone_mapping, &NullCms)
|
||||
.unwrap();
|
||||
to_rgba(&[0.25, 0.5, 1.0, 1.0], 2, true, Some(&ToSrgb::Transform(to_gray)), &mut colors, &mut out).unwrap();
|
||||
assert_eq!(out, [188, 188, 188, 128, 255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
/// A container's Exif and Brotli-compressed boxes are left out: an unreadable `brob` box before the
|
||||
/// codestream doesn't stop the image from opening.
|
||||
#[test]
|
||||
fn metadata_boxes_are_not_read() {
|
||||
let mut f = container(&[]);
|
||||
f.truncate(32); // the signature and `ftyp`
|
||||
let mut boxed = |ty: &[u8], body: &[u8]| {
|
||||
f.extend((8 + body.len() as u32).to_be_bytes());
|
||||
f.extend(ty);
|
||||
f.extend(body);
|
||||
};
|
||||
boxed(b"Exif", &[0, 0, 0, 0, b'M', b'M', 0, 42]);
|
||||
boxed(b"brob", &[b'x', b'm', b'l', b' ', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
boxed(b"jxlc", &rgba8());
|
||||
assert_eq!(decode(&f, 1 << 30).unwrap().0.pixels().map(|p| p.0).collect::<Vec<_>>(), RGBA);
|
||||
}
|
||||
|
||||
/// Colors left in their embedded RGB profile keep it: the PNG they are stored in carries the
|
||||
/// profile. Colors converted to sRGB, and a gray image's colors, which come back as RGB, are stored
|
||||
/// without one.
|
||||
#[test]
|
||||
fn colors_left_in_their_icc_profile_keep_it() {
|
||||
use image::ImageDecoder as _;
|
||||
use jxl_oxide::{EnumColourEncoding, RenderingIntent};
|
||||
// A profile jxl-color can't turn into a JPEG XL color space, so the decoder leaves the colors
|
||||
// in it: the sRGB profile with the tag of its red curve renamed.
|
||||
let unnamed = |encoding: &EnumColourEncoding, curve: &[u8; 4]| {
|
||||
let mut icc = jxl_color::icc::colour_encoding_to_icc(encoding);
|
||||
let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize;
|
||||
for at in (0..count).map(|i| 132 + 12 * i) {
|
||||
if icc[at..at + 4] == curve[..] {
|
||||
icc[at..at + 4].copy_from_slice(b"xTRC");
|
||||
}
|
||||
}
|
||||
icc
|
||||
};
|
||||
let srgb = EnumColourEncoding::srgb(RenderingIntent::Relative);
|
||||
let rgb = unnamed(&srgb, b"rTRC");
|
||||
assert_ne!(rgb, jxl_color::icc::colour_encoding_to_icc(&srgb), "a tag renamed");
|
||||
assert_eq!(output_profile(false, false, Some(&rgb)).unwrap(), Some(rgb.clone()));
|
||||
assert_eq!(output_profile(true, false, Some(&rgb)).unwrap(), None, "XYB-encoded colors become sRGB");
|
||||
assert_eq!(output_profile(false, false, Some(&jxl_color::icc::colour_encoding_to_icc(&srgb))).unwrap(), None, "converted to sRGB");
|
||||
let gray = unnamed(&EnumColourEncoding::gray_srgb(RenderingIntent::Relative), b"kTRC");
|
||||
assert!(!jxl_oxide::ColorEncodingWithProfile::with_icc(&gray).unwrap().icc_profile().is_empty());
|
||||
assert_eq!(output_profile(false, true, Some(&gray)).unwrap_err(), "the JPEG XL file can't be read: unsupported grayscale ICC profile");
|
||||
assert_eq!(
|
||||
output_profile(false, true, Some(&jxl_color::icc::colour_encoding_to_icc(&EnumColourEncoding::gray_srgb(RenderingIntent::Relative))))
|
||||
.unwrap(),
|
||||
None
|
||||
);
|
||||
assert_eq!(output_profile(false, false, None).unwrap(), None);
|
||||
// A color image left in a profile that is not an RGB one can't be stored as RGB.
|
||||
let mut lab = rgb.clone();
|
||||
lab[16..20].copy_from_slice(b"Lab ");
|
||||
assert_eq!(output_profile(false, false, Some(&lab)).unwrap_err(), "the JPEG XL file can't be read: unsupported ICC profile color space");
|
||||
assert_eq!(output_profile(true, false, Some(&lab)).unwrap(), None, "XYB-encoded colors become sRGB");
|
||||
// The PNG carries the profile, the pixels and the resolution.
|
||||
let img = image::RgbaImage::from_raw(2, 1, vec![200, 100, 50, 255, 9, 9, 9, 0]).unwrap();
|
||||
for icc in [Some(rgb), None] {
|
||||
let RasterImage { blob, width, height, .. } = super::load::as_png(img.clone(), icc.clone(), Some((144.0, 144.0))).unwrap();
|
||||
assert_eq!((width, height), (2, 1));
|
||||
let mut png = image::codecs::png::PngDecoder::new(std::io::Cursor::new(&blob.bytes[..])).unwrap();
|
||||
assert_eq!(png.icc_profile().unwrap(), icc);
|
||||
assert_eq!(image::DynamicImage::from_decoder(png).unwrap().to_rgba8(), img);
|
||||
assert_eq!(super::ppi::resolution(&blob.bytes).map(|(x, y)| (x.round(), y.round())), Some((144.0, 144.0)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_files_are_refused_without_a_panic() {
|
||||
let good = rgba8();
|
||||
for n in 0..good.len() {
|
||||
assert!(decode(&good[..n], 1 << 30).is_err(), "cut at {n}");
|
||||
}
|
||||
// Every byte changed in turn: an error or an image, never a panic.
|
||||
for i in 0..good.len() {
|
||||
for v in [0, 1, 0x7f, 0x80, 0xff] {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = decode(&f, 1 << 30);
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let cut = &good[..good.len() - 3];
|
||||
assert!(s.execute("file.place", &json!({"name": "cut.jxl", "dataBase64": b64(cut)})).is_err());
|
||||
}
|
||||
@@ -42,7 +42,10 @@ use data::{fmt_value, parse_csv, to_csv};
|
||||
use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{capture_label_styles, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets, shown_paint};
|
||||
pub(crate) use series::{
|
||||
capture_label_styles, capture_series_object_opacity, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,3 +1,5 @@
|
||||
use vectorcraft_color::BlendMode;
|
||||
|
||||
use super::axis::radar_axis;
|
||||
use super::labels::{Role, filled_lines_on, label_style};
|
||||
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
|
||||
@@ -26,26 +28,43 @@ pub(super) fn series_marks(g: &GraphSpec, i: usize, series_fill: bool, stroke: P
|
||||
(fill, stroke, width)
|
||||
}
|
||||
|
||||
/// The paths directly inside series `i`'s group (`items`) with the series' kept fill and stroke opacity on their
|
||||
/// topmost fill and stroke. Other art, such as a graph design, keeps its own opacity. A value read from a file is
|
||||
/// held to 0..1, and one that is not a number is left out.
|
||||
/// The paths directly inside series `i`'s group (`items`) with the series' kept fill and stroke opacity and blend mode on
|
||||
/// their topmost fill and stroke, and its kept object opacity and blend mode. Other art, such as a graph design, keeps its
|
||||
/// own. An opacity read from a file is held to 0..1, and one that is not a number is left out.
|
||||
pub(super) fn with_series_opacity(g: &GraphSpec, i: usize, mut items: Vec<Arc<Node>>) -> Vec<Arc<Node>> {
|
||||
let Some(slot) = g.series_paints.get(i) else { return items };
|
||||
let kept = |o: Option<f32>| o.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
|
||||
let (fill, stroke) = (kept(slot.fill_opacity), kept(slot.stroke_opacity));
|
||||
if fill.is_none() && stroke.is_none() {
|
||||
let (fill, stroke, object) = (kept(slot.fill_opacity), kept(slot.stroke_opacity), kept(slot.opacity));
|
||||
if fill.is_none() && stroke.is_none() && object.is_none() && slot.fill_blend.is_none() && slot.stroke_blend.is_none() && slot.blend.is_none() {
|
||||
return items;
|
||||
}
|
||||
for item in &mut items {
|
||||
if !matches!(item.kind, NodeKind::Path { .. }) {
|
||||
continue;
|
||||
}
|
||||
let ap = &mut Arc::make_mut(item).appearance;
|
||||
if let (Some(o), Some(f)) = (fill, ap.fill_mut()) {
|
||||
f.opacity = o;
|
||||
let n = Arc::make_mut(item);
|
||||
if let Some(o) = object {
|
||||
n.opacity = o;
|
||||
}
|
||||
if let (Some(o), Some(st)) = (stroke, ap.stroke_mut()) {
|
||||
st.opacity = o;
|
||||
if let Some(b) = slot.blend {
|
||||
n.blend = b;
|
||||
}
|
||||
let ap = &mut n.appearance;
|
||||
if let Some(f) = ap.fill_mut() {
|
||||
if let Some(o) = fill {
|
||||
f.opacity = o;
|
||||
}
|
||||
if let Some(b) = slot.fill_blend {
|
||||
f.blend = b;
|
||||
}
|
||||
}
|
||||
if let Some(st) = ap.stroke_mut() {
|
||||
if let Some(o) = stroke {
|
||||
st.opacity = o;
|
||||
}
|
||||
if let Some(b) = slot.stroke_blend {
|
||||
st.blend = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
items
|
||||
@@ -216,10 +235,10 @@ fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, P
|
||||
changed
|
||||
}
|
||||
|
||||
/// Copy the opacity of the topmost visible fill (`true`) or stroke (`false`) of generated series art just edited (`edited`:
|
||||
/// each object with the kind of row) into that series' fill or stroke opacity; art left without a row of that kind
|
||||
/// keeps none. Called inside the same document edit, so both undo together. Returns whether a series' kept opacity
|
||||
/// changed.
|
||||
/// Copy the opacity and blend mode of the topmost visible fill (`true`) or stroke (`false`) of generated series art just
|
||||
/// edited (`edited`: each object with the kind of row) into that series' fill or stroke opacity and blend mode; art left
|
||||
/// without a row of that kind keeps neither. Called inside the same document edit, so both undo together. Returns
|
||||
/// whether a series' kept opacity or blend mode changed.
|
||||
pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool)]) -> bool {
|
||||
if edited.is_empty() {
|
||||
return false;
|
||||
@@ -236,14 +255,15 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
|
||||
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
|
||||
let row = node.appearance.items.iter().rev().find(|it| it.is_fill() == *fill && it.visible());
|
||||
let opacity = row.map_or(1.0, vectorcraft_doc::AppearanceItem::opacity);
|
||||
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity)))
|
||||
let blend = row.map_or(BlendMode::Normal, vectorcraft_doc::AppearanceItem::blend);
|
||||
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity), (blend != BlendMode::Normal).then_some(blend)))
|
||||
})
|
||||
.collect();
|
||||
let mut changed = false;
|
||||
for (graph, index, fill, kept) in captures {
|
||||
for (graph, index, fill, kept, blend) in captures {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
// A fully opaque row on a series the graph keeps nothing for leaves the graph as it is.
|
||||
if kept.is_none() && spec.series_paints.len() <= index {
|
||||
// A fully opaque Normal row on a series the graph keeps nothing for leaves the graph as it is.
|
||||
if kept.is_none() && blend.is_none() && spec.series_paints.len() <= index {
|
||||
continue;
|
||||
}
|
||||
let was = spec.series_paints.clone();
|
||||
@@ -253,15 +273,73 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
|
||||
}
|
||||
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
|
||||
if fill {
|
||||
slot.fill_opacity = kept;
|
||||
(slot.fill_opacity, slot.fill_blend) = (kept, blend);
|
||||
} else {
|
||||
slot.stroke_opacity = kept;
|
||||
(slot.stroke_opacity, slot.stroke_blend) = (kept, blend);
|
||||
}
|
||||
changed |= spec.series_paints != was;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity
|
||||
/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object
|
||||
/// opacity or blend mode changed.
|
||||
pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
// A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is.
|
||||
if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index {
|
||||
continue;
|
||||
}
|
||||
let was = spec.series_paints.clone();
|
||||
// `index` is below the graph's series count (`series_members`).
|
||||
if spec.series_paints.len() <= index {
|
||||
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
|
||||
}
|
||||
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
|
||||
(slot.opacity, slot.blend) = (opacity, blend);
|
||||
changed |= spec.series_paints != was;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying
|
||||
/// it.
|
||||
pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool {
|
||||
let mut after: HashMap<(NodeId, usize), (Option<f32>, Option<BlendMode>)> = HashMap::new();
|
||||
let stored = |graph: NodeId, index: usize| {
|
||||
let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref());
|
||||
spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend))
|
||||
};
|
||||
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
|
||||
after.insert((graph, index), (opacity, blend));
|
||||
}
|
||||
after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair)
|
||||
}
|
||||
|
||||
/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a
|
||||
/// series group, in order.
|
||||
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option<f32>, Option<BlendMode>)> {
|
||||
if edited.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let members = series_members(doc);
|
||||
if members.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
edited
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
|
||||
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
|
||||
Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Graph Data › Transpose row/column: categories become series and series categories.
|
||||
pub(super) fn transpose(g: &mut GraphSpec) {
|
||||
let cells = g.cells();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{CharStyle, ColumnDesign, ColumnType, Fractions, GraphKind, GraphSpec, NodeKind};
|
||||
|
||||
use crate::{NodeId, Session};
|
||||
@@ -347,14 +347,14 @@ fn clearing_a_series_marks_appearance_forgets_its_kept_opacity() {
|
||||
}
|
||||
|
||||
/// Removing the fill whose opacity the graph keeps takes the kept opacity away; an edit that leaves a mark opaque
|
||||
/// (a blend mode alone) keeps nothing for its series.
|
||||
/// and Normal (an opacity of 100% alone) keeps nothing for its series.
|
||||
#[test]
|
||||
fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "blend": "multiply"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 100})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.is_empty());
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": 0, "opacity": 40})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.4));
|
||||
@@ -503,6 +503,198 @@ fn a_stroke_opacity_on_a_series_line_survives_regeneration() {
|
||||
assert!(!after.is_empty() && after.iter().all(|m| m.appearance.stroke().unwrap().opacity == 0.6));
|
||||
}
|
||||
|
||||
/// Each mark of series `index`: its object opacity and blend mode, and the blend modes of its top fill and stroke.
|
||||
fn transparency_of(s: &Session, id: NodeId, index: u32) -> Vec<(f32, BlendMode, BlendMode, BlendMode)> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let marks = series(&n, index).children().unwrap().to_vec();
|
||||
marks.iter().map(|m| (m.opacity, m.blend, m.appearance.fill().unwrap().blend, m.appearance.stroke().unwrap().blend)).collect()
|
||||
}
|
||||
|
||||
/// An object opacity and blend mode set on one series mark with no fill or stroke row picked are kept by the graph:
|
||||
/// every mark of that series has them after the graph is drawn again, through save and open, the other series stay
|
||||
/// opaque and Normal, 100% and Normal forget them, and undo takes them back.
|
||||
#[test]
|
||||
fn an_object_opacity_and_blend_mode_on_a_series_mark_survive_regeneration() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap();
|
||||
assert_eq!(restored, spec(&s, id));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let normal = BlendMode::Normal;
|
||||
assert!(transparency_of(&s, id, 0).iter().all(|t| *t == (0.4, BlendMode::Multiply, normal, normal)), "{:?}", transparency_of(&s, id, 0));
|
||||
assert!(transparency_of(&s, id, 1).iter().all(|t| *t == (1.0, normal, normal, normal)), "{:?}", transparency_of(&s, id, 1));
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "opacity": 100, "blend": "normal"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the edit and what the graph stored");
|
||||
}
|
||||
|
||||
/// `object.setProps` with the opacity a mark already shows replaces the opacity another mark of the series left on the
|
||||
/// graph, in one undo step, and an opacity on a graph design's copy in a series is not kept.
|
||||
#[test]
|
||||
fn an_object_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.5));
|
||||
s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 100})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, None);
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert!(transparency_of(&s, id, 0).iter().all(|t| t.0 == 1.0), "{:?}", transparency_of(&s, id, 0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.5));
|
||||
// Setting it again where the graph already stores it leaves the document and its history as they are.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
save_design(&mut s, "Square");
|
||||
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
|
||||
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
|
||||
assert!(matches!(copy.kind, NodeKind::Group { .. }));
|
||||
s.execute("object.setProps", &json!({"id": copy.id.0, "opacity": 50})).unwrap();
|
||||
assert!(spec(&s, id).series_paints.iter().all(|p| p.opacity.is_none()));
|
||||
}
|
||||
|
||||
/// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of
|
||||
/// the series again; Normal forgets it.
|
||||
#[test]
|
||||
fn a_row_blend_mode_on_a_series_mark_survives_regeneration() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (fill, stroke) = (top_row(&s, marks[0], true), top_row(&s, marks[0], false));
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "item": fill, "blend": "screen"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [marks[1].0], "item": stroke, "blend": "darken"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_blend, kept.stroke_blend), (Some(BlendMode::Screen), Some(BlendMode::Darken)));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let normal = BlendMode::Normal;
|
||||
assert!(transparency_of(&s, id, 0).iter().all(|t| *t == (1.0, normal, BlendMode::Screen, BlendMode::Darken)), "{:?}", transparency_of(&s, id, 0));
|
||||
assert!(transparency_of(&s, id, 1).iter().all(|t| *t == (1.0, normal, normal, normal)), "{:?}", transparency_of(&s, id, 1));
|
||||
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [bar.0], "item": top_row(&s, bar, true), "blend": "normal"})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_blend, None);
|
||||
}
|
||||
|
||||
/// The graph stores an object's or a row's opacity and blend mode as one pair from the mark just edited: setting only
|
||||
/// one half on another mark replaces both, either way round, and the redraw and undo follow the stored pair.
|
||||
#[test]
|
||||
fn setting_half_of_a_series_marks_transparency_stores_that_marks_whole_pair() {
|
||||
let normal = BlendMode::Normal;
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "blend": "multiply"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 50})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (Some(0.5), None));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert!(transparency_of(&s, id, 0).iter().all(|t| (t.0, t.1) == (0.5, normal)), "{:?}", transparency_of(&s, id, 0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, Some(BlendMode::Multiply)));
|
||||
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [marks[1].0], "blend": "screen"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, Some(BlendMode::Screen)));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
assert!(transparency_of(&s, id, 0).iter().all(|t| (t.0, t.1) == (1.0, BlendMode::Screen)), "{:?}", transparency_of(&s, id, 0));
|
||||
|
||||
// A fill row: a blend alone on one mark replaces the opacity another mark's row left, and the other way round.
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": fill, "blend": "darken"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (None, Some(BlendMode::Darken)));
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 60})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.6), None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (None, Some(BlendMode::Darken)));
|
||||
}
|
||||
|
||||
/// Clear Appearance on a series mark sets its object opacity back to 100% and Normal, and the graph keeps neither.
|
||||
#[test]
|
||||
fn clearing_a_series_marks_appearance_forgets_its_kept_object_opacity() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.clear", &json!({"ids": [marks[1].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.4));
|
||||
}
|
||||
|
||||
/// An appearance moved or copied onto a mark of another series takes the source's object opacity and blend mode, and
|
||||
/// the graph keeps them for the target's series; a move leaves the source's series opaque and Normal.
|
||||
#[test]
|
||||
fn moving_an_appearance_onto_a_series_mark_keeps_its_object_opacity() {
|
||||
for copy in [false, true] {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let to = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": to.0, "copy": copy})).unwrap();
|
||||
let paints = spec(&s, id).series_paints;
|
||||
assert_eq!((paints[1].opacity, paints[1].blend), (Some(0.4), Some(BlendMode::Multiply)), "copy {copy}");
|
||||
let source = if copy { (Some(0.4), Some(BlendMode::Multiply)) } else { (None, None) };
|
||||
assert_eq!((paints[0].opacity, paints[0].blend), source, "copy {copy}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An Eyedropper pick of the object's transparency onto a series mark makes the graph keep the picked opacity and blend
|
||||
/// mode for that series, even an opaque Normal pick onto a mark that already shows it.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_of_object_transparency_onto_a_series_mark_is_kept() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let to = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("transparency.set", &json!({"ids": [marks[0].0], "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": marks[0].0, "ids": [to.0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[1].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
// An opaque Normal source picked onto another opaque mark of series 0 replaces what series 0 stores.
|
||||
let opaque = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[1].id;
|
||||
s.execute("appearance.copyFrom", &json!({"source": opaque.0, "ids": [marks[1].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, None));
|
||||
}
|
||||
|
||||
/// A graphic style made from an object at 50% Multiply, applied to a series mark, makes the graph keep the style's object
|
||||
/// opacity and blend mode; redefining the style updates them for a mark still linked to it.
|
||||
#[test]
|
||||
fn a_graphic_styles_object_opacity_on_a_series_mark_is_kept() {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let (rect, _) = blue_style(&mut s, "Blue", true);
|
||||
s.execute("object.setProps", &json!({"id": rect.0, "opacity": 50, "blend": "multiply"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Faded"})).unwrap();
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Faded", "ids": [marks[0].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (Some(0.5), Some(BlendMode::Multiply)));
|
||||
s.execute("object.setProps", &json!({"id": rect.0, "opacity": 100, "blend": "normal"})).unwrap();
|
||||
s.execute("graphicStyle.redefine", &json!({"name": "Faded", "id": rect.0})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.opacity, kept.blend), (None, None));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.5), "one undo takes back the redefinition and what the graph stored");
|
||||
|
||||
// An opaque Normal style applied to an opaque mark replaces the opacity another mark of the series left.
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 40})).unwrap();
|
||||
blue_style(&mut s, "Blue", true);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [marks[1].0]})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].opacity, None);
|
||||
}
|
||||
|
||||
/// The colors of series `index`'s marks: each mark's top fill and stroke paint and its stroke weight.
|
||||
fn marks_of(s: &Session, id: NodeId, index: u32) -> Vec<(Paint, Paint, f64)> {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
@@ -1010,19 +1202,46 @@ fn a_stroke_set_on_a_filled_line_band_does_not_repaint_it() {
|
||||
assert_eq!(redrawn_band(&mut s, id), (was, Paint::solid(vectorcraft_color::Color::BLACK), 0.25));
|
||||
}
|
||||
|
||||
/// An opacity set on a Filled Lines band's stroke row is kept, without a stroke paint, and goes on the band's thin black
|
||||
/// outline when the graph is drawn again.
|
||||
/// An opacity and blend mode set on a Filled Lines band's stroke row are kept and drawn on its outline, which keeps its
|
||||
/// black paint and 0.25 pt weight.
|
||||
#[test]
|
||||
fn a_stroke_opacity_set_on_a_filled_line_band_goes_on_its_outline() {
|
||||
fn a_filled_line_bands_outline_keeps_a_stroke_opacity_and_blend_mode() {
|
||||
let (mut s, id, band) = band_graph();
|
||||
let row = top_row(&s, band, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 30})).unwrap();
|
||||
let kept = spec(&s, id).series_paints.first().cloned().unwrap_or_default();
|
||||
assert_eq!((kept.stroke.is_none(), kept.stroke_opacity), (true, Some(0.3)));
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 50, "blend": "multiply"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.stroke, kept.stroke_opacity, kept.stroke_blend), (None, Some(0.5), Some(BlendMode::Multiply)));
|
||||
let (_, outline, width) = redrawn_band(&mut s, id);
|
||||
assert_eq!((outline, width), (Paint::solid(vectorcraft_color::Color::BLACK), 0.25));
|
||||
let band = series_parts(&s, id, 0)[0].clone();
|
||||
assert_eq!(band.appearance.stroke().unwrap().opacity, 0.3);
|
||||
let st = band.appearance.stroke().unwrap();
|
||||
assert_eq!((st.opacity, st.blend), (0.5, BlendMode::Multiply));
|
||||
}
|
||||
|
||||
/// A graphic style without a stroke applied to a marker whose stroke had paint replaces the stroke opacity and blend mode
|
||||
/// the series' Filled Lines band left: the band's outline is drawn opaque and Normal again. A marker that had no stroke
|
||||
/// before the style leaves them as they are.
|
||||
#[test]
|
||||
fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() {
|
||||
for stroked in [true, false] {
|
||||
let (mut s, id, band) = band_graph();
|
||||
let marker = series_parts(&s, id, 0)[1].id;
|
||||
if stroked {
|
||||
let row = top_row(&s, marker, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
let row = top_row(&s, band, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints[0].stroke_opacity, Some(0.4));
|
||||
blue_style(&mut s, "Blue", false);
|
||||
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [marker.0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}");
|
||||
redrawn_band(&mut s, id);
|
||||
let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone();
|
||||
assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the
|
||||
@@ -1307,13 +1526,15 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
|
||||
s.execute("appearance.setItem", &json!({"ids": [line.id.0], "index": row, "color": "#0000ff"})).unwrap();
|
||||
assert!(spec(&s, id).series_paints[0].fill.is_none(), "a stroke edit on a line keeps no fill");
|
||||
|
||||
// A blend mode on another mark of the series leaves the stored paint as that mark's own paint differs from it.
|
||||
// A blend mode on another mark of the series leaves the stored paint as that mark's own paint differs from it, and
|
||||
// stores only the blend mode.
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "color": "#ff0000"})).unwrap();
|
||||
let kept = spec(&s, id);
|
||||
let mut kept = spec(&s, id).series_paints;
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": fill, "blend": "multiply"})).unwrap();
|
||||
assert_eq!(spec(&s, id), kept);
|
||||
kept[0].fill_blend = Some(vectorcraft_color::BlendMode::Multiply);
|
||||
assert_eq!(spec(&s, id).series_paints, kept);
|
||||
}
|
||||
|
||||
/// A graphic style `name` made from a new rectangle with a blue fill at 50% opacity, and without a stroke row unless
|
||||
|
||||
@@ -330,7 +330,7 @@ fn raised_area(face: &PathData, i: usize, areas: &[Option<PathData>]) -> PathDat
|
||||
.filter(|a| a.bounds().is_some_and(|b| b.overlaps(near)))
|
||||
.map(|a| (a, FillRule::NonZero)),
|
||||
);
|
||||
let only = po::boolean_n(&paths, |inside| inside.first() == Some(&true) && inside.get(1) == Some(&true) && !inside.iter().skip(2).any(|b| *b));
|
||||
let only = po::boolean_n(&paths, |inside| inside == [0, 1]);
|
||||
if only.is_empty() {
|
||||
return face.clone();
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<
|
||||
/// Run a command's implementation without the enablement check or journaling.
|
||||
pub(crate) fn run_raw(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
let c = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
(c.run)(s, p)
|
||||
super::run_spec(s, c, p)
|
||||
}
|
||||
|
||||
/// Merge the undo entries pushed since the history had `from` entries into one labelled step.
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
//! `stroke.set` whatever is selected), a graphic style clicked with nothing selected (more fills
|
||||
//! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance
|
||||
//! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only.
|
||||
//! `paint.default` resets it.
|
||||
//! option on (the default) an inherited appearance gives new art its top stroke's options only,
|
||||
//! and a change of selection loads only the proxies. `paint.default` resets it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Art Has Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{on?: bool (omitted: toggle)} the Appearance panel option (the preference newArtBasic, on by default): on, new art takes one fill and stroke (with the Stroke panel's options); off, the whole appearance of the last selected object (every fill, stroke and effect, opacity and blend mode) → {on}",
|
||||
"{on?: bool (omitted: toggle)} the Appearance panel option (the preference newArtBasic, on by default): on, new art takes one fill and stroke (with the Stroke panel's options), the fill, stroke and weight the selection shares when it last changed; off, the whole appearance of the last selected object (every fill, stroke and effect, opacity and blend mode) → {on}",
|
||||
always,
|
||||
set_basic
|
||||
),
|
||||
@@ -213,6 +213,34 @@ impl Session {
|
||||
let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend);
|
||||
self.take_new_art(ap, opacity, blend, style, true);
|
||||
}
|
||||
|
||||
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
|
||||
/// stroke proxies and the weight take what the selection shows in them, so new art looks like
|
||||
/// it. A paint the selected objects don't share (a "?" proxy) stays as it was, and art without
|
||||
/// paint (a placed image, whose None would make new art invisible) changes nothing. The
|
||||
/// template is left alone, and without a stroke to show the weight stays too.
|
||||
pub(crate) fn load_selection_paints(&mut self) {
|
||||
if !self.prefs.new_art_basic {
|
||||
return;
|
||||
}
|
||||
let has_paint = self.proxy_source(false).is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty());
|
||||
if !has_paint {
|
||||
return;
|
||||
}
|
||||
let (fill_mixed, stroke_mixed) = self.proxy_mixed();
|
||||
let (fill, stroke) = self.proxy_paints();
|
||||
let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight);
|
||||
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
|
||||
if !fill_mixed {
|
||||
self.paint.fill = unplaced(&fill);
|
||||
}
|
||||
if !stroke_mixed {
|
||||
self.paint.stroke = unplaced(&stroke);
|
||||
}
|
||||
if let Some(width) = weight {
|
||||
self.paint.stroke_width = width;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
|
||||
@@ -65,7 +65,11 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) {
|
||||
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, so a value a mark
|
||||
// already has still replaces the one another mark left on the graph.
|
||||
let transparency = opacity.is_some() || blend.is_some();
|
||||
let stores = || transparency && crate::cmd::graph::series_object_opacity_differs(d, &ids);
|
||||
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() {
|
||||
// Hidden or locked objects can't stay selected.
|
||||
if hides {
|
||||
s.select(|d, sel| sel.deselect_uneditable(d))?;
|
||||
@@ -118,6 +122,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
}
|
||||
}
|
||||
if transparency {
|
||||
crate::cmd::graph::capture_series_object_opacity(d, &ids);
|
||||
}
|
||||
// Hidden or locked objects can't stay selected.
|
||||
if hides {
|
||||
sel.deselect_uneditable(d);
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. 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?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. 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,
|
||||
default_paint
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself)",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, 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)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -855,7 +855,7 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.appearance.set_stroke(f);
|
||||
}
|
||||
// The swap writes the paint of the topmost fill and stroke, not their opacity.
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true);
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
}
|
||||
@@ -884,7 +884,7 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => n.appearance = Appearance::default_art().into(),
|
||||
}
|
||||
}
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false);
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horiz
Line truncated
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing com
Line truncated
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
@@ -111,9 +111,8 @@ fn boards_and_art(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<usize>, bool
|
||||
}
|
||||
|
||||
/// [`boards_and_art`], with both values added to the running command's journal entry, so a replay
|
||||
/// acts on the same artboards and art whatever the Artboard tool's state is then. `edit.cut` and
|
||||
/// `edit.copy` call [`artboard_copy`] without this and take no such params.
|
||||
fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Result<(Vec<usize>, bool)> {
|
||||
/// acts on the same artboards and art whatever the Artboard tool's state is then.
|
||||
pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Result<(Vec<usize>, bool)> {
|
||||
let (indices, art) = boards_and_art(s, p, cmd)?;
|
||||
note_artboards(s, p, &indices);
|
||||
s.note_journal("art", json!(art));
|
||||
@@ -510,6 +509,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"allCaps",
|
||||
"smallCaps",
|
||||
"position",
|
||||
"antiAlias",
|
||||
"leftIndent",
|
||||
"rightIndent",
|
||||
"firstLineIndent",
|
||||
@@ -534,6 +534,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"singleWordJustification",
|
||||
"mojikumi",
|
||||
"kinsoku",
|
||||
"kinsokuType",
|
||||
"direction",
|
||||
"leadingModel",
|
||||
"charAlign",
|
||||
@@ -557,6 +558,15 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !keys.iter().any(|k| p.get(*k).is_some()) {
|
||||
return Err(bad(C, "nothing to change"));
|
||||
}
|
||||
// The anti-aliasing method belongs to the whole type object; each frame keeps its own method.
|
||||
let anti_alias = match p.get("antiAlias") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(
|
||||
v.as_str()
|
||||
.and_then(vectorcraft_doc::text::TypeAntiAlias::from_id)
|
||||
.ok_or_else(|| bad(C, "`antiAlias` must be \"none\", \"sharp\", \"crisp\" or \"strong\""))?,
|
||||
),
|
||||
};
|
||||
let composer = match p.get("composer") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(match v.as_str() {
|
||||
@@ -591,6 +601,15 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, "`kinsoku` must be \"none\", \"hard\" or \"soft\"")),
|
||||
}),
|
||||
};
|
||||
let kinsoku_type = match p.get("kinsokuType") {
|
||||
None => None,
|
||||
Some(v) => Some(match v.as_str() {
|
||||
Some("pushInFirst") => vectorcraft_doc::KinsokuShoriType::PushInFirst,
|
||||
Some("pushOutFirst") => vectorcraft_doc::KinsokuShoriType::PushOutFirst,
|
||||
Some("pushOutOnly") => vectorcraft_doc::KinsokuShoriType::PushOutOnly,
|
||||
_ => return Err(bad(C, "`kinsokuType` must be \"pushInFirst\", \"pushOutFirst\" or \"pushOutOnly\"")),
|
||||
}),
|
||||
};
|
||||
let direction = match p.get("direction") {
|
||||
None => None,
|
||||
Some(v) => Some(match v.as_str() {
|
||||
@@ -842,6 +861,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = kinsoku {
|
||||
para.kinsoku = v;
|
||||
}
|
||||
if let Some(v) = kinsoku_type {
|
||||
para.kinsoku_type = v;
|
||||
}
|
||||
if let Some(v) = direction {
|
||||
para.direction = v;
|
||||
}
|
||||
@@ -872,6 +894,13 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scale = num("hScale").map(|v| v.clamp(1.0, 10000.0));
|
||||
super::graph::capture_label_styles(d, &ids, &|st| chars(st, shift, scale, (tcy_up_down, tcy_left_right)));
|
||||
}
|
||||
if let Some(v) = anti_alias {
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
t.anti_alias = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let mut result = json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
//! by `|`; a `?` marks an optional one, and a `:`, `=` or `(` starts what the entry says about it. An entry that starts
|
||||
//! with `…` stands for keys listed elsewhere: those of each command it names after `as` or `of`
|
||||
//! (`…settings as file.new`), or, naming none, any key (the options of the format an export picks). Objects inside a value aren't
|
||||
//! described key by key, so only the top level is checked.
|
||||
//! described key by key, so only the top level is checked, except in an export's options: those
|
||||
//! are checked against the options of the formats the command can write, in `marks`, `bleed` and
|
||||
//! the other objects too ([`check_export_options`]).
|
||||
//!
|
||||
//! [`Session::execute`] answers a key the description doesn't name with a parameter error
|
||||
//! ([`check_params`]), for every caller (the app, the control channel, MCP, the CLI) and for the
|
||||
@@ -500,9 +502,100 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"webExport.settings",
|
||||
];
|
||||
|
||||
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included, and
|
||||
/// [`check_effect_params`] for the effect `effect.apply` adds. A command the engine doesn't have
|
||||
/// passes: running it reports that.
|
||||
/// The object options of a PDF export, key by key: the Save PDF settings as a preset stores them,
|
||||
/// with the passwords it leaves out.
|
||||
fn pdf_option_tree() -> Value {
|
||||
let mut tree = serde_json::to_value(vectorcraft_pdf::PdfSettings::default()).unwrap_or_default();
|
||||
if let Some(security) = tree.get_mut("security").and_then(Value::as_object_mut) {
|
||||
security.extend(["openPassword", "permissionsPassword"].map(|k| (k.to_string(), Value::Null)));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
|
||||
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
match (schema.get(key), value) {
|
||||
(None, _) => {
|
||||
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
|
||||
let why = match nearest(key, &keys) {
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The options of an export command `id`. `document.export`, `document.exportSelection` and
|
||||
/// `document.serialize` take a key that some format reads (one object can carry several formats'
|
||||
/// options; `document.formats` lists them). `document.exportPdf`, `document.pdfSettings` and
|
||||
/// `pdf.preset.save` take a key that PDF reads, `document.exportEps` one that EPS reads and
|
||||
/// `document.exportDxf` one that DXF reads. Where a command takes `marks`, `bleed`, `flattener` or
|
||||
/// another object option of PDF or EPS, only the object's own keys pass. An SVG export's `svg`
|
||||
/// object is checked when it is read. Saved presets are not checked: one with a key that is no
|
||||
/// longer read keeps loading.
|
||||
fn check_export_options(id: &str, params: &Value) -> Result<()> {
|
||||
use super::fileio::{FORMATS, dxf, eps, pdf};
|
||||
let Value::Object(given) = params else { return Ok(()) };
|
||||
let mut keys: Vec<&str> = vec!["path", "format", "acknowledgeLoss"];
|
||||
let why_not = match id {
|
||||
"document.export" | "document.exportSelection" | "document.serialize" => {
|
||||
// `richBlack` is Appearance of Black's setting for a raster export, and `params` an
|
||||
// exporter plug-in's own.
|
||||
keys.extend(["includeArtboardFill", "selectedOnly", "richBlack", "params"]);
|
||||
keys.extend(FORMATS.iter().filter(|f| f.write).flat_map(|f| f.options).map(|o| o.name));
|
||||
"no format takes it"
|
||||
}
|
||||
"document.exportPdf" | "document.pdfSettings" | "pdf.preset.save" => {
|
||||
keys.push("includeArtboardFill");
|
||||
keys.extend(pdf::OPTIONS.iter().map(|o| o.name));
|
||||
match id {
|
||||
"document.pdfSettings" => keys.push("includeDocument"),
|
||||
"pdf.preset.save" => keys.extend(["name", "newName", "description"]),
|
||||
_ => {}
|
||||
}
|
||||
"PDF doesn't take it"
|
||||
}
|
||||
"document.exportEps" => {
|
||||
keys.push("includeArtboardFill");
|
||||
keys.extend(eps::OPTIONS.iter().map(|o| o.name));
|
||||
"EPS doesn't take it"
|
||||
}
|
||||
"document.exportDxf" => {
|
||||
keys.extend(dxf::OPTIONS.iter().map(|o| o.name));
|
||||
"DXF doesn't take it"
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let mut trees = pdf_option_tree();
|
||||
if let Some(tree) = trees.as_object_mut() {
|
||||
tree.insert("flattener".into(), serde_json::to_value(super::flatten::FlattenOptions::default()).unwrap_or_default());
|
||||
}
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
return Err(bad(
|
||||
id,
|
||||
match nearest(key, &keys) {
|
||||
Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"),
|
||||
None => format!("unknown parameter `{key}`; {why_not} (see document.formats)"),
|
||||
},
|
||||
));
|
||||
}
|
||||
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
|
||||
check_option_tree(id, &format!("{key}."), value, schema)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_keys`] for an engine command, the steps of a `command.batch` or an `action.batch` included,
|
||||
/// [`check_effect_params`] for the effect `effect.apply` adds and [`check_export_options`] for an
|
||||
/// export. A command the engine doesn't have passes: running it reports that.
|
||||
pub fn check_params(id: &str, params: &Value) -> Result<()> {
|
||||
check_params_in(id, params, false)
|
||||
}
|
||||
@@ -516,6 +609,7 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
{
|
||||
check_effect_params(id, effect, given)?;
|
||||
}
|
||||
check_export_options(id, params)?;
|
||||
if UNCHECKED.contains(&id) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::expand::{fill_shape, reshaped, seeded};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
|
||||
number_or, str_param, switch_or,
|
||||
@@ -307,7 +308,7 @@ pub(crate) fn pf_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) {
|
||||
match &n.kind {
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
let hook = |c: &Node| vectorcraft_render::effects::outline_object(Some(d), c);
|
||||
match vectorcraft_render::effects::compound_shape_art(n, Some(&hook)) {
|
||||
match vectorcraft_render::effects::compound_shape_art(Some(d), n, Some(&hook)) {
|
||||
Some(art) => out.push(art),
|
||||
None => children.iter().for_each(|c| pf_leaves(d, c, out)),
|
||||
}
|
||||
@@ -891,24 +892,60 @@ pub(crate) fn outlined_stroke(
|
||||
|
||||
/// Path `l` with every stroke outlined, in appearance order: runs of fills stay on copies of
|
||||
/// the path, each stroke becomes its outline (or brush art), grouped when there are several.
|
||||
/// As on the canvas, the path's geometry effects ([`reshaped`]) shape the path first, and each
|
||||
/// stroke's own geometry effects then shape the path that stroke outlines; [`outlined_stroke`]
|
||||
/// gets the stroke without them. A fill with a random Transform effect paints the outline its
|
||||
/// geometry effects make of the path, on a copy of its own. A path whose Transform effect copies
|
||||
/// it with a gradient, or has Scale Strokes & Effects or Transform Patterns on, becomes the art the
|
||||
/// canvas draws for it, each copy with its own gradient, stroke width and pattern, and its strokes
|
||||
/// outlined before the art gets new ids. Random in a Transform effect takes its seed
|
||||
/// from the object's id, so these effects give the outline the values the canvas drew. When the
|
||||
/// geometry effects leave nothing to paint, an empty group takes the path's place.
|
||||
/// `None` when `l` has no stroke to outline.
|
||||
pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Brush], l: &Node) -> Option<Node> {
|
||||
use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry, has_transform_art, is_geometry, reshape};
|
||||
if !l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st))) {
|
||||
return None;
|
||||
}
|
||||
if has_transform_art(l) {
|
||||
let mut art = reshape(Some(&*d), l, None)?;
|
||||
outline_member_strokes(d, brushes, &mut art);
|
||||
return Some(d.reid(&art));
|
||||
}
|
||||
let reshaped = reshaped(d, l);
|
||||
let l = reshaped.as_ref().unwrap_or(l);
|
||||
let (path, rule) = node_path(l)?;
|
||||
let ctx = GeomContext::of(l);
|
||||
// A fill belongs to the source path, whether open or closed. Converting its stroke
|
||||
// preserves that fill on a separate copy (including compound member geometry).
|
||||
let mut parts: Vec<Node> = vec![];
|
||||
let mut fills: Vec<AppearanceItem> = vec![];
|
||||
for item in &l.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => fills.push(item.clone()),
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => {
|
||||
let shaped = f.effects.iter().any(seeded).then(|| path.bounds().and_then(|b| fill_shape(d, l, item, &path, b))).flatten();
|
||||
let Some((shape, _, _, moved)) = shaped else {
|
||||
fills.push(item.clone());
|
||||
continue;
|
||||
};
|
||||
if !fills.is_empty() {
|
||||
parts.push(styled_copy(d, l, std::mem::take(&mut fills)));
|
||||
}
|
||||
let mut plain = moved;
|
||||
plain.effects_mut().retain(|e| !is_geometry(&e.id));
|
||||
parts.push(styled_copy(d, &shape, vec![plain]));
|
||||
}
|
||||
AppearanceItem::Stroke(st) if outlinable(st) => {
|
||||
if !fills.is_empty() {
|
||||
parts.push(styled_copy(d, l, std::mem::take(&mut fills)));
|
||||
}
|
||||
parts.extend(outlined_stroke(d, brushes, &path, rule, st));
|
||||
let mut plain = st.clone();
|
||||
plain.effects.retain(|e| !is_geometry(&e.id));
|
||||
let stroked = match path.bounds() {
|
||||
Some(b) if has_geometry(&st.effects) => apply_geometry_with(&st.effects, &path, b, &ctx.item(item)),
|
||||
_ => path.clone(),
|
||||
};
|
||||
parts.extend(outlined_stroke(d, brushes, &stroked, rule, &plain));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -916,9 +953,27 @@ pub(crate) fn outline_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Br
|
||||
if !fills.is_empty() {
|
||||
parts.push(styled_copy(d, l, fills));
|
||||
}
|
||||
let reshapes = reshaped.is_some()
|
||||
|| l.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if outlinable(st) && has_geometry(&st.effects)));
|
||||
if parts.is_empty() && reshapes {
|
||||
// The geometry effects leave nothing to paint, as on the canvas: an empty group takes the path's place.
|
||||
parts.push(Node::group(d.alloc_id(), vec![]));
|
||||
}
|
||||
assemble(d, l, parts)
|
||||
}
|
||||
|
||||
/// Outline the strokes of every member of group `n`, however deep ([`outline_strokes`]).
|
||||
fn outline_member_strokes(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &mut Node) {
|
||||
let Some(children) = n.children_mut() else { return };
|
||||
for c in children.iter_mut() {
|
||||
if let Some(o) = outline_strokes(d, brushes, c) {
|
||||
*c = Arc::new(o);
|
||||
} else if c.children().is_some() {
|
||||
outline_member_strokes(d, brushes, Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain copy of path `l` (new ids, no transparency, name or mask) painted with `items`.
|
||||
/// The copy is shown and unlocked.
|
||||
pub(crate) fn styled_copy(d: &mut Document, l: &Node, items: Vec<AppearanceItem>) -> Node {
|
||||
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save PDF Preset",
|
||||
[],
|
||||
None,
|
||||
"{name?: (default: a new \"PDF Preset N\"), newName?: rename it, description?, preset?: the preset to start from (default: the saved preset `name`, else VectorCraft Default), …options of document.exportPdf} create or change a saved preset (built-in presets are read-only; passwords are never stored) → {name, created, settings}",
|
||||
"{name?: (default: a new \"PDF Preset N\"), newName?: rename it, description?, preset?: the preset to start from (default: the saved preset `name`, else VectorCraft Default), …options of document.exportPdf} create or change a saved preset (built-in presets are read-only; passwords are never stored) → {name, created, settings}. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused",
|
||||
always,
|
||||
save
|
||||
),
|
||||
|
||||
+231
-26
@@ -7,7 +7,8 @@
|
||||
//! plug-in that fails leaves the document untouched), and read and write the data they keep with
|
||||
//! the document ([`vectorcraft_doc::plugin_data`], theirs alone); live-effect plug-ins are applied
|
||||
//! like any effect (`effect.apply {effect: "plugin.<id>"}`) and drawn by `vectorcraft-effects`;
|
||||
//! exporters add a file format that `document.export` writes (`fileio::plugin_formats`).
|
||||
//! exporters add a file format that `document.export` writes, and importers one that
|
||||
//! `document.open` reads (`fileio::plugin_formats`).
|
||||
//!
|
||||
//! A filter may ask for a heavy budget (`Budget::Heavy`: minutes rather than a minute, for routing,
|
||||
//! packing or simulation). It installs only once the user agrees (`plugin.install {allowHeavy}`),
|
||||
@@ -20,6 +21,13 @@
|
||||
//! `doc.write` an output that changes the document is refused, and without `state` it neither
|
||||
//! reads nor writes the data it keeps with the document.
|
||||
//!
|
||||
//! A filter or a live effect may add menu commands of its own (its manifest's `commands`). Each
|
||||
//! is the command `plugin.<plug-in id>.<command id>` while the plug-in is installed
|
||||
//! ([`command_specs`], which [`super::find_command`] and the command listings read): under
|
||||
//! Object › Plug-ins › the plug-in's name (Effect › Plug-ins for a live effect's), journaled so
|
||||
//! actions record it, and run as a filter run of the plug-in ([`run_command`]) with the command's
|
||||
//! id in `_context`, its own checked parameters and the plug-in's permissions, as one undo step.
|
||||
//!
|
||||
//! A plug-in of API level 2 that lists `progress` may import the host's `vc_progress`,
|
||||
//! `vc_cancelled` and `vc_log` ([`vectorcraft_plugins::host`]): run inside a
|
||||
//! [`vectorcraft_doc::cancel::scope`] (the app's heavy filters and background exports), its
|
||||
@@ -29,11 +37,11 @@
|
||||
//! `plugin.clearCache` empties the cache, `plugin.list` and `plugin.info` give its size
|
||||
//! (`cacheBytes`), replacing the plug-in keeps both and `plugin.remove` deletes them.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Effect, Node};
|
||||
use vectorcraft_plugins::{Budget, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
|
||||
@@ -58,7 +66,7 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
});
|
||||
match m.kind {
|
||||
Kind::Effect => v["effect"] = json!(effect::effect_id(&m.id)),
|
||||
Kind::Exporter => {
|
||||
Kind::Exporter | Kind::Importer => {
|
||||
v["format"] = json!(export::format_id(&m.id));
|
||||
v["extensions"] = json!(m.extensions);
|
||||
}
|
||||
@@ -67,6 +75,21 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if m.budget == Budget::Heavy {
|
||||
v["budget"] = json!("heavy");
|
||||
}
|
||||
if m.paint_output {
|
||||
v["paintOutput"] = json!(true);
|
||||
}
|
||||
if !m.commands.is_empty() {
|
||||
let commands: Vec<Value> = m
|
||||
.commands
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let run = m.for_command(c);
|
||||
json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(),
|
||||
"paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())})
|
||||
})
|
||||
.collect();
|
||||
v["commands"] = json!(commands);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -97,6 +120,8 @@ fn plugin_by_id(cmd: &str, p: &Value) -> Result<Arc<Plugin>> {
|
||||
/// like any other command.
|
||||
pub struct FilterRun {
|
||||
plugin: Arc<Plugin>,
|
||||
/// The plug-in command it runs (`plugin.<id>.<command>`), if it isn't `plugin.run`'s run.
|
||||
command: Option<Command>,
|
||||
input: Vec<u8>,
|
||||
params: Vec<u8>,
|
||||
/// The objects the plug-in is given, and the container new objects go in.
|
||||
@@ -137,14 +162,30 @@ impl FilterRun {
|
||||
format!("`{}` is an exporter: export with document.export {{\"format\": \"{}\"}}", m.id, export::format_id(&m.id)),
|
||||
));
|
||||
}
|
||||
Kind::Importer => {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("`{}` is an importer: open a file with document.open {{\"importer\": \"{}\"}}", m.id, export::format_id(&m.id)),
|
||||
));
|
||||
}
|
||||
}
|
||||
// Bad parameters fail before anything runs.
|
||||
let mut params = Value::Object(m.resolve_params(&plugin_params(p)).map_err(|e| bad(C, e.to_string()))?);
|
||||
Self::prepare_with(s, plugin, None, C, p)
|
||||
}
|
||||
|
||||
/// The run of `plugin`, or of its `command`, that command `c`'s params `p` ask for, on the
|
||||
/// active document. Bad parameters fail before anything runs.
|
||||
fn prepare_with(s: &Session, plugin: Arc<Plugin>, command: Option<Command>, c: &str, p: &Value) -> Result<FilterRun> {
|
||||
let m = plugin.manifest();
|
||||
let resolved = match &command {
|
||||
Some(cmd) => m.for_command(cmd).resolve_params(&plugin_params(p)),
|
||||
None => m.resolve_params(&plugin_params(p)),
|
||||
};
|
||||
let mut params = Value::Object(resolved.map_err(|e| bad(c, e.to_string()))?);
|
||||
let may = m.permissions();
|
||||
let st = s.doc()?;
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused,
|
||||
// as `selected_roots` refuses it.
|
||||
let selected = match ids_param(p, "ids", C)? {
|
||||
let selected = match ids_param(p, "ids", c)? {
|
||||
Some(ids) => ids,
|
||||
None => {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
@@ -160,10 +201,15 @@ impl FilterRun {
|
||||
// What the plug-in keeps with the document, as it last wrote it.
|
||||
let data = st.doc.plugin_data(&m.id).filter(|_| may.contains(&Permission::State)).cloned().unwrap_or(Value::Null);
|
||||
params["_context"] = json!({"mode": "filter", "bounds": bounds.map(rect), "artboard": board.map(|a| rect(a.rect)), "documentData": data});
|
||||
// A command run says which command it is.
|
||||
if let Some(cmd) = &command {
|
||||
params["_context"]["mode"] = json!("command");
|
||||
params["_context"]["command"] = json!(cmd.id);
|
||||
}
|
||||
let input = objects::encode_input(&st.doc, &inputs);
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| bad(C, e.to_string()))?;
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| bad(c, e.to_string()))?;
|
||||
let document = (st.uid, st.revision);
|
||||
Ok(FilterRun { plugin, input, params, inputs, parent, document })
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, parent, document })
|
||||
}
|
||||
|
||||
/// The plug-in, for its name and budget.
|
||||
@@ -214,7 +260,9 @@ impl FilterRun {
|
||||
}
|
||||
let may_write = may.contains(&Permission::DocWrite);
|
||||
let (inputs, parent) = (self.inputs, self.parent);
|
||||
let ids = s.edit(m.name.trim_end_matches('…'), |d, sel| {
|
||||
// A command's undo step is named after the command.
|
||||
let label = self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label);
|
||||
let ids = s.edit(&label, |d, sel| {
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
@@ -226,7 +274,11 @@ impl FilterRun {
|
||||
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
|
||||
Ok(ids)
|
||||
})?;
|
||||
Ok(json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
let mut out = json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
|
||||
if let Some(cmd) = &self.command {
|
||||
out["command"] = json!(cmd.id);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,6 +308,146 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.finish(s, &output)
|
||||
}
|
||||
|
||||
/// The command id of plug-in `plugin`'s command `command`: `plugin.<plugin>.<command>`.
|
||||
pub fn command_id(plugin: &str, command: &str) -> String {
|
||||
format!("{}{plugin}.{command}", vectorcraft_plugins::PREFIX)
|
||||
}
|
||||
|
||||
/// Is `id` shaped as a plug-in command's id (`plugin.<plug-in id>.<command id>`)? This module's
|
||||
/// own `plugin.*` commands have no dot after the prefix, and a command id has none.
|
||||
pub fn is_command_id(id: &str) -> bool {
|
||||
id.strip_prefix(vectorcraft_plugins::PREFIX).is_some_and(|rest| rest.contains('.'))
|
||||
}
|
||||
|
||||
/// The installed plug-in and its command that command id `id` names.
|
||||
pub fn command_of(id: &str) -> Option<(Arc<Plugin>, Command)> {
|
||||
let (plugin, command) = id.strip_prefix(vectorcraft_plugins::PREFIX)?.rsplit_once('.')?;
|
||||
let p = registry::get(plugin)?;
|
||||
let c = p.manifest().command(command)?.clone();
|
||||
Some((p, c))
|
||||
}
|
||||
|
||||
/// The plug-in commands of the installed plug-ins, the registry revision they were listed at, and
|
||||
/// a count that changes whenever the list does ([`commands_generation`]).
|
||||
struct Listed {
|
||||
revision: Option<u64>,
|
||||
generation: u64,
|
||||
specs: Vec<&'static CommandSpec>,
|
||||
}
|
||||
|
||||
static LISTED: RwLock<Listed> = RwLock::new(Listed { revision: None, generation: 0, specs: Vec::new() });
|
||||
|
||||
/// Every command spec made for a plug-in command, made once: specs hold static strings, so memory
|
||||
/// stays bounded by the plug-in commands ever installed.
|
||||
static MADE: Mutex<Vec<&'static CommandSpec>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The commands the installed plug-ins add, in plug-in id order and then in each manifest's order.
|
||||
pub fn command_specs() -> Vec<&'static CommandSpec> {
|
||||
let revision = registry::revision();
|
||||
if let Ok(l) = LISTED.read()
|
||||
&& l.revision == Some(revision)
|
||||
{
|
||||
return l.specs.clone();
|
||||
}
|
||||
let specs: Vec<&'static CommandSpec> =
|
||||
registry::list().iter().flat_map(|p| p.manifest().commands.iter().map(|c| spec_of(p, c)).collect::<Vec<_>>()).collect();
|
||||
// When a plug-in was installed or removed during the listing, the list may not match
|
||||
// `revision`. It is returned without being cached, and the next call lists again.
|
||||
if registry::revision() != revision {
|
||||
return specs;
|
||||
}
|
||||
let mut l = LISTED.write().unwrap_or_else(|e| e.into_inner());
|
||||
if l.specs.len() != specs.len() || l.specs.iter().zip(&specs).any(|(a, b)| !std::ptr::eq(*a, *b)) {
|
||||
l.generation += 1;
|
||||
}
|
||||
l.revision = Some(revision);
|
||||
l.specs.clone_from(&specs);
|
||||
specs
|
||||
}
|
||||
|
||||
/// Changes whenever the plug-in commands [`command_specs`] lists change, for caches built from
|
||||
/// them (the keyboard shortcuts' catalogue).
|
||||
pub fn commands_generation() -> u64 {
|
||||
command_specs();
|
||||
LISTED.read().map(|l| l.generation).unwrap_or_else(|e| e.into_inner().generation)
|
||||
}
|
||||
|
||||
/// The spec of installed plug-in command `id`.
|
||||
pub fn find_spec(id: &str) -> Option<&'static CommandSpec> {
|
||||
if !is_command_id(id) {
|
||||
return None;
|
||||
}
|
||||
command_specs().into_iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
/// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and
|
||||
/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live
|
||||
/// effect: never a menu the manifest names) and its params description.
|
||||
fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
|
||||
let m = p.manifest();
|
||||
let id = command_id(&m.id, &c.id);
|
||||
let label = c.shown_label();
|
||||
let top = if m.kind == Kind::Effect { "Effect" } else { "Object" };
|
||||
let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME);
|
||||
let mut fields =
|
||||
String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)");
|
||||
let doc = m.for_command(c).params_doc();
|
||||
if let Some(own) = doc.strip_prefix('{').and_then(|d| d.strip_suffix('}')).filter(|d| !d.is_empty()) {
|
||||
fields.push_str(", ");
|
||||
fields.push_str(own);
|
||||
}
|
||||
let params = format!(
|
||||
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids}}",
|
||||
m.id, c.id
|
||||
);
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params;
|
||||
if let Some(s) = made.iter().find(same) {
|
||||
return s;
|
||||
}
|
||||
let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice());
|
||||
let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec {
|
||||
id: registry::intern(&id),
|
||||
label: registry::intern(&label),
|
||||
menu,
|
||||
shortcut: None,
|
||||
params: registry::intern(¶ms),
|
||||
enabled: has_doc,
|
||||
run: unrouted,
|
||||
journal: true,
|
||||
}));
|
||||
made.push(spec);
|
||||
spec
|
||||
}
|
||||
|
||||
/// A plug-in command's `run`: plug-in commands run through [`super::run_spec`], which passes
|
||||
/// [`run_command`] the command id.
|
||||
fn unrouted(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(EngineError::Internal { cmd: "plugin".into(), msg: "a plug-in command runs through Session::execute".into() })
|
||||
}
|
||||
|
||||
/// Runs plug-in command `id` (`plugin.<plug-in id>.<command id>`): a filter run of the plug-in on
|
||||
/// `ids` (else the selection) with the command's own parameters, checked before it runs, and
|
||||
/// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named
|
||||
/// after the command → `{plugin, command, ids}`. A run that fails (a trap, an exhausted budget, an
|
||||
/// output it may not make) leaves the document as it was, and the error names the plug-in and the
|
||||
/// command.
|
||||
pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
// An output handed in is for `plugin.run` alone.
|
||||
s.plugin_output = None;
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
let failed = {
|
||||
let (name, label) = (permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME), command.shown_label());
|
||||
move |e: EngineError| match e {
|
||||
EngineError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(format!("“{name}” › {label}: {e}")),
|
||||
}
|
||||
};
|
||||
let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?;
|
||||
let output = r.run().map_err(&failed)?;
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
|
||||
/// Admits the effect records a filter returned for object `n` (written, its effects still its own)
|
||||
/// as `effect.apply` would apply them: each new record a known effect (one of ours, or an installed
|
||||
/// live-effect plug-in) with parameters it takes, filled in to their defaults. A record the object
|
||||
@@ -264,8 +456,13 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Texturizer) comes as the effect stores it, never as a file to read: a plug-in can't have the
|
||||
/// host read one.
|
||||
fn admit_effects(fx: &[Effect], n: &Node) -> std::result::Result<Vec<Effect>, String> {
|
||||
admit_effects_for("plugin.run", fx, n)
|
||||
}
|
||||
|
||||
/// [`admit_effects`] for command `cmd`, which bad parameters name: `plugin.run`, or `document.open`
|
||||
/// for the objects an importer plug-in returns.
|
||||
pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::result::Result<Vec<Effect>, String> {
|
||||
use vectorcraft_render::effects;
|
||||
const C: &str = "plugin.run";
|
||||
let mut out = Vec::with_capacity(fx.len());
|
||||
for (j, e) in fx.iter().enumerate() {
|
||||
if n.appearance.effects.contains(e) {
|
||||
@@ -278,7 +475,7 @@ fn admit_effects(fx: &[Effect], n: &Node) -> std::result::Result<Vec<Effect>, St
|
||||
Some(plugin) => {
|
||||
plugin.manifest().resolve_params(¶ms).map_err(|why| refuse(why.to_string()))?;
|
||||
}
|
||||
None => super::params::check_effect_params(C, &e.id, ¶ms).map_err(|why| refuse(why.to_string()))?,
|
||||
None => super::params::check_effect_params(cmd, &e.id, ¶ms).map_err(|why| refuse(why.to_string()))?,
|
||||
}
|
||||
if super::effectcmd::texture_load_effect(&e.id)
|
||||
&& let Some(t) = params.get(effects::pixel::TEXTURE_IMAGE)
|
||||
@@ -353,8 +550,8 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless
|
||||
/// `allowHeavy` says the user agreed, one that lists permissions the user hasn't granted its id
|
||||
/// unless `grant` lists them all, one that would take another module's place ([`takes_over`])
|
||||
/// `allowHeavy` says the user agreed, one that lists permissions the user hasn't granted this very
|
||||
/// module unless `grant` lists them all, one that would take another module's place ([`takes_over`])
|
||||
/// unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records the grant with
|
||||
/// the module's hash, keeps it for the next start and installs it → its `plugin.list` entry.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -399,8 +596,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
));
|
||||
}
|
||||
// A plug-in that lists permissions installs once the user grants them: whoever installs it
|
||||
// asks them first, unless they already granted all of them (with a plug-in store, to this
|
||||
// module).
|
||||
// asks them first, unless they already granted this very module all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
@@ -408,13 +604,22 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(C, format!("“{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees")));
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
// held back. A failed write of that module is only logged, and the grant then doesn't cover
|
||||
// the new module. A stored module that can't be read back isn't replaced by one that needs a
|
||||
// grant.
|
||||
let previous = s.stored_plugin_bytes(plugin.id());
|
||||
let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes);
|
||||
if m.asks_permissions() {
|
||||
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
|
||||
registry::grant(g.clone());
|
||||
s.store_grant(&m.id, Some(g));
|
||||
if stored && !s.store_grant(&m.id, Some(g)) {
|
||||
s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref());
|
||||
stored = false;
|
||||
}
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541), with their settings and cache.
|
||||
let stored = s.store_plugin(plugin.id(), &bytes);
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
@@ -669,7 +874,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's format id, plugin.<id>, for document.export, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), cacheBytes (the bytes its cache holds; see plugin.clearCache)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -678,7 +883,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Plug-in Info",
|
||||
[],
|
||||
None,
|
||||
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null)}",
|
||||
"{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
@@ -687,7 +892,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [..] (default: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -696,7 +901,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash, and replacing the plug-in with one that lists no new permission needs none; with a plug-in store attached, only the grants kept there count, each for the module with its hash alone), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; with a plug-in store attached, only the grants kept there count), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -705,7 +910,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted its id: plugin.install then needs grant) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted this very module, its bytes included: plugin.install then needs grant) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
@@ -732,7 +937,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Plug-ins",
|
||||
["Object", "Plug-ins"],
|
||||
None,
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted its id; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100} (% with custom and tiling), overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one grey page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colours keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colours are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print",
|
||||
[],
|
||||
Some("Cmd+P"),
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's; the saved settings stay), settings?: {…settings of print.setup} (over the document's or the preset's), includeArtboardFill?: true (each artboard's background color prints behind its art; false leaves it out), path?, format?: pdf (default: a print-ready PDF) | postscript (the default for a .ps path: a PostScript file with DSC comments, %%Pages, a page per sheet with its paper size, marks, separations with their ink and halftone screen, the fixed flatness, negatives), level?: 3|2 (the PostScript language level), flattenerPreset?: \"medium\" (PostScript: the preset transparency is flattened with — high, low or a saved one, see flattener.presets.list), acknowledgeLoss?: bool (with path: write over the file the document was read from although reading it left things out), forPrinter?: bool (the PDF goes to a print queue: a page whose paper is turned to landscape is written upright, the art turned a quarter anticlockwise, as a printer driver turns a landscape job; macOS prints a landscape page as it is, cut off on upright paper; paper wide in Portrait and transverse pages stay as they are)} print the document, one page per sheet of paper (per tile, per ink, per copy; with copiesPerSheet, a sheet holds as many copies of an artboard as fit) → {pages, format, path, bytes, warnings}; no path → {dataBase64, bytes, pages, format, warnings}. Raster effects print at the document's raster effects resolution; a PDF leaves halftone screens and flatness to the output device",
|
||||
has_doc,
|
||||
print
|
||||
),
|
||||
@@ -228,6 +228,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
view: sh.view,
|
||||
window: sh.window,
|
||||
place: sh.place,
|
||||
copies: &sh.copies,
|
||||
area: sh.area,
|
||||
marks: sh.marks.as_ref(),
|
||||
negative: sh.negative,
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::colorcmds::{Recolor, Scope};
|
||||
use super::colorcmds::{NotChanged, Recolor, Scope, left_out};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, check_switches, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param,
|
||||
};
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Recolor Artwork",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}",
|
||||
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -118,6 +118,38 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
used.into_iter().map(|(_, u)| u).collect()
|
||||
}
|
||||
|
||||
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
|
||||
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
|
||||
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
|
||||
let mut colors = vec![];
|
||||
node_colors(n, &mut |c, _| colors.push(*c));
|
||||
let mut patterns: Vec<&str> = vec![];
|
||||
pattern_names(n, &mut patterns);
|
||||
let mut next = 0;
|
||||
while let Some(&name) = patterns.get(next) {
|
||||
next += 1;
|
||||
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
|
||||
node_colors(a, &mut |c, _| colors.push(*c));
|
||||
pattern_names(a, &mut patterns);
|
||||
}
|
||||
}
|
||||
colors
|
||||
}
|
||||
|
||||
/// Adds the names of the patterns `n` and the objects inside it use as fills or strokes to `names`,
|
||||
/// leaving out names already there.
|
||||
fn pattern_names<'a>(n: &'a Node, names: &mut Vec<&'a str>) {
|
||||
n.walk(&mut |m| {
|
||||
for p in node_paints(m) {
|
||||
if let Paint::Pattern { pattern, .. } = p
|
||||
&& !names.contains(&pattern.as_str())
|
||||
{
|
||||
names.push(pattern);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The objects whose colors `recolor.colors` and `recolor.reduce` read, for [`used_colors`]: `ids`
|
||||
/// (each checked) or else the selection, with everything they hold; with nothing selected, the
|
||||
/// objects Select All takes and the objects inside them, leaving out every hidden or locked object
|
||||
@@ -526,6 +558,10 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `selected_roots` refuses it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
let ids = s.doc()?.selection.objects.clone();
|
||||
let left = {
|
||||
let st = s.doc()?;
|
||||
left_out(&st.doc, st.isolation, &super::edit::roots_of(&st.doc, ids.clone()))
|
||||
};
|
||||
let group = text_param(p, "group", C)?;
|
||||
if ids.is_empty() && group.is_none() {
|
||||
return Err(bad(C, "select artwork to recolour, or give a colour `group`"));
|
||||
@@ -563,7 +599,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let rename = text_param(p, "rename", C)?;
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let (changed, edit, added, converted) = s.edit(label, |d, _| {
|
||||
let (changed, edit, added, converted, not_changed) = s.edit(label, |d, _| {
|
||||
// The rows' library swatches join the document (one it has with that name and colour is
|
||||
// used as it is).
|
||||
let mut added = vec![];
|
||||
@@ -601,12 +637,27 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let map = ColorMap::new(&rows, method, model, &links, kept, mapped_adjust);
|
||||
let f = |c: Color| map.map(c);
|
||||
let lf = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| map.map_link(c, link, tint);
|
||||
// The objects left out whose colors the pass would change, with the colors they show now.
|
||||
// The trial pass does not count towards the note on color models.
|
||||
let before: Vec<(NodeId, Vec<Color>, bool)> = Recolor::with_links(scope, &f, &lf)
|
||||
.would_change(d, &left)
|
||||
.into_iter()
|
||||
.filter_map(|(id, hidden)| Some((id, shown_colors(d, d.node(id)?), hidden)))
|
||||
.collect();
|
||||
map.converted.set(false);
|
||||
let changed = Recolor::with_links(scope, &f, &lf).run(d, &ids);
|
||||
let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?;
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
|
||||
Ok((changed, edit, added, map.converted.get()))
|
||||
// Rewriting the group's swatches can change the colors of art linked to them, left out or
|
||||
// not, and of the patterns it uses. Art that only loses its link keeps its colors and is
|
||||
// counted.
|
||||
let not_changed = NotChanged::of(
|
||||
before.iter().filter(|(id, colors, _)| d.node(*id).is_some_and(|now| shown_colors(d, now) == *colors)).map(|(_, _, hidden)| *hidden),
|
||||
);
|
||||
Ok((changed, edit, added, map.converted.get(), not_changed))
|
||||
})?;
|
||||
let mut out = json!({ "changed": changed, "swatches": added });
|
||||
not_changed.report(&mut out);
|
||||
if let Some(e) = edit {
|
||||
e.defaults(s);
|
||||
out["relinked"] = json!(e.relinked());
|
||||
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows; exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. 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 (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked 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) → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked 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) → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -349,14 +349,14 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The graph stores the rows of the kinds the style shows, now on top of each stack.
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false);
|
||||
} else {
|
||||
d.graphic_style_id(i);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false);
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -476,7 +476,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for nid in &follow {
|
||||
apply_style(d, *nid, &g, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false);
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true);
|
||||
set_link(d, &[src], Some(id));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -1604,6 +1604,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
path_spacing: 0.0,
|
||||
wrap: Vec::new(),
|
||||
optical_margin: false,
|
||||
anti_alias: Default::default(),
|
||||
system_layout: false,
|
||||
fractional_widths: true,
|
||||
list_count: 0,
|
||||
@@ -1893,6 +1894,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
path_spacing: 0.0,
|
||||
wrap: Vec::new(),
|
||||
optical_margin: false,
|
||||
anti_alias: Default::default(),
|
||||
system_layout: t.system_layout,
|
||||
fractional_widths: t.fractional_widths,
|
||||
list_count: 0,
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
|
||||
("leading_model", json!(v.leading_model)),
|
||||
("burasagari", json!(v.burasagari)),
|
||||
("kinsoku", json!(v.kinsoku)),
|
||||
("kinsoku_type", json!(v.kinsoku_type)),
|
||||
("roman_hanging", json!(v.roman_hanging)),
|
||||
("kashida", json!(v.kashida)),
|
||||
] {
|
||||
|
||||
@@ -1134,6 +1134,65 @@ fn a_thread_takes_its_first_frames_optical_margin_alignment() {
|
||||
assert_eq!([a, b, c].map(|id| optical(&s, id).0), [true; 3]);
|
||||
}
|
||||
|
||||
/// The anti-aliasing method (`text.setFormat {antiAlias}`) belongs to each frame and is saved
|
||||
/// only when not Sharp. A range sets its frame in one undo step. Threading and opening preserve
|
||||
/// different methods on the frames of a thread.
|
||||
#[test]
|
||||
fn the_anti_aliasing_method_is_set_for_each_frame_of_a_thread() {
|
||||
use vectorcraft_doc::text::TypeAntiAlias::{self, Crisp, None as Hard, Sharp, Strong};
|
||||
let method = |s: &Session, id: u64| text_of(&s.doc().unwrap().doc, NodeId(id)).map(|t| t.anti_alias);
|
||||
let saved = |s: &Session, id: u64| serde_json::to_value(text_of(&s.doc().unwrap().doc, NodeId(id)).unwrap()).unwrap().get("antiAlias").cloned();
|
||||
let (mut s, a, b) = quoted_thread();
|
||||
assert_eq!((method(&s, a), method(&s, b)), (Some(Sharp), Some(Sharp)));
|
||||
assert_eq!(saved(&s, a), None, "Sharp is not saved");
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let err = s.execute("text.setFormat", &json!({"antiAlias": "smooth"})).unwrap_err().to_string();
|
||||
assert!(err.contains("`antiAlias` must be"), "{err}");
|
||||
s.execute("text.setFormat", &json!({"antiAlias": "crisp"})).unwrap();
|
||||
assert_eq!((method(&s, a), method(&s, b)), (Some(Sharp), Some(Crisp)), "only the selected frame takes it");
|
||||
assert_eq!(saved(&s, b), Some(json!("crisp")));
|
||||
// A range of characters sets its whole frame.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 0, "end": 1, "antiAlias": "none"})).unwrap();
|
||||
assert_eq!((method(&s, a), method(&s, b)), (Some(Hard), Some(Crisp)));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((method(&s, a), method(&s, b)), (Some(Sharp), Some(Crisp)), "one undo step");
|
||||
// A new frame does not change the methods of the existing frames.
|
||||
s.execute("text.setFormat", &json!({"ids": [b], "antiAlias": "strong"})).unwrap();
|
||||
let c = new_id(s.execute("text.thread.add", &json!({"from": b, "at": [400, 10]})).unwrap());
|
||||
assert_eq!([a, b, c].map(|id| method(&s, id)), [Some(Sharp), Some(Strong), Some(Strong)]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Threading existing frames with different methods preserves both.
|
||||
let (mut joined, first_id, second_id) = quoted_thread();
|
||||
joined.execute("text.thread.remove", &json!({})).unwrap();
|
||||
joined.execute("text.setFormat", &json!({"ids": [first_id], "antiAlias": "crisp"})).unwrap();
|
||||
joined.execute("text.setFormat", &json!({"ids": [second_id], "antiAlias": "strong"})).unwrap();
|
||||
joined.execute("select.set", &json!({"ids": [first_id, second_id]})).unwrap();
|
||||
joined.execute("text.thread.create", &json!({})).unwrap();
|
||||
assert_eq!((method(&joined, first_id), method(&joined, second_id)), (Some(Crisp), Some(Strong)));
|
||||
joined.execute("text.editRange", &json!({"id": first_id, "start": 0, "end": 0, "insert": "New "})).unwrap();
|
||||
assert_eq!((method(&joined, first_id), method(&joined, second_id)), (Some(Crisp), Some(Strong)), "reflow keeps both methods");
|
||||
joined.execute("text.thread.remove", &json!({})).unwrap();
|
||||
assert_eq!((method(&joined, first_id), method(&joined, second_id)), (Some(Crisp), Some(Strong)), "unthreading keeps both methods");
|
||||
let first: [TypeAntiAlias; 2] = [Crisp, Hard];
|
||||
for (one, name) in [(first, "old.vectorcraft"), ([Hard, Crisp], "old.vectorcraft"), (first, "old.eps"), ([Hard, Crisp], "old.eps")] {
|
||||
for (id, m) in [(a, one[0]), (b, one[1])] {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let Some(NodeKind::Text(t)) = doc.node_mut(NodeId(id)).map(|n| &mut n.kind) else { panic!("not text") };
|
||||
t.anti_alias = m;
|
||||
}
|
||||
let bytes = if name.ends_with(".eps") {
|
||||
let r = s.execute("document.exportEps", &json!({})).unwrap();
|
||||
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
|
||||
} else {
|
||||
vectorcraft_format::save(&s.doc().unwrap().doc, false)
|
||||
};
|
||||
let r = s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert_eq!(r["restored"], name.ends_with(".eps"), "{r}");
|
||||
assert_eq!(threads(&s), [[a, b]], "{name}");
|
||||
assert_eq!((method(&s, a), method(&s, b)), (Some(one[0]), Some(one[1])), "{name}, frame methods");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file saved with the frames of one thread set differently opens with the first frame's
|
||||
/// setting in every frame: a native file, and an EPS file restored from the document it carries.
|
||||
#[test]
|
||||
|
||||
@@ -98,6 +98,43 @@ fn kinsoku_set_is_set_per_paragraph_and_saved_only_when_not_hard() {
|
||||
assert_eq!(old.kinsoku, Kinsoku::Hard);
|
||||
}
|
||||
|
||||
/// Paragraph panel menu › Kinsoku Shori Type: `text.setFormat {kinsokuType}` sets it per
|
||||
/// paragraph in one undo step, refuses unknown values, saves it only when it is not Push Out Only
|
||||
/// (new type's and older documents' type), reopens with the file, and paragraph styles carry it.
|
||||
#[test]
|
||||
fn kinsoku_shori_type_is_set_per_paragraph_and_saved_only_when_not_push_out_only() {
|
||||
use vectorcraft_doc::KinsokuShoriType;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "あ」\nい", "area": {"width": 100, "height": 100}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
assert_eq!(text(&s).para_at(0).kinsoku_type, KinsokuShoriType::PushOutOnly);
|
||||
assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kinsoku_type").is_none());
|
||||
s.execute("text.setFormat", &json!({"id": id, "start": 0, "end": 1, "kinsokuType": "pushInFirst"})).unwrap();
|
||||
assert_eq!((text(&s).para_at(0).kinsoku_type, text(&s).para_at(1).kinsoku_type), (KinsokuShoriType::PushInFirst, KinsokuShoriType::PushOutOnly));
|
||||
assert_eq!(serde_json::to_value(text(&s).para_at(0)).unwrap()["kinsoku_type"], "pushInFirst");
|
||||
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert_eq!((back.para_at(0).kinsoku_type, back.para_at(1).kinsoku_type), (KinsokuShoriType::PushInFirst, KinsokuShoriType::PushOutOnly));
|
||||
assert!(s.execute("text.setFormat", &json!({"id": id, "kinsokuType": "pushIn"})).is_err());
|
||||
assert_eq!(text(&s).para_at(0).kinsoku_type, KinsokuShoriType::PushInFirst, "an unknown value changes nothing");
|
||||
s.execute("text.setFormat", &json!({"id": id, "kinsokuType": "pushOutFirst"})).unwrap();
|
||||
assert_eq!(text(&s).para_at(1).kinsoku_type, KinsokuShoriType::PushOutFirst);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((text(&s).para_at(0).kinsoku_type, text(&s).para_at(1).kinsoku_type), (KinsokuShoriType::PushInFirst, KinsokuShoriType::PushOutOnly));
|
||||
// A paragraph style carries it.
|
||||
s.execute("paraStyle.new", &json!({"name": "Pushed in", "attrs": {"kinsoku_type": "pushOutFirst"}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Pushed in", "id": id})).unwrap();
|
||||
assert_eq!(text(&s).para_at(1).kinsoku_type, KinsokuShoriType::PushOutFirst);
|
||||
let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap();
|
||||
assert_eq!(old.kinsoku_type, KinsokuShoriType::PushOutOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burasagari_is_set_per_paragraph_and_saved_only_when_on() {
|
||||
use vectorcraft_doc::Burasagari;
|
||||
|
||||
@@ -138,9 +138,10 @@ fn names_param(p: &Value, cmd: &str, fallback: Option<String>, nothing: &str) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse what a variable of `kind` can't be bound to: art that is locked, on a hidden or locked
|
||||
/// layer, or on a locked artboard; a text variable only drives type; an image variable only drives
|
||||
/// an image object; a variable of unknown kind drives nothing.
|
||||
/// Refuse what a variable of `kind` can't be bound to: art on a hidden layer or in a hidden group,
|
||||
/// art on a locked artboard, and, unless `kind` is visibility, art that is locked or on a locked
|
||||
/// layer or in a locked group; a text variable only drives type; an image variable only drives an
|
||||
/// image object; a variable of unknown kind drives nothing.
|
||||
fn check_bindable(doc: &vectorcraft_doc::Document, ids: &[NodeId], kind: VariableKind, cmd: &str) -> Result<()> {
|
||||
if kind == VariableKind::Unknown {
|
||||
return Err(bad(cmd, "a variable of unknown kind can't be bound to objects"));
|
||||
@@ -149,7 +150,7 @@ fn check_bindable(doc: &vectorcraft_doc::Document, ids: &[NodeId], kind: Variabl
|
||||
for id in ids {
|
||||
match doc.node(*id) {
|
||||
None => return Err(EngineError::NoNode(*id)),
|
||||
Some(_) if !doc.variable_target_with(&locks, *id) => return Err(bad(cmd, not_a_target(doc, *id))),
|
||||
Some(_) if !doc.variable_target_with(&locks, *id, kind) => return Err(bad(cmd, not_a_target(doc, *id, kind))),
|
||||
Some(n) if kind == VariableKind::Text && !matches!(n.kind, NodeKind::Text(_)) => {
|
||||
return Err(bad(cmd, format!("node {} is not type", id.0)));
|
||||
}
|
||||
@@ -165,14 +166,16 @@ fn check_bindable(doc: &vectorcraft_doc::Document, ids: &[NodeId], kind: Variabl
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why `variable_target` refuses `id`: the object is locked, a group or layer that holds it is
|
||||
/// locked, one that holds it is hidden, or it is on a locked artboard, checked in that order.
|
||||
fn not_a_target(doc: &vectorcraft_doc::Document, id: NodeId) -> String {
|
||||
/// Why `variable_target` refuses `id` for a variable of `kind`: the object is locked, a group or
|
||||
/// layer that holds it is locked, one that holds it is hidden, or it is on a locked artboard,
|
||||
/// checked in that order. For a visibility variable, the object and group lock checks are skipped.
|
||||
fn not_a_target(doc: &vectorcraft_doc::Document, id: NodeId, kind: VariableKind) -> String {
|
||||
let holders: Vec<&vectorcraft_doc::Node> =
|
||||
doc.ancestry(id).unwrap_or_default().into_iter().filter(|i| *i != id).filter_map(|i| doc.node(i)).collect();
|
||||
if doc.node(id).is_some_and(|n| n.locked) {
|
||||
let locks = kind != VariableKind::Visibility;
|
||||
if locks && doc.node(id).is_some_and(|n| n.locked) {
|
||||
format!("node {} is locked", id.0)
|
||||
} else if holders.iter().any(|n| n.locked) {
|
||||
} else if locks && holders.iter().any(|n| n.locked) {
|
||||
format!("node {} is in a locked group or layer", id.0)
|
||||
} else if holders.iter().any(|n| !n.visible) {
|
||||
format!("node {} is in a hidden group or layer", id.0)
|
||||
@@ -511,8 +514,9 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Update Data Set: write what the bound objects hold now into the row that is active, for each
|
||||
/// variable the row holds. A variable whose objects report no value (locked, inside a locked
|
||||
/// layer or group, on a locked artboard, or gone) keeps the row's value. With `all`, every other variable the
|
||||
/// variable the row holds. A variable whose objects report no value (gone, or, for a variable
|
||||
/// other than a visibility variable, locked or inside a locked layer or group, or, for any
|
||||
/// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the
|
||||
/// objects report a value for is added to the row. Without an active row there is nothing to
|
||||
/// update, so say so rather than picking one. With every bound object locked, no value is
|
||||
/// written; an update that writes no value adds no undo step.
|
||||
@@ -588,14 +592,16 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result<Value> {
|
||||
}
|
||||
// Which bound objects the row may rewrite, measured once before any of them changes, so
|
||||
// text that grows onto a locked artboard part way through is still rewritten. Each id is
|
||||
// keyed by whether a text value is meant for it, which checks every frame of its story.
|
||||
let targets: BTreeSet<(NodeId, bool)> = {
|
||||
// keyed by whether a text value is meant for it, which checks every frame of its story,
|
||||
// and by whether a visibility value is, which ignores locks.
|
||||
let targets: BTreeSet<(NodeId, bool, bool)> = {
|
||||
let locks = d.locked_artboards();
|
||||
let mut out = BTreeSet::new();
|
||||
for (id, var) in &pairs {
|
||||
let text = d.variables.variable(var).is_some_and(|v| v.kind == VariableKind::Text);
|
||||
if if text { d.story_target_with(&locks, *id) } else { d.dataset_target_with(&locks, *id) } {
|
||||
out.insert((*id, text));
|
||||
let kind = d.variables.variable(var).map_or(VariableKind::Unknown, |v| v.kind);
|
||||
let text = kind == VariableKind::Text;
|
||||
if if text { d.story_target_with(&locks, *id) } else { d.dataset_target_with(&locks, *id, kind) } {
|
||||
out.insert((*id, text, kind == VariableKind::Visibility));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -617,12 +623,13 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Locked art, art in a locked layer or group or on a locked artboard, and text whose
|
||||
// object is gone, can't be rewritten: skipped and counted, like the rest. Hidden art
|
||||
// is rewritten, in a hidden layer or group too, and stays hidden unless a visibility
|
||||
// value shows it. A text value rewrites the whole story of threaded text, so it skips
|
||||
// when any frame of it is locked or on a locked artboard.
|
||||
if !targets.contains(&(id, kind == VariableKind::Text)) {
|
||||
// Art that is gone, art on a locked artboard, and art that is locked or in a locked
|
||||
// layer or group, is skipped and counted, like the rest, except that a visibility value
|
||||
// shows and hides locked art off a locked artboard. Hidden art is rewritten, in a hidden layer or group too,
|
||||
// and stays hidden unless a visibility value shows it. A text value rewrites the whole
|
||||
// story of threaded text, so it skips when any frame of it is locked or on a locked
|
||||
// artboard.
|
||||
if !targets.contains(&(id, kind == VariableKind::Text, kind == VariableKind::Visibility)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -759,7 +766,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Bind Variable",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{variable, ids?} bind objects (default: the selection) to a variable; text needs type, image needs an image object, graph needs a graph root, locked art is refused. A type object holds one text variable: binding it to another text variable is refused, and the error names the one it has. Variables of other kinds can share an object, and binding an object to a variable it already has changes nothing → {bound, already}",
|
||||
"{variable, ids?} bind objects (default: the selection) to a variable; text needs type, image needs an image object, graph needs a graph root, art on a locked artboard is refused, and so are locked art and art in a locked layer or group except by a visibility variable. A type object holds one text variable: binding it to another text variable is refused, and the error names the one it has. Variables of other kinds can share an object, and binding an object to a variable it already has changes nothing → {bound, already}",
|
||||
has_doc,
|
||||
bind
|
||||
),
|
||||
@@ -815,7 +822,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Data Set",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (locked, inside a locked layer or group, on a locked artboard, or gone) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}",
|
||||
"{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}",
|
||||
has_doc,
|
||||
dataset_update
|
||||
),
|
||||
|
||||
@@ -25,9 +25,10 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo
|
||||
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
|
||||
/// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the
|
||||
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the
|
||||
/// Artboard tool had selected for its commands; the view's center the app passes to Edit Symbol);
|
||||
/// an action leaves them out ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 22] = [
|
||||
/// Artboard tool had selected for its commands; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 26] = [
|
||||
("file.new", "created"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
@@ -46,6 +47,10 @@ const REPLAY_ONLY: [(&str, &str); 22] = [
|
||||
("artboard.cut", "selectedArtboards"),
|
||||
("artboard.rename", "selectedArtboards"),
|
||||
("artboard.switchOrientation", "selectedArtboards"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
("edit.cut", "selectedArtboards"),
|
||||
("edit.cut", "art"),
|
||||
("select.allOnArtboard", "artboard"),
|
||||
("symbol.edit", "artboard"),
|
||||
("symbol.edit", "viewCenter"),
|
||||
|
||||
@@ -19,12 +19,20 @@ pub struct HistoryEntry {
|
||||
next: usize,
|
||||
/// The template and name `label` was made from ([`Session::edit_named`]).
|
||||
pub(crate) named: Option<NamedStep>,
|
||||
/// A number no other step takes ([`History::step`]).
|
||||
serial: u64,
|
||||
/// Original and converted new-art colors, only for steps that change document color mode.
|
||||
pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>,
|
||||
/// Owned new-art snapshots included in both directional estimates.
|
||||
color_mode_bytes: usize,
|
||||
}
|
||||
|
||||
/// The next [`HistoryEntry::serial`]: 1 for the first step made, so 0 never names a step.
|
||||
fn next_serial() -> u64 {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// A step name made by filling the `{name}` placeholder of a template with a name
|
||||
/// ([`Session::edit_named`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -57,6 +65,7 @@ impl HistoryEntry {
|
||||
next_bytes,
|
||||
next: std::ptr::from_ref(next) as usize,
|
||||
named: None,
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
}
|
||||
@@ -88,6 +97,7 @@ impl HistoryEntry {
|
||||
next_bytes: costs.bytes,
|
||||
next: Arc::as_ptr(now) as usize,
|
||||
named: None,
|
||||
serial: next_serial(),
|
||||
color_mode_paints: None,
|
||||
color_mode_bytes: 0,
|
||||
}
|
||||
@@ -155,6 +165,13 @@ impl History {
|
||||
self.undo.iter().chain(&self.redo).map(|e| e.bytes).sum()
|
||||
}
|
||||
|
||||
/// Which step the document is at: the newest undo step and the next redo step, by numbers no
|
||||
/// other step takes (0 for none). Every new step, Undo, Redo and edit merged into the newest
|
||||
/// step (an undo group) changes it; a selection change does not.
|
||||
pub fn step(&self) -> (u64, u64) {
|
||||
(self.undo.last().map_or(0, |e| e.serial), self.redo.last().map_or(0, |e| e.serial))
|
||||
}
|
||||
|
||||
/// The document at row `row` of the History panel, `now` being the document now: the rows before
|
||||
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
|
||||
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
|
||||
@@ -192,13 +209,14 @@ impl History {
|
||||
}
|
||||
|
||||
/// Estimate the newest undo step again, its next state now being `now` (the steps after it were
|
||||
/// merged into it, or an undo group extended it).
|
||||
/// merged into it, or an undo group extended it). It takes a new number ([`History::step`]).
|
||||
pub(crate) fn recost_last(&mut self, now: &Document) {
|
||||
if let Some(e) = self.undo.last_mut() {
|
||||
let (before, after) = e.doc.retained_bytes_each(now);
|
||||
e.bytes = before.saturating_add(e.color_mode_bytes);
|
||||
e.next_bytes = after.saturating_add(e.color_mode_bytes);
|
||||
e.next = std::ptr::from_ref(now) as usize;
|
||||
e.serial = next_serial();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,10 @@ pub struct Session {
|
||||
/// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes
|
||||
/// back as it was at the release ([`Session::pointer`]).
|
||||
pub(crate) lender: Option<Box<dyn Tool>>,
|
||||
/// The active document (its uid) and its [`History::step`] when the tool last handled a pointer
|
||||
/// event or drew its overlays: when they differ at the next one, the tool is told first
|
||||
/// ([`vectorcraft_tools::Tool::history_moved`]). None until the first.
|
||||
pub(crate) tool_step: Option<(u64, (u64, u64))>,
|
||||
/// The selection of the active document (its uid) as Cmd lent `tool`: what the lent tool's
|
||||
/// gesture found, so that one that leaves it as it was picks nothing.
|
||||
pub(crate) selection_at_lend: Option<(u64, vectorcraft_doc::Selection)>,
|
||||
@@ -175,6 +179,9 @@ pub struct Session {
|
||||
/// The composite fonts (lowercase names) that the open documents defined when the font
|
||||
/// database was last brought in step with them ([`cmd::compositefonts::sync`]).
|
||||
pub(crate) composite_names: Vec<String>,
|
||||
/// Every composite font (lowercase name) this session has registered in the font database:
|
||||
/// type read for opening may have been laid out in one that is gone by the time it opens.
|
||||
pub(crate) composite_names_registered: std::collections::HashSet<String>,
|
||||
/// While a command that changes nothing in the document runs (a query, or one of
|
||||
/// [`command_sets::JOURNALED_READS`]): it reads the instance of an object selected in a symbol
|
||||
/// instance's art.
|
||||
@@ -246,9 +253,10 @@ pub struct Session {
|
||||
/// Where folder searches may go; `None`: this computer's rules ([`cmd::findfiles::Rules`]).
|
||||
/// Tests set it.
|
||||
pub search_rules: Option<cmd::findfiles::Rules>,
|
||||
/// Canvas feedback cached for the pending deferred preview ([`Session::overlays`]); cleared
|
||||
/// when the preview params change or the interaction ends.
|
||||
pub(crate) deferred_overlay_cache: Option<(String, Value, Vec<vectorcraft_tools::Overlay>)>,
|
||||
/// Canvas feedback cached for the pending deferred preview ([`Session::overlays`],
|
||||
/// [`Session::deferred_transform_box`]); cleared when the preview params change or the
|
||||
/// interaction ends.
|
||||
pub(crate) deferred_overlay_cache: Option<tooling::DeferredFeedback>,
|
||||
/// The walker threads a folder search starts; `None`: [`cmd::findfiles::threads`]. Tests set
|
||||
/// it.
|
||||
pub search_threads: Option<usize>,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use vectorcraft_doc::{Node, TextObject};
|
||||
|
||||
use super::{
|
||||
Arc, Clipboard, Color, CommandInfo, DocState, Document, DrawMode, EngineError, GradientPaint, Journal, NodeKind, PaintDefaults, Prefs, Result,
|
||||
Session, ViewInfo, cmd, command_specs, file_access,
|
||||
@@ -42,6 +46,7 @@ impl Session {
|
||||
journal: Journal::default(),
|
||||
tool: vectorcraft_tools::create("selection"),
|
||||
lender: None,
|
||||
tool_step: None,
|
||||
selection_at_lend: None,
|
||||
lent_selection: None,
|
||||
last_selection_tool: None,
|
||||
@@ -84,6 +89,7 @@ impl Session {
|
||||
batch_steps: None,
|
||||
batch_paint_docs: Vec::new(),
|
||||
composite_names: Vec::new(),
|
||||
composite_names_registered: HashSet::new(),
|
||||
reading: false,
|
||||
place_hand_off: None,
|
||||
queue_hand_off: None,
|
||||
@@ -182,10 +188,8 @@ impl Session {
|
||||
self.reset_tool_for_doc_switch();
|
||||
}
|
||||
self.active = Some(index);
|
||||
// Type is drawn in the composite fonts of the document now in front, and measured again
|
||||
// when they differ from those of the document before.
|
||||
if switched && cmd::compositefonts::sync(self) {
|
||||
self.refresh_document_text_bounds(index);
|
||||
if switched {
|
||||
self.sync_front_composite_fonts();
|
||||
}
|
||||
true
|
||||
} else {
|
||||
@@ -193,6 +197,16 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]),
|
||||
/// after a switch or a close brought it there. Its type set in a composite font that differs
|
||||
/// from the one of that name before (added, changed or removed) is measured again, and type not
|
||||
/// measured yet (in a document replaced while in the back) is measured now.
|
||||
fn sync_front_composite_fonts(&mut self) {
|
||||
let changed: HashSet<String> = cmd::compositefonts::sync(self).into_iter().collect();
|
||||
let Some(index) = self.active else { return };
|
||||
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() || sets_in_any(t, &changed));
|
||||
}
|
||||
|
||||
/// The name [`Session::next_untitled`] gives next (New Document's Name field).
|
||||
pub fn peek_untitled(&self) -> String {
|
||||
format!("Untitled-{}", self.untitled_counter + 1)
|
||||
@@ -211,19 +225,44 @@ impl Session {
|
||||
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
|
||||
// Inline graphics in text take their size from their symbols' art (not saved either).
|
||||
doc.resolve_inline_art();
|
||||
let trees = doc.layers.iter_mut().chain(doc.symbols.iter_mut().map(|s| &mut s.art));
|
||||
let trees = trees.chain(doc.graph_designs.iter_mut().map(|g| &mut g.art));
|
||||
for tree in trees.chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) {
|
||||
refresh_tree_text_bounds(tree);
|
||||
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
|
||||
for tree in text_trees_mut(doc) {
|
||||
each_text_where(tree, &mut uncached, &mut cmd::typecmd::refresh_bounds_for_first_frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Session::refresh_text_bounds`] for open document `index`, as a change that is not an
|
||||
/// edit: a saved document stays saved, and its undo history keeps its documents as they are.
|
||||
fn refresh_document_text_bounds(&mut self, index: usize) {
|
||||
if let Some(st) = self.docs.get_mut(index) {
|
||||
st.change_unsaved(|doc| Self::refresh_text_bounds(Arc::make_mut(doc)));
|
||||
/// Measure the type in open document `index` that `stale` picks (in its trees as
|
||||
/// [`Session::refresh_text_bounds`] walks them), as a change that is not an edit: a saved
|
||||
/// document stays saved, and its undo history keeps its documents as they are. The document is
|
||||
/// left as it is when `stale` picks nothing.
|
||||
fn refresh_document_text_bounds(&mut self, index: usize, mut stale: impl FnMut(&TextObject) -> bool) {
|
||||
let Some(st) = self.docs.get_mut(index) else { return };
|
||||
if !text_trees(&st.doc).any(|n| has_text_where(n, &mut stale)) {
|
||||
return;
|
||||
}
|
||||
st.change_unsaved(|doc| {
|
||||
let doc = Arc::make_mut(doc);
|
||||
for tree in text_trees_mut(doc) {
|
||||
each_text_where(tree, &mut stale, &mut cmd::typecmd::refresh_bounds_for_first_frame);
|
||||
}
|
||||
// Inline graphics take their size from their symbols' art, whose type may just have
|
||||
// been measured again: the text holding one whose size changed is measured again too.
|
||||
if !doc.resolve_inline_art().is_empty() {
|
||||
for tree in text_trees_mut(doc) {
|
||||
each_text_where(tree, &mut |t| t.cached_bounds.is_none(), &mut cmd::typecmd::refresh_bounds_for_first_frame);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Register the composite fonts of open document `index`, which is in front, and measure its
|
||||
/// type not measured yet and its type set in a font of a name that a composite font of an open
|
||||
/// document or of the font database has, or had before: that type may have been laid out in
|
||||
/// another document's composite fonts (those registered while its file was read for opening).
|
||||
fn sync_opened_composite_fonts(&mut self, index: usize) {
|
||||
let mut names = cmd::compositefonts::names_in_use(self);
|
||||
names.extend(cmd::compositefonts::sync(self));
|
||||
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() || sets_in_any(t, &names));
|
||||
}
|
||||
|
||||
/// Add a document and make it active. Between `edit.undoGroup.begin` and `edit.undoGroup.end`,
|
||||
@@ -234,6 +273,8 @@ impl Session {
|
||||
// (importers and the native reader have seen to theirs already, with a warning).
|
||||
doc.limit_depth();
|
||||
cmd::compositefonts::filter_loaded(&mut doc);
|
||||
// Inline graphics in text take their size from their symbols' art (not saved).
|
||||
doc.resolve_inline_art();
|
||||
// Guides from files saved before guides had layers go on a layer.
|
||||
doc.adopt_guides();
|
||||
cmd::dimension::conform(&mut doc);
|
||||
@@ -244,8 +285,7 @@ impl Session {
|
||||
self.docs.push(st);
|
||||
let i = self.docs.len() - 1;
|
||||
self.active = Some(i);
|
||||
cmd::compositefonts::sync(self);
|
||||
self.refresh_document_text_bounds(i);
|
||||
self.sync_opened_composite_fonts(i);
|
||||
if self.depth == 0
|
||||
&& let Some(label) = self.explicit_undo_group.clone()
|
||||
{
|
||||
@@ -262,11 +302,26 @@ impl Session {
|
||||
}
|
||||
doc.limit_depth();
|
||||
cmd::compositefonts::filter_loaded(&mut doc);
|
||||
doc.resolve_inline_art();
|
||||
doc.adopt_guides();
|
||||
cmd::dimension::conform(&mut doc);
|
||||
// In the back, type set in a font named like a composite font is measured when the document
|
||||
// comes to the front and its own composite fonts are registered, not in the front
|
||||
// document's.
|
||||
let mut back_names = None;
|
||||
if self.active == Some(index) {
|
||||
// Pending tool work (typing, a drag) belongs to the content being thrown away.
|
||||
self.reset_tool_for_doc_switch();
|
||||
} else {
|
||||
let mut names = cmd::compositefonts::names_in_use(self);
|
||||
names.extend(doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
|
||||
for tree in text_trees_mut(&mut doc) {
|
||||
each_text_where(tree, &mut |t| t.cached_bounds.is_some() && sets_in_any(t, &names), &mut |t| {
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
});
|
||||
}
|
||||
back_names = Some(names);
|
||||
}
|
||||
let old = &self.docs[index];
|
||||
let mut st = DocState::new(doc, old.path.clone());
|
||||
@@ -297,12 +352,10 @@ impl Session {
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
}
|
||||
// Type in the composite fonts of a document in the back is measured again when it comes to
|
||||
// the front.
|
||||
if self.active == Some(index) {
|
||||
cmd::compositefonts::sync(self);
|
||||
match back_names {
|
||||
Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)),
|
||||
None => self.sync_opened_composite_fonts(index),
|
||||
}
|
||||
self.refresh_document_text_bounds(index);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -319,7 +372,7 @@ impl Session {
|
||||
stash.push(old);
|
||||
}
|
||||
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
|
||||
cmd::compositefonts::sync(self);
|
||||
self.sync_front_composite_fonts();
|
||||
true
|
||||
}
|
||||
|
||||
@@ -344,33 +397,56 @@ impl Session {
|
||||
true
|
||||
}
|
||||
|
||||
/// Commands with enablement (for menus, palette, MCP `list_commands`).
|
||||
/// Commands with enablement (for menus, palette, MCP `list_commands`), the installed plug-ins'
|
||||
/// commands last.
|
||||
pub fn commands(&self) -> Vec<CommandInfo> {
|
||||
command_specs().iter().map(|c| c.info(self)).collect()
|
||||
command_specs().iter().chain(crate::cmd::plugin::command_specs()).map(|c| c.info(self)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay out the type in tree `n` (opacity mask art included) whose bounds aren't cached. Only the
|
||||
/// nodes on the way to such type are copied.
|
||||
fn refresh_tree_text_bounds(n: &mut Arc<vectorcraft_doc::Node>) {
|
||||
fn stale(n: &vectorcraft_doc::Node) -> bool {
|
||||
matches!(&n.kind, NodeKind::Text(t) if t.cached_bounds.is_none())
|
||||
|| n.extras().mask.as_deref().is_some_and(|m| stale(&m.art))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| stale(c)))
|
||||
}
|
||||
if !stale(n) {
|
||||
/// Whether some of type `t` is set in a font named (in any case) one of `names`, lowercased.
|
||||
fn sets_in_any(t: &TextObject, names: &HashSet<String>) -> bool {
|
||||
!names.is_empty() && t.runs.iter().any(|r| names.contains(&r.style.font_family.to_lowercase()))
|
||||
}
|
||||
|
||||
/// The trees of `doc` that hold type: its layers, symbol definitions, graph designs and pattern
|
||||
/// tiles.
|
||||
fn text_trees(doc: &Document) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let trees = doc.layers.iter().chain(doc.symbols.iter().map(|s| &s.art));
|
||||
let trees = trees.chain(doc.graph_designs.iter().map(|g| &g.art));
|
||||
trees.chain(doc.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
}
|
||||
|
||||
/// [`text_trees`], to change.
|
||||
fn text_trees_mut(doc: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
|
||||
let trees = doc.layers.iter_mut().chain(doc.symbols.iter_mut().map(|s| &mut s.art));
|
||||
let trees = trees.chain(doc.graph_designs.iter_mut().map(|g| &mut g.art));
|
||||
trees.chain(doc.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
}
|
||||
|
||||
/// Whether tree `n` (opacity mask art included) holds type that `pick` picks.
|
||||
fn has_text_where(n: &Node, pick: &mut dyn FnMut(&TextObject) -> bool) -> bool {
|
||||
matches!(&n.kind, NodeKind::Text(t) if pick(t))
|
||||
|| n.extras().mask.as_deref().is_some_and(|m| has_text_where(&m.art, pick))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| has_text_where(c, pick)))
|
||||
}
|
||||
|
||||
/// Run `act` on the type in tree `n` (opacity mask art included) that `pick` picks. Only the nodes
|
||||
/// on the way to such type are copied.
|
||||
fn each_text_where(n: &mut Arc<Node>, pick: &mut dyn FnMut(&TextObject) -> bool, act: &mut dyn FnMut(&mut TextObject)) {
|
||||
if !has_text_where(n, pick) {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(n);
|
||||
if let NodeKind::Text(t) = &mut n.kind
|
||||
&& t.cached_bounds.is_none()
|
||||
&& pick(t)
|
||||
{
|
||||
cmd::typecmd::refresh_bounds_for_first_frame(t);
|
||||
act(t);
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
|
||||
refresh_tree_text_bounds(&mut m.art);
|
||||
each_text_where(&mut m.art, pick, act);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
refresh_tree_text_bounds(c);
|
||||
each_text_where(c, pick, act);
|
||||
}
|
||||
}
|
||||
@@ -76,9 +76,13 @@ impl Session {
|
||||
cmd::ids_param(params, "ids", id)?;
|
||||
}
|
||||
// Clear's menu needs a selection; an agent supplying explicit targets only needs a
|
||||
// document. The command validates those targets before making any edit.
|
||||
// document. The command validates those targets before making any edit. Cut and Copy given
|
||||
// the artboards the journal recorded need only a document too, whatever is selected and
|
||||
// whichever tool is chosen.
|
||||
let given = given_ids(spec.params, params);
|
||||
let enabled = if id == "edit.clear" && params.get("ids").is_some() {
|
||||
let enabled = if (id == "edit.clear" && params.get("ids").is_some())
|
||||
|| (matches!(id, "edit.copy" | "edit.cut") && params.get("selectedArtboards").is_some())
|
||||
{
|
||||
cmd::has_doc(self)
|
||||
} else if let Some(ids) = given.clone() {
|
||||
// Objects given as `ids` (or `id`) stand in for the selection: the command is enabled
|
||||
@@ -109,11 +113,14 @@ impl Session {
|
||||
})
|
||||
.flatten();
|
||||
let selected_before = select_first.as_ref().and(self.active()).map(|d| (d.uid, d.selection.clone(), d.active_layer));
|
||||
// Only a selection command that changes the selection loads its paints for new art: other
|
||||
// commands, and clicking what is already selected, keep a sampled paint in the proxies.
|
||||
let selection_was = (id.starts_with("select.") || id == "layer.target").then(|| self.active().map(|d| d.selection.clone())).flatten();
|
||||
let run = |s: &mut Session| {
|
||||
if let Some(ids) = &select_first {
|
||||
s.execute("select.set", &serde_json::json!({ "ids": ids }))?;
|
||||
}
|
||||
let r = (spec.run)(s, params);
|
||||
let r = cmd::run_spec(s, spec, params);
|
||||
if r.is_err()
|
||||
&& let Some((uid, selection, layer)) = selected_before
|
||||
&& let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
|
||||
@@ -131,6 +138,9 @@ impl Session {
|
||||
let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) };
|
||||
if r.is_err() && self.depth == 0 {
|
||||
self.batch_paint_docs.clear();
|
||||
// A failed or panicked command's documents are put back: type is drawn in their
|
||||
// composite fonts again, not in those the command set.
|
||||
cmd::compositefonts::sync(self);
|
||||
}
|
||||
let r = r?;
|
||||
if self.depth == 0 {
|
||||
@@ -143,6 +153,9 @@ impl Session {
|
||||
});
|
||||
if !restored {
|
||||
self.inherit_new_art();
|
||||
if selection_was.is_some_and(|was| self.active().is_some_and(|d| d.selection != was)) {
|
||||
self.load_selection_paints();
|
||||
}
|
||||
}
|
||||
for uid in std::mem::take(&mut self.batch_paint_docs) {
|
||||
if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
|
||||
|
||||
+172
-51
@@ -32,7 +32,8 @@ use std::collections::BTreeMap;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use vectorcraft_pdf::{PdfPreset, builtin_preset};
|
||||
use vectorcraft_plugins::safe_mode;
|
||||
@@ -79,9 +80,9 @@ pub(crate) const MAX_CACHE_SCAN: usize = storage::MAX_CACHE_ENTRIES * 2;
|
||||
/// Held while a plug-in's settings or cache change, so two runs can't pass a cap together or lose
|
||||
/// each other's settings.
|
||||
static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
|
||||
/// The closed flag of each plug-in folder's storage, shared by every storage made for the folder
|
||||
/// until the plug-in is removed, which sets it and drops it.
|
||||
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<AtomicBool>>> = Mutex::new(BTreeMap::new());
|
||||
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
|
||||
/// the plug-in is removed, which closes it and drops it.
|
||||
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
|
||||
/// file system, then a hash of the name, so that names that differ only in characters a file name
|
||||
@@ -289,8 +290,8 @@ impl Session {
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant it, is skipped with a log record. A grant covers only the module it was
|
||||
/// given to ([`grant_covers`]).
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant.
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
@@ -376,9 +377,9 @@ impl Session {
|
||||
written && merged.complete()
|
||||
}
|
||||
|
||||
/// Whether `plugin` installs without asking the user: it lists no permissions, or its id was
|
||||
/// granted every one it lists, in the grants of the attached plug-in store when there is one
|
||||
/// (for this module alone, [`grant_covers`]), else in this process's
|
||||
/// Whether `plugin` installs without asking the user: it lists no permissions, or this very
|
||||
/// module (its id and SHA-256) was granted every one it lists, in the grants of the attached
|
||||
/// plug-in store when there is one ([`grant_covers`]), else in this process's
|
||||
/// ([`vectorcraft_plugins::registry::approved`]).
|
||||
pub(crate) fn plugin_approved(&self, plugin: &vectorcraft_plugins::Plugin) -> bool {
|
||||
self.plugin_approver()(plugin)
|
||||
@@ -403,6 +404,29 @@ impl Session {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes))
|
||||
}
|
||||
|
||||
/// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and
|
||||
/// an error, with a log record, when the file can't be read or is larger than the module limit.
|
||||
pub(crate) fn stored_plugin_bytes(&self, id: &str) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(dir) = self.plugin_dir.as_deref() else { return Ok(None) };
|
||||
let path = dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)));
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let max = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
read_capped(&path, max).map(Some).inspect_err(|e| log::warn!("can't read the stored plug-in {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) {
|
||||
match previous {
|
||||
Some(bytes) => {
|
||||
self.store_plugin(id, bytes);
|
||||
}
|
||||
None => self.unstore_plugin(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file the plug-in `id` is stored in, spelled as [`Session::load_stored_plugins`] names it
|
||||
/// (`None` without a plug-in folder).
|
||||
pub(crate) fn stored_plugin_file(&self, id: &str) -> Option<String> {
|
||||
@@ -413,14 +437,15 @@ impl Session {
|
||||
/// other grants as they are; with none left, remove the file. Entries this version can't use
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`.
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) {
|
||||
let Some(dir) = &self.plugin_dir else { return };
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let Some(dir) = &self.plugin_dir else { return false };
|
||||
let mut file = match read_grants(dir) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let others = file.other.len();
|
||||
@@ -430,22 +455,23 @@ impl Session {
|
||||
None => file.grants.remove(id).is_some(),
|
||||
} || file.other.len() != others;
|
||||
if !changed {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
|
||||
entries.extend(file.other);
|
||||
if entries.is_empty() {
|
||||
take(dir, GRANTS_FILE);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
|
||||
// and not at all when that is too.
|
||||
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
|
||||
match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) {
|
||||
Some(bytes) => {
|
||||
put(dir, GRANTS_FILE, &bytes);
|
||||
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
|
||||
None => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE));
|
||||
false
|
||||
}
|
||||
None => log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,7 +500,7 @@ impl Session {
|
||||
/// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it.
|
||||
/// The folder is first renamed out of the way (`<folder>.removed`), and that fails, leaving it
|
||||
/// as it was, when the rename does; what the deletion then leaves stays under that name, with a
|
||||
/// log record, and is deleted at the plug-in's next removal.
|
||||
/// log record. A later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str) -> Result<(), StorageError> {
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
let Some(dir) = &self.plugin_dir else { return Ok(()) };
|
||||
@@ -483,8 +509,8 @@ impl Session {
|
||||
// Every storage handed out for the folder, including those runs still hold, is closed once
|
||||
// the folder is out of the way; until then they keep working.
|
||||
let close = || {
|
||||
if let Some(closed) = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).remove(&path) {
|
||||
closed.store(true, Ordering::Release);
|
||||
if let Some(data) = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).remove(&path) {
|
||||
data.closed.store(true, Ordering::Release);
|
||||
}
|
||||
};
|
||||
// A `storage` folder that is a link leads out of the store: nothing there is deleted. A link
|
||||
@@ -543,22 +569,67 @@ pub(crate) fn plugin_data_dir(dir: &Path, id: &str) -> PathBuf {
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> {
|
||||
let dir = dir?;
|
||||
let data = plugin_data_dir(dir, id);
|
||||
let closed = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone();
|
||||
Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, closed }))
|
||||
let state = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone();
|
||||
Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, state }))
|
||||
}
|
||||
|
||||
/// A file's size and modified time (`None`: there is no file).
|
||||
type FileStamp = Option<(u64, SystemTime)>;
|
||||
|
||||
/// The stamp of the file at `path`.
|
||||
fn file_stamp(path: &Path) -> Result<FileStamp, StorageError> {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(m) => Ok(Some((m.len(), m.modified().map_err(|e| io(&e))?))),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(io(&e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The modified time of the folder at `dir` (`None`: it can't be read, or there is no folder).
|
||||
fn folder_stamp(dir: &Path) -> Option<SystemTime> {
|
||||
std::fs::symlink_metadata(dir).ok()?.modified().ok()
|
||||
}
|
||||
|
||||
/// What every storage made for one plug-in folder shares ([`PLUGIN_DATA_OPEN`]).
|
||||
#[derive(Default)]
|
||||
struct PluginData {
|
||||
/// Set, under [`PLUGIN_DATA_LOCK`], once the plug-in is removed.
|
||||
closed: AtomicBool,
|
||||
kept: Mutex<Kept>,
|
||||
}
|
||||
|
||||
/// What the folder's files last held in this process.
|
||||
#[derive(Default)]
|
||||
struct Kept {
|
||||
settings: Option<KeptSettings>,
|
||||
cache: Option<KeptCache>,
|
||||
}
|
||||
|
||||
/// The settings by key, and the settings file's stamp when they were read or written.
|
||||
struct KeptSettings {
|
||||
stamp: FileStamp,
|
||||
values: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The bytes of the cache entries, and the cache folder's stamp when they were added up.
|
||||
#[derive(Clone, Copy)]
|
||||
struct KeptCache {
|
||||
stamp: Option<SystemTime>,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
/// The settings and cache of one plug-in, in its folder of the plug-in store (see the module docs).
|
||||
/// Keys and entry names are [`storage::valid_name`]s; an entry's file name is its name as
|
||||
/// [`case_safe`] writes it, so that names differing only in case get different files. A link
|
||||
/// anywhere in the folder's path below the store is refused, and so is a cache file that is not a
|
||||
/// plain file.
|
||||
/// plain file. The settings stay in memory ([`Kept`]) while the settings file keeps its size and
|
||||
/// modified time, and every change is written to the file before the call returns. The total
|
||||
/// `cache_bytes` reports stays in memory while the cache folder keeps its modified time.
|
||||
pub(crate) struct PluginStorage {
|
||||
/// The plug-in store, and the plug-in's folder in it.
|
||||
root: PathBuf,
|
||||
dir: PathBuf,
|
||||
/// Set, under [`PLUGIN_DATA_LOCK`], once the plug-in is removed; shared by every storage of the
|
||||
/// folder ([`PLUGIN_DATA_OPEN`]).
|
||||
closed: Arc<AtomicBool>,
|
||||
state: Arc<PluginData>,
|
||||
}
|
||||
|
||||
/// The sizes of `files` added up, at most `u64::MAX`: the sizes come from the file system.
|
||||
@@ -577,12 +648,13 @@ fn io(e: &std::io::Error) -> StorageError {
|
||||
StorageError::Io(e.to_string())
|
||||
}
|
||||
|
||||
/// Does grant `g` cover `plugin`: was it given to this module (the same SHA-256) for every
|
||||
/// Does grant `g` cover `plugin`: was it given to this module (the same id and SHA-256) for every
|
||||
/// permission the module lists? A module with other bytes under the id needs the user's approval
|
||||
/// again, and so doesn't get the settings and cache kept for the id without it, and so does every
|
||||
/// module when the grant records no hash.
|
||||
/// again, and so doesn't get the settings and cache kept for the id without it. A grant whose hash
|
||||
/// is missing or not a valid SHA-256 covers no module.
|
||||
fn grant_covers(g: &vectorcraft_plugins::permissions::Grant, plugin: &vectorcraft_plugins::Plugin) -> bool {
|
||||
!g.hash.is_empty() && g.hash == plugin.hash() && g.covers(&plugin.manifest().permissions())
|
||||
let m = plugin.manifest();
|
||||
g.covers(&m.id, plugin.hash(), &m.permissions())
|
||||
}
|
||||
|
||||
/// Is `path` a link (a symbolic link or, on Windows, a junction)?
|
||||
@@ -631,17 +703,29 @@ impl PluginStorage {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings, by key. A file that is too large or doesn't parse is moved aside
|
||||
/// ([`BAD_SETTINGS_FILE`]) with a log record, and the settings are empty. `meter` is charged the
|
||||
/// file's size before it is read.
|
||||
fn read_settings(&self, meter: &mut Meter) -> Result<BTreeMap<String, Vec<u8>>, StorageError> {
|
||||
fn kept(&self) -> MutexGuard<'_, Kept> {
|
||||
self.state.kept.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The settings: those in `kept` when the settings file still has their stamp, else the file's,
|
||||
/// which then replace them.
|
||||
fn read_settings<'a>(&self, kept: &'a mut Option<KeptSettings>, meter: &mut Meter) -> Result<&'a mut KeptSettings, StorageError> {
|
||||
let path = self.settings_path();
|
||||
self.no_links(&path)?;
|
||||
let size = match std::fs::metadata(&path) {
|
||||
Ok(m) => m.len(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(e) => return Err(io(&e)),
|
||||
let stamp = file_stamp(&path)?;
|
||||
let held = match kept.take() {
|
||||
Some(held) if held.stamp == stamp => held,
|
||||
_ => self.load_settings(stamp, meter)?,
|
||||
};
|
||||
Ok(kept.insert(held))
|
||||
}
|
||||
|
||||
/// Reads the settings file, whose stamp is `stamp`. A file that is too large or doesn't parse is
|
||||
/// moved aside ([`BAD_SETTINGS_FILE`]) with a log record, and the settings are empty. `meter` is
|
||||
/// charged the file's size before it is read.
|
||||
fn load_settings(&self, stamp: FileStamp, meter: &mut Meter) -> Result<KeptSettings, StorageError> {
|
||||
let path = self.settings_path();
|
||||
let Some((size, _)) = stamp else { return Ok(KeptSettings { stamp, values: BTreeMap::new() }) };
|
||||
let readable = size <= storage::MAX_SETTINGS_BYTES as u64;
|
||||
if readable {
|
||||
meter.take(size)?;
|
||||
@@ -657,12 +741,30 @@ impl PluginStorage {
|
||||
settings.filter(|s| s.len() <= storage::MAX_SETTINGS && s.values().all(|v| v.len() <= storage::MAX_SETTING_BYTES))
|
||||
});
|
||||
match parsed {
|
||||
Some(settings) => Ok(settings),
|
||||
Some(values) => Ok(KeptSettings { stamp, values }),
|
||||
None => {
|
||||
let aside = self.dir.join(BAD_SETTINGS_FILE);
|
||||
log::warn!("the plug-in settings {} don't read: moved to {} and started empty", path.display(), aside.display());
|
||||
std::fs::rename(&path, &aside).map_err(|e| io(&e))?;
|
||||
Ok(BTreeMap::new())
|
||||
Ok(KeptSettings { stamp: None, values: BTreeMap::new() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the settings in `kept` to the file and records the file's new stamp. When that fails,
|
||||
/// or settings were written and the file is gone, `kept` is emptied, so the next call reads the
|
||||
/// file again.
|
||||
fn save_settings(&self, kept: &mut Option<KeptSettings>, meter: &mut Meter) -> Result<(), StorageError> {
|
||||
let Some(held) = kept.as_mut() else { return Ok(()) };
|
||||
let written = self.write_settings(&held.values, meter);
|
||||
match (written, file_stamp(&self.settings_path())) {
|
||||
(Ok(()), Ok(stamp)) if stamp.is_some() || held.values.is_empty() => {
|
||||
held.stamp = stamp;
|
||||
Ok(())
|
||||
}
|
||||
(written, _) => {
|
||||
*kept = None;
|
||||
written
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -690,7 +792,7 @@ impl PluginStorage {
|
||||
|
||||
/// Fails with [`StorageError::Unavailable`] once the storage is closed.
|
||||
fn open(&self) -> Result<(), StorageError> {
|
||||
if self.closed.load(Ordering::Acquire) { Err(StorageError::Unavailable) } else { Ok(()) }
|
||||
if self.state.closed.load(Ordering::Acquire) { Err(StorageError::Unavailable) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The entries of the cache folder (plain files named as [`Self::entry_path`] names them, which
|
||||
@@ -727,28 +829,33 @@ impl Storage for PluginStorage {
|
||||
fn setting(&self, key: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
Ok(self.read_settings(meter)?.remove(key))
|
||||
let mut kept = self.kept();
|
||||
Ok(self.read_settings(&mut kept.settings, meter)?.values.get(key).cloned())
|
||||
}
|
||||
|
||||
fn set_setting(&self, key: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut settings = self.read_settings(meter)?;
|
||||
let mut kept = self.kept();
|
||||
let settings = &mut self.read_settings(&mut kept.settings, meter)?.values;
|
||||
if value.len() > storage::MAX_SETTING_BYTES || (!settings.contains_key(key) && settings.len() >= storage::MAX_SETTINGS) {
|
||||
return Err(StorageError::Full);
|
||||
}
|
||||
if settings.get(key).is_some_and(|old| old == value) {
|
||||
return Ok(());
|
||||
}
|
||||
settings.insert(key.to_string(), value.to_vec());
|
||||
self.write_settings(&settings, meter)
|
||||
self.save_settings(&mut kept.settings, meter)
|
||||
}
|
||||
|
||||
fn delete_setting(&self, key: &str, meter: &mut Meter) -> Result<bool, StorageError> {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut settings = self.read_settings(meter)?;
|
||||
if settings.remove(key).is_none() {
|
||||
let mut kept = self.kept();
|
||||
if self.read_settings(&mut kept.settings, meter)?.values.remove(key).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
self.write_settings(&settings, meter).map(|()| true)
|
||||
self.save_settings(&mut kept.settings, meter).map(|()| true)
|
||||
}
|
||||
|
||||
fn cache_entry(&self, name: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
|
||||
@@ -782,7 +889,10 @@ impl Storage for PluginStorage {
|
||||
meter.take(value.len() as u64)?;
|
||||
std::fs::create_dir_all(self.cache_dir()).map_err(|e| io(&e))?;
|
||||
self.no_links(&path)?;
|
||||
write_atomic(&path, value).map_err(|e| io(&e))
|
||||
write_atomic(&path, value).map_err(|e| io(&e))?;
|
||||
let stamp = folder_stamp(&self.cache_dir());
|
||||
self.kept().cache = stamp.map(|_| KeptCache { stamp, bytes: total });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_cache_entry(&self, name: &str) -> Result<bool, StorageError> {
|
||||
@@ -791,7 +901,10 @@ impl Storage for PluginStorage {
|
||||
let path = self.entry_path(name);
|
||||
self.no_links(&path)?;
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(()) => Ok(true),
|
||||
Ok(()) => {
|
||||
self.kept().cache = None;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(e) => Err(io(&e)),
|
||||
}
|
||||
@@ -819,6 +932,7 @@ impl Storage for PluginStorage {
|
||||
freed = freed.saturating_add(m.len());
|
||||
}
|
||||
}
|
||||
self.kept().cache = Some(KeptCache { stamp: folder_stamp(&dir), bytes: 0 });
|
||||
Ok(freed)
|
||||
}
|
||||
|
||||
@@ -826,7 +940,14 @@ impl Storage for PluginStorage {
|
||||
if self.open().is_err() {
|
||||
return 0;
|
||||
}
|
||||
self.cache_files().map(|(files, _)| sum_sizes(&files)).unwrap_or(0)
|
||||
let stamp = folder_stamp(&self.cache_dir());
|
||||
if let Some(kept) = self.kept().cache.filter(|k| k.stamp == stamp) {
|
||||
return kept.bytes;
|
||||
}
|
||||
let Ok((files, _)) = self.cache_files() else { return 0 };
|
||||
let bytes = sum_sizes(&files);
|
||||
self.kept().cache = Some(KeptCache { stamp, bytes });
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Blend Options (defaults with nothing selected, `object.blend.info`) and the Blend tool:
|
||||
//! start points from clicked anchors, adding keys to a blend instead of nesting it (M8.18), and
|
||||
//! Escape dropping the first pick.
|
||||
//! Escape, or an edit made outside the tool, dropping the first pick.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
@@ -233,6 +233,102 @@ fn escape_drops_the_blend_tools_first_pick() {
|
||||
assert_eq!(spec(&s, g).0, vec![b, c], "a was not added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_undo_or_redo_made_outside_the_blend_tool_drops_its_first_pick() {
|
||||
for case in ["edit", "undo", "redo", "group"] {
|
||||
let undo = case == "undo";
|
||||
let mut s = session();
|
||||
let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0));
|
||||
if case == "redo" {
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
// In an open undo group, the edit after the pick is merged into the group's step.
|
||||
if case == "group" {
|
||||
s.begin_undo_group();
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#00ff00"})).unwrap();
|
||||
}
|
||||
s.select_tool("blend", ViewInfo::default()).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap();
|
||||
// Undo takes away c, the object picked first; an edit or a redo recolors c, which is not picked.
|
||||
click(&mut s, if undo { 420.0 } else { 20.0 }, 20.0);
|
||||
assert!(!s.overlays(ViewInfo::default()).is_empty());
|
||||
match case {
|
||||
"undo" => s.execute("edit.undo", &json!({})).unwrap(),
|
||||
"redo" => s.execute("edit.redo", &json!({})).unwrap(),
|
||||
_ => s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(),
|
||||
};
|
||||
assert!(s.overlays(ViewInfo::default()).is_empty(), "{case}: the pick is not marked");
|
||||
let (layers, depth) = (s.doc().unwrap().doc.layers.clone(), s.doc().unwrap().history.undo.len());
|
||||
click(&mut s, 220.0, 20.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![b], "{case}: b is picked first");
|
||||
assert_eq!((&s.doc().unwrap().doc.layers, s.doc().unwrap().history.undo.len()), (&layers, depth), "{case}: the click changes no art");
|
||||
click(&mut s, if undo { 20.0 } else { 420.0 }, 20.0);
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(spec(&s, g).0, if undo { vec![a, b] } else { vec![b, c] }, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_picks_with_no_edit_between_them_blend() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0));
|
||||
s.select_tool("blend", ViewInfo::default()).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap();
|
||||
click(&mut s, 20.0, 20.0);
|
||||
// Drawing the overlays between the picks does not drop the first one.
|
||||
assert!(!s.overlays(ViewInfo::default()).is_empty());
|
||||
click(&mut s, 220.0, 20.0);
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(spec(&s, g).0, vec![a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_blend_the_blend_tool_adds_to_ends_adding() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0));
|
||||
let (d, e) = (rect(&mut s, 0.0, 300.0, 40.0), rect(&mut s, 200.0, 300.0, 40.0));
|
||||
let other = id_of(&s.execute("object.blend.make", &json!({"ids": [d.0, e.0]})).unwrap());
|
||||
s.select_tool("blend", ViewInfo::default()).unwrap();
|
||||
let click = |s: &mut Session, x: f64, y: f64| s.pointer(&PointerEvent::new(PointerKind::Down, x, y), ViewInfo::default()).unwrap();
|
||||
click(&mut s, 20.0, 20.0);
|
||||
click(&mut s, 220.0, 20.0);
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("edit.clear", &json!({"ids": [g.0]})).unwrap();
|
||||
sel(&mut s, &[other]);
|
||||
click(&mut s, 420.0, 20.0);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![c], "c is picked first");
|
||||
assert_eq!(spec(&s, other).0, vec![d, e], "c is not added to the selected blend");
|
||||
assert!([a, b, g].iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "the blend went with its keys");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_change_keeps_the_blend_tools_first_pick() {
|
||||
for drag in [false, true] {
|
||||
let mut s = session();
|
||||
let (a, b, c) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0), rect(&mut s, 400.0, 0.0, 40.0));
|
||||
let view = ViewInfo::default();
|
||||
s.select_tool("blend", view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 20.0, 20.0), view).unwrap();
|
||||
sel(&mut s, &[c]);
|
||||
// Cmd lends the selection tool: a click on c selects it, a drag moves it (an edit).
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let to = if drag { 440.0 } else { 420.0 };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 20.0).with_mods(cmd), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, to, 20.0).with_mods(cmd), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, to, 20.0).with_mods(cmd), view).unwrap();
|
||||
assert_eq!(s.tool_id(), "blend");
|
||||
assert_eq!(s.overlays(view).is_empty(), drag, "drag {drag}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 20.0), view).unwrap();
|
||||
if drag {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![b], "the drag dropped the pick");
|
||||
} else {
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(spec(&s, g).0, vec![a, b]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_points_round_trip_and_old_blends_load() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2969,6 +2969,91 @@ fn image_trace_make_places_paths_over_the_image() {
|
||||
assert_eq!(paths[0].appearance.fill_paint(), Paint::solid(Color::rgb8(0, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_keep_colors_traces_only_the_colors_listed() {
|
||||
// A light field with a black ring, a red square and a blue bar on it.
|
||||
let art = vectorcraft_trace::Raster::from_fn(200, 150, |x, y| {
|
||||
let r = (f64::from(x) + 0.5 - 70.0).hypot(f64::from(y) + 0.5 - 60.0);
|
||||
if (34.0..=40.0).contains(&r) {
|
||||
[0, 0, 0, 255]
|
||||
} else if (130..170).contains(&x) && (30..70).contains(&y) {
|
||||
[200, 40, 50, 255]
|
||||
} else if (30..170).contains(&x) && (110..130).contains(&y) {
|
||||
[40, 80, 200, 255]
|
||||
} else {
|
||||
[240, 240, 220, 255]
|
||||
}
|
||||
});
|
||||
let traced = |keep: Value| {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::IDENTITY);
|
||||
let params = json!({"params": {"mode": "color", "palette": "limited", "colors": 4, "keepColors": keep}});
|
||||
let r = s.execute("imageTrace.makeAndExpand", ¶ms)?;
|
||||
let g = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
let fills: Vec<Paint> = g.children().unwrap().iter().map(|n| n.appearance.fill_paint()).collect();
|
||||
Ok::<_, EngineError>((r["colors"].clone(), fills))
|
||||
};
|
||||
let (black, red, blue, light) = (Color::rgb8(0, 0, 0), Color::rgb8(200, 40, 50), Color::rgb8(40, 80, 200), Color::rgb8(240, 240, 220));
|
||||
let has = |fills: &[Paint], c: Color| fills.contains(&Paint::solid(c));
|
||||
// Nothing listed: every color.
|
||||
let (colors, fills) = traced(json!([])).unwrap();
|
||||
assert_eq!(colors, 4);
|
||||
assert!([black, red, blue, light].into_iter().all(|c| has(&fills, c)), "{fills:?}");
|
||||
// The black and the red only.
|
||||
let (colors, fills) = traced(json!(["#000000", "#c8283c"])).unwrap();
|
||||
assert_eq!(colors, 2);
|
||||
assert!(has(&fills, black) && has(&fills, red), "{fills:?}");
|
||||
assert!(fills.iter().all(|f| *f == Paint::solid(black) || *f == Paint::solid(red)), "{fills:?}");
|
||||
// A color that is none is refused.
|
||||
let e = traced(json!(["#000000", "black"])).unwrap_err().to_string();
|
||||
assert!(e.contains("\"black\"") && e.contains("#rrggbb"), "{e}");
|
||||
assert!(find_command("imageTrace.make").unwrap().params.contains("keepColors?: [\"#rrggbb\"…]"));
|
||||
assert!(find_command("imageTrace.makeAndExpand").unwrap().params.contains("warnings: [text…] (as imageTrace.make)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_keep_colors_warns_about_colors_that_match_nothing() {
|
||||
// A light field with a black ring and a red square on it.
|
||||
let art = vectorcraft_trace::Raster::from_fn(200, 150, |x, y| {
|
||||
let r = (f64::from(x) + 0.5 - 70.0).hypot(f64::from(y) + 0.5 - 60.0);
|
||||
if (34.0..=40.0).contains(&r) {
|
||||
[0, 0, 0, 255]
|
||||
} else if (130..170).contains(&x) && (30..70).contains(&y) {
|
||||
[200, 40, 50, 255]
|
||||
} else {
|
||||
[240, 240, 220, 255]
|
||||
}
|
||||
});
|
||||
let traced = |params: Value| {
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::IDENTITY);
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({ "params": params })).unwrap();
|
||||
(r["paths"].as_u64().unwrap(), r["warnings"].clone())
|
||||
};
|
||||
let color = |keep: Value| traced(json!({"mode": "color", "palette": "limited", "colors": 3, "keepColors": keep}));
|
||||
// Every color listed is in the image: no warning.
|
||||
let (paths, warnings) = color(json!(["#000000", "#c8283c"]));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!([]));
|
||||
// No color matches: nothing is traced, and the reply says why.
|
||||
assert_eq!(
|
||||
color(json!(["#ff00ff", "#00ffff"])),
|
||||
(0, json!(["Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff)."]))
|
||||
);
|
||||
// One color matches nothing: the others are traced, and that one is named.
|
||||
let (paths, warnings) = color(json!(["#000000", "#00ffff"]));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!(["keepColors: none of the colors the trace found matches #00ffff, so nothing of it is traced."]));
|
||||
// Ignore Color leaves out the only color listed.
|
||||
let ignored =
|
||||
traced(json!({"mode": "color", "palette": "limited", "colors": 3, "keepColors": ["#000000"], "ignoreWhite": true, "ignoreColor": "#000000"}));
|
||||
assert_eq!(ignored, (0, json!(["Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists."])));
|
||||
// Flat Logo mode does not use the list.
|
||||
let (paths, warnings) = traced(json!({"mode": "logo", "keepColors": ["#ff00ff"]}));
|
||||
assert!(paths > 0);
|
||||
assert_eq!(warnings, json!(["Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds."]));
|
||||
}
|
||||
|
||||
/// #3098: a trace made away from the command (off the UI thread) and handed in makes the command's
|
||||
/// own edit, as one undo step; Cancel stops it; once its image has changed it no longer applies.
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user