Merge main into feat/color-rgb-percent

This commit is contained in:
dotCooCoo committed 2026-11-12 15:11:03 -08:00
commit 5494e1aaa7
467 files changed
+36566 -2846

No files matched your search

Generated
+14 -13
View File
@@ -217,7 +217,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -986,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1060,7 +1060,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1081,7 +1081,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"chrono",
"dunce",
@@ -1108,7 +1108,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
dependencies = [
"flate2",
"serde",
@@ -1620,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3869,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4391,7 +4391,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4769,7 +4769,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4828,7 +4828,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5687,7 +5687,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6326,6 +6326,7 @@ dependencies = [
"craft-window",
"eframe",
"egui",
"futures-lite",
"image",
"log",
"muda",
@@ -7516,7 +7517,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
+3 -3
View File
@@ -14,18 +14,18 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
+1
View File
@@ -246,6 +246,7 @@ fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
h
}
+3
View File
@@ -107,6 +107,9 @@ wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
futures-lite = "2"
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
+7 -3
View File
@@ -1,10 +1,10 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use super::portal_save;
#[cfg(target_os = "linux")]
use super::tablet;
#[cfg(all(windows, not(target_vendor = "win7")))]
use super::windows_stylus;
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
#[cfg(target_os = "linux")]
use super::{linux_screen_color, tablet};
#[cfg(target_os = "macos")]
use super::{mac_save_format, mac_screen_color, mac_tablet};
@@ -354,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
let (clip, clip_probe) = (parent.clone(), parent.clone());
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
let sampled_ui = ui.clone();
#[cfg(target_os = "linux")]
let sampled_parent = p1.clone();
Services {
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
@@ -408,6 +410,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
// Sample Color from Screen: the system's color sampler.
#[cfg(target_os = "macos")]
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
#[cfg(target_os = "linux")]
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
..Default::default()
@@ -0,0 +1,42 @@
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
mod portal;
mod request;
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
Box::new(move || {
let (tx, rx) = std::sync::mpsc::channel();
let (ui, window) = (ui.clone(), parent.clone());
std::thread::Builder::new()
.name("screen-color".into())
.spawn(move || {
// The thread names the window and holds it until the export that names it is dropped.
let (handle, export) = match window.as_deref() {
Some(window) => {
let (handle, export) = super::portal_save::exported_parent(window);
(handle, Some(export))
}
None => (String::new(), None),
};
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
drop(export);
drop(window);
let answer = picked.map_err(|failure| {
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
failure.message().to_string()
});
// The UI may be gone (the app quitting): nothing waits for the color then.
let _ = tx.send(answer);
ui.request_repaint();
})
.map_err(|e| {
log::warn!("could not start the screen color sampler's thread: {e}");
"the screen color sampler failed".to_string()
})?;
Ok(rx)
})
}
@@ -0,0 +1,319 @@
//! The XDG desktop portal's `Screenshot.PickColor`
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
//! the call returns a request path at once, and the request's `Response` signal later carries the
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
use std::collections::HashMap;
use zbus::blocking::{Connection, Proxy};
use zbus::zvariant::{OwnedValue, Value};
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
/// the sampler, so the person's time with the sampler does not count.
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
/// Why no color came back, as the status bar shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Failure {
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
Unavailable(String),
/// The portal did not return a request path in time, or it left the bus before it answered.
NoAnswer(String),
/// The portal ended the request without a color, or its answer can't be read.
Failed(String),
}
impl Failure {
/// The status bar's message (English; the status bar translates it).
pub(super) fn message(&self) -> &'static str {
match self {
Failure::Unavailable(_) => "this system has no screen color sampler",
Failure::NoAnswer(_) => "the screen color sampler did not answer",
Failure::Failed(_) => "the screen color sampler failed",
}
}
/// What went wrong, for the log.
pub(super) fn detail(&self) -> &str {
match self {
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
}
}
}
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
const UNAVAILABLE: &[&str] = &[
"org.freedesktop.DBus.Error.ServiceUnknown",
"org.freedesktop.DBus.Error.NameHasNoOwner",
"org.freedesktop.DBus.Error.UnknownMethod",
"org.freedesktop.DBus.Error.UnknownInterface",
"org.freedesktop.DBus.Error.UnknownObject",
];
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
}
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
/// after it has no bound, and ends when the portal answers or leaves the bus.
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
// Made before the call: a portal can send its answer before the call returns.
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| Failure::Failed(e.to_string()))?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
answer(code, &results)
}
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
fn call_failure(e: &zbus::Error) -> Failure {
match e {
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
_ => Failure::Failed(e.to_string()),
}
}
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
/// any other code ends the request without one. The components are passed on as given;
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
match code {
0 => {}
1 => return Ok(None),
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
}
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
match &**color {
Value::Structure(s) => match s.fields() {
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
},
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
}
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
matches!(r, Err(Failure::Failed(_)))
}
#[test]
fn a_picked_color_keeps_its_srgb_values() {
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
}
#[test]
fn a_cancel_needs_no_color() {
assert_eq!(answer(1, &HashMap::new()), Ok(None));
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
}
#[test]
fn other_response_codes_are_failures() {
for code in [2, 3, u32::MAX] {
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
}
}
#[test]
fn a_success_without_a_valid_color_is_a_failure() {
assert!(failed(answer(0, &HashMap::new())));
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
assert!(failed(answer(0, &wrong)));
// Fewer fields, more fields, and fields of another type: an error, not a panic.
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
assert!(failed(answer(0, &wrong)));
}
}
#[test]
fn call_errors_say_whether_the_system_has_a_sampler() {
let reply = |name: &str| {
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
zbus::Error::from(error)
};
for name in UNAVAILABLE {
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
}
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
assert_eq!(
messages,
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
);
assert_eq!(call_failure(&broken).detail(), broken.to_string());
}
/// Every language that translates the sampler's other messages translates these too. The
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
#[test]
fn the_messages_are_translated_where_the_sampler_is() {
use vectorcraft_ui_egui::i18n::{Lang, message};
const OPEN: &str = "the screen color sampler is already open";
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
for lang in langs {
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
}
}
}
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
fn client(address: &str) -> Connection {
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
}
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
/// starts an installed portal in its place.
fn portal(address: &str) -> Connection {
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
}
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
/// other request paths or from other connections are ignored; a cancel gives no color; and a
/// portal that leaves the bus while the person picks ends the wait.
#[test]
fn the_answer_is_the_portals_response_on_the_returned_path() {
use zbus::blocking::MessageIterator;
use zbus::zvariant::OwnedObjectPath;
let Some((_daemon, address)) = private_bus() else { return };
let address = address.as_str();
let server = portal(address);
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
let incoming = MessageIterator::from(&server);
let worker = std::thread::spawn(move || {
let mut calls = Vec::new();
for msg in incoming {
let msg = msg.unwrap();
let header = msg.header();
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
continue;
}
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
assert!(token.starts_with("vectorcraft_color_"));
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
assert!(!calls.iter().any(|(_, old)| old == &token));
calls.push((parent, token));
// A portal older than version 0.9 answers on a path of its own, not the token's.
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
if calls.len() == 4 {
server.reply(&header, &handle).unwrap();
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
break;
}
let to = header.sender().cloned().map(zbus::names::BusName::from);
// Another connection can't end the wait by claiming the portal left.
impostor
.emit_signal(
to.clone(),
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"NameOwnerChanged",
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
)
.unwrap();
let wrong = color((1.0, 0.0, 0.0));
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
// The reply that names the path goes last: every answer above came before it.
server.reply(&header, &handle).unwrap();
}
calls
});
let client = client(address);
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
assert_eq!(pick(&client, "wayland:example"), Ok(None));
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
let calls = worker.join().unwrap();
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
}
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
#[test]
fn a_portal_without_pick_color_ends_the_request() {
let Some((_daemon, address)) = private_bus() else { return };
let address = address.as_str();
let server = portal(address);
let incoming = zbus::blocking::MessageIterator::from(&server);
let worker = std::thread::spawn(move || {
for msg in incoming {
let msg = msg.unwrap();
let header = msg.header();
if header.member().map(|m| m.as_str()) == Some("PickColor") {
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
break;
}
}
});
let client = client(address);
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
let failure = pick(&client, "");
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
worker.join().unwrap();
}
}
@@ -0,0 +1,127 @@
//! The answer to the color sampler's XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
//! first.
use std::io::Read as _;
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
pub(super) fn token(prefix: &str) -> Result<String, String> {
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(super) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes.
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
let header = reply.header();
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
{
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
}
+4 -7
View File
@@ -35,7 +35,6 @@ trait Backend {
fn suspend(&mut self, window: &Self::Window);
fn restore(&mut self, window: &Self::Window);
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
fn current(&self) -> Option<Self::Cursor>;
fn set(&mut self, cursor: &Self::Cursor);
}
@@ -73,9 +72,10 @@ impl<B: Backend> State<B> {
&& *key == request.key
&& *owned == window
{
if self.backend.current().as_ref() != Some(cursor) {
self.backend.set(cursor);
}
// AppKit can show the system arrow when the pointer moves while
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
// comparison would keep the arrow. Setting the cursor again costs nothing.
self.backend.set(cursor);
return;
}
self.release();
@@ -135,9 +135,6 @@ impl Backend for AppKit {
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
build(&request.bitmap)
}
fn current(&self) -> Option<Self::Cursor> {
Some(NSCursor::currentCursor())
}
fn set(&mut self, cursor: &Self::Cursor) {
cursor.set();
}
+5 -14
View File
@@ -6,7 +6,6 @@ use std::cell::Cell;
struct Fake {
window: Option<u8>,
suspended: Vec<u8>,
current: Option<Key>,
sets: usize,
builds: usize,
restores: Vec<u8>,
@@ -27,17 +26,12 @@ impl Backend for Fake {
fn restore(&mut self, w: &u8) {
self.suspended.retain(|v| v != w);
self.restores.push(*w);
self.current = None;
}
fn build(&mut self, r: &Request) -> Option<Key> {
self.builds += 1;
(!self.fail).then_some(r.key)
}
fn current(&self) -> Option<Key> {
self.current
}
fn set(&mut self, cursor: &Key) {
self.current = Some(*cursor);
fn set(&mut self, _: &Key) {
self.sets += 1;
}
}
@@ -66,19 +60,16 @@ fn deliver(state: &mut State<Fake>, request: Option<Request>) {
}
#[test]
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
let req = request(1.0);
let mut state = fake_state();
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.suspended, [1]);
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.sets, 1);
// Simulate a platform fallback replacing the cursor after finalization. The next pass
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
state.backend.current = None;
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.sets, 2);
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
deliver(&mut state, None);
assert_eq!(state.backend.restores, [1]);
deliver(&mut state, Some(req.clone()));
+4
View File
@@ -32,6 +32,8 @@ mod cursor_theme;
mod gpu;
mod hang_watch;
#[cfg(target_os = "linux")]
mod linux_screen_color;
#[cfg(target_os = "linux")]
mod linux_stylus;
mod logging;
#[cfg(all(target_os = "macos", feature = "wgpu"))]
@@ -485,6 +487,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_pdf_preset_store(&mut app.session);
// The custom dictionary's words, kept in their own file next to the preferences.
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
+7
View File
@@ -242,6 +242,13 @@ fn parent(window: &winit::window::Window) -> (String, Option<wayland::Export>) {
}
}
/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`):
/// the identifier stays valid until the second value is dropped.
#[cfg(target_os = "linux")]
pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) {
parent(window)
}
/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off
/// Linux).
#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
+8
View File
@@ -81,6 +81,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
/// file next to the settings, and list the heads it holds.
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
session.attach_arrowheads_file(path.to_string_lossy().to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
+12 -9
View File
@@ -370,11 +370,14 @@ pub struct ArtBrush {
pub scale: ArtScale,
/// Width in percent.
pub width: f64,
/// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from
/// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest.
/// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the
/// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure
/// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing
/// and Rotation from −180° to 180° (half way at 0°).
#[serde(skip_serializing_if = "Option::is_none")]
pub width_mode: Option<Variation>,
/// The width at the heaviest pen pressure (%), for Pressure (`width` without one).
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
/// at 180° (`width` without one).
#[serde(skip_serializing_if = "Option::is_none")]
pub width_max: Option<f64>,
pub flip_along: bool,
@@ -388,11 +391,11 @@ impl ArtBrush {
/// The range of the width (%).
pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0);
/// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the
/// width follows the pressure.
/// The widths (%) where the pen reads 0 and 1 for the width's mode (the lightest and the
/// heaviest pressure, for Pressure): `width` for both unless the width follows the pen.
pub fn width_range(&self) -> (f64, f64) {
match self.width_mode {
Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)),
Some(m) if m.follows_pen() => (self.width, self.width_max.unwrap_or(self.width)),
_ => (self.width, self.width),
}
}
@@ -713,8 +716,8 @@ impl Brush {
}
BrushKind::Art(a) => {
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
// The width follows the pen's pressure or stays fixed.
if a.width_mode != Some(Variation::Pressure) {
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
if !a.width_mode.is_some_and(Variation::follows_pen) {
a.width_mode = None;
}
a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width));
@@ -806,7 +809,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
let mut out = match &brush.kind {
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
};
+56
View File
@@ -1371,6 +1371,62 @@ fn art_brush_width_follows_the_pressure() {
assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}");
}
/// Art Brush Options: Width on Tilt goes from Width with the pen lying flat to the second width
/// upright, and on Bearing or Rotation from Width at −180° to the second width at 180°, along the
/// stroke as the pen recorded it; each mode reads only its own input.
#[test]
fn art_brush_width_follows_tilt_bearing_and_rotation() {
let brush = |mode: Variation| {
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
if let BrushKind::Art(a) = &mut b.kind {
(a.width, a.width_mode, a.width_max) = (50.0, Some(mode), Some(300.0));
}
b
};
let bp = line(0.0, 0.0, 100.0, 0.0);
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
// Tilt, upright at the start (300 %: 6 pt either side of 4 pt art) to flat at the end (50 %: 1 pt).
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
let out = draw(&brush(Variation::Tilt), &upright_to_flat);
assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0));
// Bearing and Rotation: half way at 0°, a quarter of the way at −90°, three quarters at 90°.
for (mode, angle, half) in [
(Variation::Bearing, 0.0, 3.5),
(Variation::Bearing, -90.0, 2.25),
(Variation::Bearing, 90.0, 4.75),
(Variation::Rotation, -90.0, 2.25),
(Variation::Rotation, 90.0, 4.75),
] {
let st = if mode == Variation::Bearing { posed(Some(0.5), Some(angle), None) } else { posed(None, None, Some(angle)) };
let h = bounds(&draw(&brush(mode), &st)).height();
assert!(near(h, 2.0 * half, 1e-6), "{mode:?} {angle}: {h}");
}
// Each mode reads its own input: without it (the pressure, or another of the pen's values
// recorded instead), the art is half way between the two widths.
let others = [
(Variation::Tilt, posed(None, Some(90.0), Some(90.0))),
(Variation::Tilt, pressed(vec![(0.0, 0.0), (1.0, 1.0)])),
(Variation::Bearing, posed(Some(0.0), None, Some(90.0))),
(Variation::Rotation, posed(Some(0.0), Some(90.0), None)),
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0))),
];
for (mode, st) in others {
let h = bounds(&draw(&brush(mode), &st)).height();
assert!(near(h, 7.0, 1e-6), "{mode:?}: {h}");
}
// The pen's modes are kept when a definition is read, and Random is read as Fixed.
let lib = parse_library(&serde_json::json!([
{"name": "t", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "tilt", "width_max": 300.0},
{"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "bearing", "width_max": 300.0},
{"name": "r", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "rotation", "width_max": 300.0},
{"name": "x", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 300.0},
]));
let modes: Vec<_> = lib.iter().map(|b| if let BrushKind::Art(a) = &b.kind { a.width_mode } else { None }).collect();
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
}
/// Definitions from files and commands are kept within their ranges.
#[test]
fn sanitize_keeps_values_within_their_ranges() {
+6 -5
View File
@@ -8,7 +8,7 @@
use std::sync::Arc;
use kurbo::ParamCurveNearest;
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
use crate::track::{Rng, Track, normal, seed_of, tracks};
@@ -503,9 +503,10 @@ fn art_on_run(
bend_widened(t, art, b, along, cross, widen)
}
/// An art brush's art along `bp`. With a width that follows the pen's pressure, the art is as
/// wide as the pressure recorded at each point of the stroke gives (half way without a recording).
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>) -> Vec<Node> {
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
/// or rotation), the art is as wide as what `stroke` recorded at each point gives (half way
/// without a recording).
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] };
let (light, heavy) = a.width_range();
let width = light.max(heavy);
@@ -522,7 +523,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
}
// A run past the start of a closed track wraps round to it.
let at = if s > l { s - l } else { s };
let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0);
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
(light + (heavy - light) * p) / width
};
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
+11 -7
View File
@@ -187,6 +187,9 @@ pub struct HpglOutput {
pub pens: Vec<[u8; 3]>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// Notes on the options: sorting the paths or drawing the inner paths first was applied only
/// in part.
pub setting_notes: Vec<String>,
}
/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are
@@ -280,10 +283,11 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
if !by_pen.iter().all(Vec::is_empty) {
pen_warnings.iter().for_each(|w| warn(&mut warnings, w));
}
let mut setting_notes = vec![];
if opts.sort || opts.inside_first {
let (mut at, mut work) = ((0, 0), MAX_SORT_WORK);
for paths in &mut by_pen {
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut warnings);
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut setting_notes);
}
}
if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) {
@@ -293,7 +297,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
Version::Hpgl => plain(&by_pen),
Version::Hpgl2 => encoded(&by_pen, &pens),
};
out.push(HpglOutput { bytes, pens: pens.clone(), warnings });
out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes });
}
Ok(out)
}
@@ -366,20 +370,20 @@ fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 {
/// for a closed path any of its points (where it then starts); without, the first in paint order.
/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is.
/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with
/// `inside_first`, with a warning. Returns where the pen stops.
/// `inside_first`, with a note in `notes`. Returns where the pen stops.
fn reorder(
paths: &mut Vec<Vec<(i64, i64)>>,
mut at: (i64, i64),
work: &mut u64,
nearest: bool,
inside_first: bool,
warnings: &mut Vec<String>,
notes: &mut Vec<String>,
) -> (i64, i64) {
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect();
// The paths each path lies inside, and how many paths inside each are still to draw.
let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten();
if inside_first && outer.is_none() {
warn(warnings, UNNESTED);
warn(notes, UNNESTED);
}
let mut waiting = vec![0usize; paths.len()];
for o in outer.iter().flatten().flatten() {
@@ -430,11 +434,11 @@ fn reorder(
if *work == 0 || best.0 >= left.len() {
match &outer {
Some(outer) => {
warn(warnings, UNSORTED_INSIDE);
warn(notes, UNSORTED_INSIDE);
inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths);
}
None => {
warn(warnings, UNSORTED);
warn(notes, UNSORTED);
paths.extend(left.into_iter().map(|(_, p, _)| p));
}
}
+7 -6
View File
@@ -852,7 +852,8 @@ fn sorting_measures_a_closed_path_by_its_nearest_point() {
fn sorting_stops_at_its_budget_and_keeps_every_path() {
let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) });
assert!(out.warnings.iter().any(|w| w == UNSORTED), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [UNSORTED]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(text(&out).matches("PD").count(), 600);
}
@@ -944,18 +945,18 @@ fn inside_first_orders_each_pens_paths() {
}
/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in
/// paint order, with a warning.
/// paint order, with a note on the option.
#[test]
fn inside_first_past_its_budget_draws_in_paint_order() {
let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED]);
assert_eq!(out.setting_notes, [UNNESTED]);
let l = lefts(&out);
assert_eq!(l.len(), 100);
assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}");
// With `sort` too, the budget is spent before sorting starts: paint order, with both warnings.
// With `sort` too, the budget is spent before sorting starts: paint order, with both notes.
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED, UNSORTED]);
assert_eq!(out.setting_notes, [UNNESTED, UNSORTED]);
assert_eq!(lefts(&out), l);
}
@@ -969,7 +970,7 @@ fn inside_first_past_its_sorting_budget_keeps_the_rings_last() {
v
});
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNSORTED_INSIDE]);
assert_eq!(out.setting_notes, [UNSORTED_INSIDE]);
let l = lefts(&out);
assert_eq!(l.len(), 602);
assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..]));
+3
View File
@@ -410,6 +410,9 @@ pub struct DxfOutput {
pub images: Vec<DxfImage>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// What was left out because an option turns it off (Include Placed Images or Include Fill
/// Hatches off).
pub setting_notes: Vec<String>,
}
/// The smallest and largest `scale` (drawing units per unit).
+15 -3
View File
@@ -520,6 +520,8 @@ pub(crate) struct Scene<'a> {
/// Image keys → index into `images` (`None`: left out).
by_key: HashMap<String, Option<usize>>,
warnings: Vec<String>,
/// What was left out because an option asked for it ([`DxfOutput::setting_notes`]).
setting_notes: Vec<String>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
extents: Option<[f64; 4]>,
/// The opacity of the containers around the current object.
@@ -554,6 +556,7 @@ impl<'a> Scene<'a> {
files: vec![],
by_key: HashMap::new(),
warnings: vec![],
setting_notes: vec![],
brushes: None,
extents: None,
opacity: 1.0,
@@ -588,15 +591,24 @@ impl<'a> Scene<'a> {
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
}
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
/// it changed. A note about an option goes to [`Self::note_setting`].
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
/// Note `w`, once, about something left out because an option turns it off.
fn note_setting(&mut self, w: &str) {
if !self.setting_notes.iter().any(|x| x == w) {
self.setting_notes.push(w.to_string());
}
}
fn handle(&mut self) -> Handle {
let h = Handle(self.next);
self.next = self.next.saturating_add(1);
@@ -930,7 +942,7 @@ impl<'a> Scene<'a> {
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
self.lines(&closed_fill(outline), style, 0.0);
if !self.o.include_hatches {
self.warn(HATCHES_OFF);
self.note_setting(HATCHES_OFF);
return;
}
let h = self.handle();
@@ -1321,7 +1333,7 @@ impl<'a> Scene<'a> {
return;
}
if !self.o.include_images {
self.warn(IMAGES_OFF);
self.note_setting(IMAGES_OFF);
return;
}
let Some(i) = self.image_def(im) else { return };
+13 -8
View File
@@ -881,12 +881,13 @@ fn fills_without_hatches_keep_their_outlines() {
let d = shapes_doc();
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
assert_eq!(out.warnings, [HATCHES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [HATCHES_OFF]);
let e = entities(&out);
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
// Hatches stay by default, with no note.
let on = export(&d, &opts(&d)).unwrap();
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty());
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
let compound = doc_with(|d| {
@@ -916,13 +917,14 @@ fn fills_without_hatches_keep_their_outlines() {
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
// Nothing filled: no note.
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap();
assert!(none.warnings.is_empty() && none.setting_notes.is_empty());
// R12 has no hatches anyway: the same outlines, and its own note alone.
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
let (off, on) = (r12(false), r12(true));
assert_eq!(off.bytes, on.bytes);
assert_eq!(off.warnings, on.warnings);
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(off.setting_notes.is_empty());
}
#[test]
@@ -957,15 +959,18 @@ fn images_can_be_left_out_with_their_files() {
let p = pairs(&out.bytes);
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
assert_eq!(out.warnings, [IMAGES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
// R12 has no images anyway: its own note alone.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
#[test]
@@ -983,7 +988,7 @@ fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_b
let cnc = run(DxfPreset::Cnc.options());
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
assert!(cnc.images.is_empty());
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes);
let custom = DxfPreset::Custom.options();
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
}
+178 -4
View File
@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize};
use crate::Color;
use crate::freeform::Freeform;
mod spread;
pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum GradientKind {
#[default]
@@ -94,6 +97,82 @@ impl GradientMethod {
}
}
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
pub enum GradientSpread {
/// The first and last stops' colors carry on past the ends, as gradients always did.
#[default]
Pad,
/// The stops start again at each end.
Repeat,
/// The stops run back the other way at each end, so every other run is mirrored.
Reflect,
}
impl GradientSpread {
/// Every spread, in the order the Gradient panel lists them.
pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect];
/// Parse a spread name (`pad`, `repeat`, `reflect`; any case).
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
}
pub fn label(self) -> &'static str {
match self {
Self::Pad => "Pad",
Self::Repeat => "Repeat",
Self::Reflect => "Reflect",
}
}
pub fn is_pad(&self) -> bool {
*self == Self::Pad
}
}
impl<'de> Deserialize<'de> for GradientSpread {
/// A spread name; a file's unknown name or other value reads as Pad.
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
Name(String),
Other(serde::de::IgnoredAny),
}
Ok(match Raw::deserialize(d)? {
Raw::Name(s) => Self::parse(&s).unwrap_or_default(),
Raw::Other(_) => Self::Pad,
})
}
}
/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own
/// limit.
pub const MAX_REPEATS: u32 = 100;
fn one_repeat() -> u32 {
1
}
fn is_one_repeat(n: &u32) -> bool {
*n == 1
}
/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else
/// reads as 1.
fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Raw {
Number(f64),
Other(serde::de::IgnoredAny),
}
Ok(match Raw::deserialize(d)? {
Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32,
_ => 1,
})
}
/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
/// expanded stops may stray from the perceptual mix: under half a colour level.
const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
@@ -259,6 +338,15 @@ pub struct Gradient {
/// How the colours between the stops are mixed (Classic unless set; written only when not).
#[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
pub method: GradientMethod,
/// What it paints past the ends of its stops (Pad unless set; written only when not). A
/// freeform gradient has no ends and ignores it.
#[serde(default, skip_serializing_if = "GradientSpread::is_pad")]
pub spread: GradientSpread,
/// How many times the stops run along the vector with Repeat and Reflect, 1 to
/// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad
/// ignores it. Written only when it is not 1.
#[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")]
pub repeats: u32,
}
impl Default for Gradient {
@@ -271,7 +359,55 @@ impl Default for Gradient {
impl Gradient {
/// A gradient of `kind` through `stops`, with the default options.
pub fn new(kind: GradientKind, stops: Vec<GradientStop>) -> Self {
Self { kind, stops, dither: false, method: GradientMethod::Classic }
Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 }
}
/// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`].
pub fn repeat_count(&self) -> u32 {
self.repeats.clamp(1, MAX_REPEATS)
}
/// Does it paint something other than its end colors past the ends of its stops, or run its
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
pub fn is_spread(&self) -> bool {
!self.spread.is_pad() && self.kind != GradientKind::Freeform
}
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
/// for two gradients whose spreads paint alike.
pub fn painted_spread(&self) -> (GradientSpread, u32) {
if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) }
}
/// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the
/// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops
/// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run
/// mirrored with Reflect. A `t` that is not finite is returned as it is.
pub fn spread_param(&self, t: f64) -> f64 {
self.spreader()(t)
}
/// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where
/// `per_turn` would do for stops that run once around: that many for each time the stops run
/// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its
/// turn.
pub fn conic_wedge_count(&self, per_turn: usize) -> usize {
let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 };
per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES)
}
/// [`Self::spread_param`] as a function that holds no borrow of the gradient.
pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> {
let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad };
let n = f64::from(self.repeat_count());
move |t: f64| {
if !t.is_finite() {
return t;
}
match spread {
GradientSpread::Pad => t,
GradientSpread::Repeat => (t * n).rem_euclid(1.0),
GradientSpread::Reflect => {
let w = (t * n).rem_euclid(2.0);
if w > 1.0 { 2.0 - w } else { w }
}
}
}
}
/// Colour and opacity at `t` (honours midpoints and the method).
pub fn sample(&self, t: f32) -> (Color, f32) {
@@ -544,10 +680,18 @@ impl Gradient {
GradientStop { opacity, ..GradientStop::new(offset, color) }
};
let d = to - from;
let mut stops = vec![stop(0.0, from)];
let expanded = self.expanded_stops();
// Where stops share the offset `from` (a sharp step, as where the runs of a repeating
// gradient meet), the piece starts with the color after the step; sampling gives the one
// before it.
let first = match expanded.iter().rev().find(|(t, ..)| *t == from) {
Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) },
_ => stop(0.0, from),
};
let mut stops = vec![first];
if d > 1e-6 {
stops.extend(
self.expanded_stops()
expanded
.into_iter()
.filter(|(t, ..)| *t > from && *t < to)
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
@@ -954,6 +1098,35 @@ impl GradientGeom {
self.set_focal(Some(m * q));
}
}
/// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or
/// diamond gradient: the vector `k` times as long from the same start, and for an off-center
/// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps
/// its placement (its level is a turn).
pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom {
if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) {
return *self;
}
let u = self.end - self.start;
let mut out = *self;
if kind == GradientKind::Radial
&& let (Some(f), Some(frame)) = (self.focal, self.unit_frame())
{
// Level t of an off-center radial is the extent ellipse scaled by t about the line
// from the focal point to the center: the new center sits on that line, `k` times as
// far from the focal point.
let f = (frame.inverse() * f).to_vec2();
out.start = frame * (f * (1.0 - k)).to_point();
}
out.end = out.start + u * k;
out
}
/// The placement over which one run of the stops of a gradient that repeats `n` times along
/// its vector lies ([`Self::levels_scaled`] by 1/`n`).
pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom {
self.levels_scaled(kind, 1.0 / f64::from(n.max(1)))
}
pub fn angle_deg(&self) -> f64 {
let v = self.end - self.start;
(-v.y).atan2(v.x).to_degrees()
@@ -1148,12 +1321,13 @@ impl GradientPaint {
inks: bool,
) -> impl Iterator<Item = [u8; N]> + use<N> {
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
let spread = self.gradient.spreader();
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
let (x0, y0) = (area.x0, area.y0);
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
let c = ramp.at(geom.param_at(kind, p) as f32);
let c = ramp.at(spread(geom.param_at(kind, p)) as f32);
std::array::from_fn(|k| {
if k + 1 == N {
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
+374
View File
@@ -0,0 +1,374 @@
//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad
//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as
//! the painted area needs, and the vector stretched over those runs.
use kurbo::{Point, Rect, Vec2};
use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop};
use crate::Color;
/// Most runs of the stops [`Gradient::padded_over`] writes.
pub const MAX_SPREAD_RUNS: usize = 256;
/// Most stops [`Gradient::padded_over`] writes, all runs together.
pub const MAX_SPREAD_STOPS: usize = 16384;
/// The farthest level from its center a radial or diamond gradient's runs are written out to by
/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart),
/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]).
pub const MAX_SPREAD_LEVEL: f64 = 65536.0;
/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as
/// different: sixteen times single precision's step just below 1.
const MIN_OFFSET_GAP: f64 = 1e-6;
/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]).
#[derive(Clone, Debug, PartialEq)]
pub struct Padded {
/// The gradient with its stops repeated, padding past its ends.
pub gradient: Gradient,
/// Where those runs lie.
pub geom: GradientGeom,
/// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the
/// first run's level over the last one's outer level for a radial or diamond one.
pub first: f64,
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
pub runs: usize,
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed,
/// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
pub capped: bool,
}
impl Gradient {
/// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a
/// gradient that pads and paints `area` the same way: its stops repeated, each run's
/// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or
/// diamond from its first level, 0, the first stop's color inside the area's innermost run).
/// `None` for a gradient that pads, a conic or
/// freeform one, one without stops, and a placement whose levels at the corners are not
/// finite.
pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option<Padded> {
self.padded_within(geom, area, MAX_SPREAD_STOPS)
}
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs
/// written need more stops than that, each run leaves out the stops that change its colors
/// least ([`fit_run`]), so every run is still written.
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
let kind = self.kind;
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
return None;
}
let period = geom.period(kind, self.repeat_count());
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
let ts = corners.map(|p| period.param_at(kind, p));
if ts.iter().any(|t| !t.is_finite()) {
return None;
}
let centered = kind.is_centered();
// The level's range over the area. A linear gradient's extremes lie at corners. Radial and
// diamond levels are nested convex rings from level 0: the largest at a corner, the
// smallest 0 when the area holds the rings' center, else on its edge.
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
let budget = max_stops.min(MAX_SPREAD_STOPS);
let most = MAX_SPREAD_RUNS.min(budget / 2).max(1);
let capped = hi - lo > most as f64;
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
// those around the vector's start where the area reaches it, else the area's runs nearest
// to it.
let lo = match capped {
true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64),
_ => lo,
};
let n = (hi - lo).min(most as f64).max(1.0);
let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method);
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
// (single-precision fractions of the outermost level) tell apart only so far out, the
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min);
// A whole level, so the runs keep their places (and Reflect its mirrored ones).
let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n);
let far = centered && lo + n > farthest;
let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) };
// `lo` is a whole number, possibly past what an integer holds: its parity in floating point.
let first_odd = lo.rem_euclid(2.0) >= 1.0;
let (stops, geom) = if centered {
// The levels from 0, the runs from level `lo` (the first stop's color inside it).
(self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n))
} else {
let u = period.end - period.start;
(
self.runs(&one, first_odd, 0.0, n as usize, n),
GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period },
)
};
let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() };
let first = if centered { lo / (lo + n) } else { 0.0 };
Some(Padded { gradient, geom, first, runs: n as usize, capped })
}
/// The gradient as it runs from the start of its vector (0) to its end (1), as one that
/// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`]
/// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that
/// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are.
pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> {
self.unrolled_within(MAX_SPREAD_STOPS)
}
/// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops
/// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with
/// fewer than two stops for each run do the runs past those that fit pad with the last one.
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if !self.is_spread() {
return Cow::Borrowed(self);
}
// Without stops there is nothing to repeat: it pads all the same.
if self.stops.is_empty() {
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
}
let n = self.repeat_count() as usize;
let budget = max_stops.min(MAX_SPREAD_STOPS);
let kept = n.min(budget / 2).max(1);
let one = fit_run(whole_run(&self.stops), budget / kept, self.method);
let stops = self.runs(&one, false, 0.0, kept, n as f64);
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
}
/// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two):
/// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that
/// pads with more stops than that without the stops that change its colors least
/// ([`fit_run`]). Others as they are.
pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if self.is_spread() {
return self.unrolled_within(max_stops);
}
if self.stops.len() <= max_stops.max(2) {
return Cow::Borrowed(self);
}
Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() })
}
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
/// one without stops.
pub fn cycle(&self) -> Option<(Gradient, u32)> {
if !self.is_spread() || self.stops.is_empty() {
return None;
}
let one = whole_run(&self.stops);
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
}
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
/// Reflect, the odd-numbered runs are mirrored).
fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec<GradientStop> {
let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one));
let mut stops = Vec::with_capacity(one.len() * n);
for j in 0..n {
let run = match &mirrored_run {
Some(m) if (j % 2 == 1) != first_odd => m.as_slice(),
_ => one,
};
stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() }));
}
stops
}
}
/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding):
/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the
/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather
/// than from samples along them, so a long side does not hide a run near it. 0 for a placement
/// without a frame.
fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 {
let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start };
if area.contains(center) {
return 0.0;
}
let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() };
let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 };
let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2());
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]
.map(|p| (to_unit * p).to_vec2());
let mut least = f64::INFINITY;
for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) {
let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) };
least = least.min(side);
}
if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 }
}
/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the
/// level is linear between the points where the segment crosses an axis, so the smallest is at
/// an end or at one of those crossings.
fn diamond_least(a: Vec2, b: Vec2) -> f64 {
let d = b - a;
let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)];
[Some(0.0), Some(1.0), crossings[0], crossings[1]]
.into_iter()
.flatten()
.filter(|u| (0.0..=1.0).contains(u))
.map(|u| {
let p = a + d * u;
p.x.abs() + p.y.abs()
})
.fold(f64::INFINITY, f64::min)
}
/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level.
const RADIAL_HALVINGS: usize = 1100;
/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter
/// level under it: the distance to the center for a centered radial. An off-center radial's level
/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance
/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the
/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the
/// extent ellipse.
fn radial_least(a: Vec2, b: Vec2, focal: Option<Vec2>) -> f64 {
let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) };
let reach = f.hypot();
if reach.is_nan() || reach >= 1.0 {
return 0.0;
}
let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t;
// At this level the circle reaches the segment's nearest point to the ellipse's center.
let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0);
let mut lo = 0.0;
if !hi.is_finite() || past(lo) {
return 0.0;
}
for _ in 0..RADIAL_HALVINGS {
let mid = lo + (hi - lo) / 2.0;
if hi - lo <= 0.25 || mid <= lo || mid >= hi {
break;
}
if past(mid) { hi = mid } else { lo = mid }
}
lo
}
/// How far `c` is from the segment from `a` to `b`.
fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 {
let d = b - a;
let along = (c - a).dot(d) / d.hypot2();
let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 };
(a + d * u - c).hypot()
}
/// The stops of one run, from offset 0 to 1: the end colors held out to the ends.
fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
let mut out = stops.to_vec();
if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() {
out.insert(0, GradientStop { offset: 0.0, ..first });
}
if let Some(last) = out.last_mut() {
// The last stop's midpoint leads nowhere; the copy at 1 takes over.
if last.offset < 1.0 {
let end = GradientStop { offset: 1.0, ..last.clone() };
out.push(end);
}
}
out
}
/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two):
/// as it is when it fits, else without the stops that change its colors least, left out one at a
/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still
/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or
/// process plates lie from the line between theirs (a whole unit when its swatch link or color
/// model differs from either of theirs, and a whole unit more when its midpoint or the one before
/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose
/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm.
fn fit_run(one: Vec<GradientStop>, budget: usize, method: GradientMethod) -> Vec<GradientStop> {
use std::cmp::Reverse;
use std::collections::BinaryHeap;
let budget = budget.max(2);
let n = one.len();
if n <= budget {
return one;
}
let mix = |x: &Color, y: &Color, v: f32| match method {
GradientMethod::Classic => x.lerp_keep_model(y, v),
m => m.mix(x, y, v),
};
let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 {
let span = b.offset - a.offset;
let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 };
// Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`.
let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb());
let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max);
let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs();
// Process inks, which colors that look alike can print differently: off their line, or a
// change of color model.
let process = match (&a.color, &s.color, &b.color) {
(Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => {
[(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max)
}
_ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0,
_ => 1.0,
};
let color = color.max(process);
// Separations: a change of swatch link, or of tint or process plates off their line.
let ink = if s.swatch != a.swatch || s.swatch != b.swatch {
1.0
} else {
let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs();
let plates = match (a.plates, s.plates, b.plates) {
(None, None, None) => 0.0,
(Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max),
_ => 1.0,
};
tint.max(plates)
};
// Leaving it out merges two spans, and an off-center midpoint shapes one of them.
let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 };
// Non-negative, so the bits order as the numbers do (NaN counts as 0).
(color.max(opacity).max(ink) + shaped).max(0.0).to_bits()
};
// The stops still kept on either side of each stop, and each stop's latest cost entry.
let mut prev: Vec<usize> = (0..n).map(|i| i.saturating_sub(1)).collect();
let mut next: Vec<usize> = (1..=n).collect();
let mut gone = vec![false; n];
let mut version = vec![0u32; n];
let mut heap: BinaryHeap<Reverse<(u32, usize, u32)>> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect();
let mut left = n;
while left > budget {
let Some(Reverse((_, i, v))) = heap.pop() else { break };
if gone[i] || v != version[i] {
continue;
}
gone[i] = true;
left -= 1;
let (a, b) = (prev[i], next[i]);
next[a] = b;
prev[b] = a;
for j in [a, b] {
if j != 0 && j != n - 1 {
version[j] += 1;
heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j])));
}
}
}
one.into_iter()
.enumerate()
.filter(|(i, _)| !gone[*i])
.map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } })
.collect()
}
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
g.reverse();
g.stops
}
#[cfg(test)]
mod tests;
+480
View File
@@ -0,0 +1,480 @@
use kurbo::Vec2;
use super::*;
use crate::gradient::{GradientPaint, MAX_REPEATS};
use crate::{Color, GradientMethod};
fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient {
Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) }
}
fn black_white() -> Vec<GradientStop> {
let mut a = GradientStop::new(0.0, Color::BLACK);
a.midpoint = 0.3;
vec![a, GradientStop::new(1.0, Color::WHITE)]
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect
/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has
/// no ends to spread past.
#[test]
fn spread_maps_the_parameter_to_a_place_along_the_stops() {
let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3);
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] {
assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t));
}
let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3);
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] {
assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t));
}
let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3);
assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2));
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
assert_eq!(free.spread_param(0.7), 0.7);
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
assert!(repeat.spread_param(f64::NAN).is_nan());
// A count out of range (set in code) counts as the nearest one in range.
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS);
}
/// The native format writes the spread and count only when they are not Pad and 1, reads a file
/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest
/// one it can hold.
#[test]
fn the_file_keeps_the_spread_and_reads_bad_values_leniently() {
let plain = serde_json::to_value(Gradient::default()).unwrap();
assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}");
let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4);
let v = serde_json::to_value(&g).unwrap();
assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4)));
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
let read = |spread: serde_json::Value, repeats: serde_json::Value| {
let mut v = serde_json::to_value(Gradient::default()).unwrap();
v["spread"] = spread;
v["repeats"] = repeats;
let g: Gradient = serde_json::from_value(v).unwrap();
(g.spread, g.repeats)
};
assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3));
assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1));
assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS));
assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1));
let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1));
}
/// One run's placement: a level of the period is the gradient's level times the count, for
/// linear, diamond and off-center radial gradients; a conic keeps its placement.
#[test]
fn a_period_holds_one_run_of_the_stops() {
let p = Point::new(72.0, 61.0);
let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None };
let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) };
let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial };
for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
let period = geom.period(kind, 4);
assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}");
assert_eq!(period.focal, geom.focal, "{kind:?}");
}
assert_eq!(radial.period(GradientKind::Conic, 4), radial);
assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1");
}
/// The stops repeated over the area: as many runs as its corners reach, each in place.
#[test]
fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap();
assert!(!p.capped);
// Runs of 10 from -10 to 30: four of them.
assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0)));
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]);
assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6));
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
// Every point gets the color the gradient gives it.
for x in [-4.0, 1.0, 7.5, 13.0, 24.0] {
let q = Point::new(x, 5.0);
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}");
}
}
#[test]
fn reflect_mirrors_every_other_run_and_its_midpoints() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
let colors: Vec<Color> = p.gradient.stops.iter().map(|s| s.color).collect();
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]);
// Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7.
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
}
#[test]
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)];
let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]);
}
/// An off-center radial grows about its focal point, a diamond about its center; every point
/// keeps its color.
#[test]
fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
let c = Point::new(50.0, 50.0);
let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) };
let diamond = GradientGeom { focal: None, ..radial };
for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap();
assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len());
assert_eq!(p.geom.focal, geom.focal);
for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] {
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}");
}
}
}
/// A run of the stops far too short for the area is written with at most so many runs, and pads
/// past them; a gradient of many stops is written with every run the area needs, each run
/// without the stops that change its colors least, within so many stops; a conic, a padding
/// gradient and one without stops have nothing to pad.
#[test]
fn far_repeats_are_capped_and_many_stops_are_sampled() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
assert!(p.capped);
assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS);
let many: Vec<GradientStop> = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect();
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len());
for x in [0.7, 33.3, 66.1, 99.5] {
let q = Point::new(x, 0.5);
let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
}
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) };
assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
}
/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs
/// from the area writes the hundred it crosses, not the first 256 from the center; a linear
/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it.
/// Every point checked gets the color the gradient gives it.
#[test]
fn the_runs_written_cover_a_distant_area() {
let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None };
let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None };
for (kind, geom, area) in [
(GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
(GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
(GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)),
] {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
let p = g.padded_over(&geom, area).unwrap();
assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}");
assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS);
for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] {
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
}
}
}
/// A tiny radial centered just outside the area, beside a side between any evenly spaced
/// samples of it: the runs written start from the area's true innermost level.
#[test]
fn the_innermost_level_is_found_between_samples() {
let c = Point::new(-0.0005, 7.8125);
let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap();
for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] {
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}");
}
}
/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's
/// center: the runs written start from that side's true innermost level, so the runs beside it
/// keep their colors.
#[test]
fn the_innermost_level_is_found_along_a_very_long_side() {
let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0);
for x in [0.3, 12345.678, -7777.25, 98765.4321] {
let c = Point::new(x, -0.00005);
let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run };
for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
let p = g.padded_over(&geom, area).unwrap();
assert!(p.capped, "{kind:?}");
for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] {
let level = geom.param_at(kind, q);
assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}");
let want = g.sample(g.spread_param(level) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
}
}
}
}
/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart:
/// the gradient is written capped, its stops still apart and in order.
#[test]
fn runs_too_far_from_the_center_are_capped() {
let c = Point::new(0.0, 0.0);
let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap();
assert!(p.capped);
assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order");
let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count();
assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len());
}
/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around
/// level 50,000 it is capped, every stop written apart from the next.
#[test]
fn close_stops_are_written_only_where_they_stay_apart() {
let many: Vec<GradientStop> = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect();
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) };
let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap();
assert!(p.capped);
// Only where one run meets the next do two stops share an offset.
let runs = p.gradient.stops.len() / 1001;
let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count();
assert!(shared < runs, "{shared} stops share an offset in {runs} runs");
// Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within
// it gets the gradient's colors, Reflect's mirrored runs included.
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)];
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) };
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap();
assert!(p.capped, "past level 123 it pads");
for x in [121.3, 121.9, 122.5] {
let q = Point::new(x, 0.1);
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
}
}
/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a
/// corner there) starts with the new run's first color, not the old run's last.
#[test]
fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() {
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) };
let piece = g.unrolled().span(0.5, 1.0);
assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops);
assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK));
let before = g.unrolled().span(0.0, 0.5);
assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK));
}
/// An area very far past a very short reflecting vector (a file's numbers) is padded without the
/// run count overflowing.
#[test]
fn a_far_area_pads_without_overflowing() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0));
assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS));
// Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds.
let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom };
let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap();
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom);
}
/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with
/// Reflect); one cycle is a run, or a run and its mirror.
#[test]
fn unrolled_and_cycle_stops() {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) };
let u = g.unrolled();
let offsets: Vec<f32> = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect();
assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]);
let colors: Vec<Color> = u.stops.iter().map(|s| s.color).collect();
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]);
for t in [0.05, 0.4, 0.71, 0.99] {
let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb());
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}");
}
let (cycle, runs) = g.cycle().unwrap();
assert_eq!((runs, cycle.stops.len()), (2, 4));
let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() };
assert_eq!(repeat.cycle().unwrap().1, 1);
assert!(Gradient::default().cycle().is_none());
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
}
/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run
/// when unrolled, each run without the stops that change its colors least: its last run ends on
/// its last color instead of the rest padding with it.
#[test]
fn unrolled_many_stops_keep_every_run() {
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) };
let u = g.unrolled();
assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len());
for t in [0.005, 0.5051, 0.9149, 0.9951] {
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
let got = u.sample(t as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}");
}
// A padding gradient fitted to fewer stops keeps its ends.
let pad = Gradient::new(GradientKind::Linear, g.stops.clone());
let fitted = pad.fitted(16);
assert_eq!(fitted.stops.len(), 16);
for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] {
assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color);
}
assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_)));
}
/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1)
/// is written within the limit, every run the area needs included.
#[test]
fn a_run_over_the_stop_limit_is_written_within_it() {
let stops: Vec<GradientStop> = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) };
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap();
assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len());
assert!(g.unrolled_within(256).stops.len() <= 256);
}
/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a
/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose
/// them.
#[test]
fn fitting_keeps_sharp_steps_and_swatch_links() {
let mut stops: Vec<GradientStop> = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect();
let red = Color::rgb(1.0, 0.0, 0.0);
// A band of red from 0.5003 to 0.5013, with a sharp step at each side.
for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] {
let gray = Color::gray(offset);
stops.push(GradientStop::new(offset, color.unwrap_or(gray)));
}
let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) };
stops.push(spot.clone());
// Three stops of one ink that look alike but print at different tints.
for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] {
stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) });
}
// A span shaped by an off-center midpoint.
if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) {
s.midpoint = 0.13;
}
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let g = Gradient::new(GradientKind::Linear, stops);
let fitted = g.fitted(32);
assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len());
let red_at = |t: f32| fitted.sample(t).0.to_rgb();
assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays");
assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow");
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops);
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays");
assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays");
// Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the
// first stays. (The stop before an ink starts stays as well: leaving it out would blend the
// ink in sooner.)
let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) };
let few = vec![
GradientStop::new(0.0, Color::gray(0.0)),
GradientStop::new(0.2, Color::gray(0.17)),
GradientStop::new(0.3, Color::gray(0.3)),
ink(0.4, 0.2),
ink(0.5, 0.9),
ink(0.6, 0.2),
GradientStop::new(1.0, Color::gray(1.0)),
];
let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]);
// A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line
// gives.
let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5));
let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5);
let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)];
let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) };
let fitted = perceptual.fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
// A black of other inks between blacks that look the same prints differently: it stays.
let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 });
let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 });
let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)];
let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() };
let u = spread.unrolled_within(128);
assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run");
}
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
/// PDF write as images) repeat with the stops, for each kind.
#[test]
fn pixels_repeat_and_reflect_for_every_kind() {
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
let c = Point::new(20.0, 20.0);
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
for sp in [GradientSpread::Repeat, GradientSpread::Reflect] {
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) });
let geom = if kind == GradientKind::Linear {
GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None }
} else {
GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None }
};
g.geom = Some(geom);
let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect();
for (i, got) in px.iter().enumerate().step_by(37) {
let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5);
let t = g.gradient.spread_param(geom.param_at(kind, p));
// Not where Repeat jumps from the last stop back to the first.
if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) {
continue;
}
let want = g.gradient.sample(t as f32).0.to_rgba8(1.0);
assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}");
}
}
}
}
}
/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most
/// so many.
#[test]
fn conic_wedges_count_each_run() {
let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4);
assert_eq!(g.conic_wedge_count(360), 1440);
assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360);
assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES);
}
+1 -1
View File
@@ -16,7 +16,7 @@ pub mod swatch;
pub use blend::BlendMode;
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop};
pub use libraries::SwatchLibrary;
pub use swatch::{Swatch, SwatchGroup, default_swatches};
+3 -1
View File
@@ -196,8 +196,10 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
let at = if mirrored { 1.0 - s.offset } else { s.offset };
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
};
// Stops that repeat or reflect run that many times across the box.
let unrolled = g.gradient.unrolled();
let stops: Vec<String> =
if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+23
View File
@@ -261,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() {
}
}
/// A gradient swatch that repeats or reflects has its stops written that many times across the
/// box, every other run backwards for Reflect.
#[test]
fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
for (spread, want) in [
(crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"),
(crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"),
] {
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch {
name: "Bands".into(),
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))),
global: false,
spot: false,
}],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}");
}
}
#[test]
fn holds_counts_the_swatches_each_format_writes() {
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
+1 -1
View File
@@ -10,7 +10,7 @@ mod stroke_style;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign};
/// One entry of the appearance stack.
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
+4 -2
View File
@@ -193,8 +193,10 @@ impl StrokeLayer {
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
let head = if end { &self.end_arrow } else { &self.start_arrow };
// A custom head can paint in front of its tip, which Extend puts past the end point.
let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() };
head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+7
View File
@@ -202,6 +202,13 @@ impl AngleProfile {
if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 }
}
/// The angle at `t` (0..1) as [`Self::at`] reads it, but in the samples' own running degrees,
/// so the whole turns the curve makes along the stroke are kept; 0 without any samples.
pub fn unwrapped_at(&self, t: f64) -> f64 {
let v = interpolated(&self.points, t).unwrap_or(0.0);
if v.is_finite() { v } else { 0.0 }
}
/// A profile from (position, degrees) samples in order along the stroke: non-finite ones are
/// dropped, each sample is joined to the one before it the shorter way round, and the curve is
/// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
+98 -5
View File
@@ -1,3 +1,7 @@
use std::sync::Arc;
use vectorcraft_geom::{PathData, Rect};
use super::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -53,8 +57,74 @@ impl Dash {
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a
/// document that uses it draws it wherever it opens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(from = "CustomArrowheadData")]
pub struct CustomArrowhead {
/// The name the arrowhead menus show (the symbol's name in the arrowheads file).
pub name: String,
/// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
/// as the built-in heads are, and a unit is the head's weight.
pub path: PathData,
}
#[derive(Deserialize)]
struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
}
impl From<CustomArrowheadData> for CustomArrowhead {
fn from(d: CustomArrowheadData) -> Self {
CustomArrowhead::new(d.name, d.path)
}
}
impl CustomArrowhead {
/// The most anchors a custom head's outline may have, and the most subpaths.
pub const MAX_ANCHORS: usize = 4096;
/// How far from the tip a custom head's outline may reach, in head units.
pub const MAX_UNITS: f64 = 64.0;
/// Head `name` with outline `path` (in head units). An outline with more than
/// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
pub fn new(name: String, path: PathData) -> Self {
let path = if Self::fits(&path) { path } else { PathData::default() };
CustomArrowhead { name, path }
}
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
/// finite points within [`Self::MAX_UNITS`] only.
pub fn fits(path: &PathData) -> bool {
let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS;
anchors <= Self::MAX_ANCHORS
&& path.subpaths.len() <= Self::MAX_ANCHORS
&& path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out))
}
fn bounds(&self) -> Option<Rect> {
self.path.control_bounds()
}
/// How far any part of the head can be from its tip, in head units.
pub fn reach(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1)))
}
/// How far the head spreads either side of its line, in head units.
pub fn half_width(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
}
/// Where the stroke ends under the head, in head units back from the tip: halfway along the
/// head's length.
pub fn stop(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
}
}
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Arrowhead {
Triangle,
TriangleOpen,
@@ -102,6 +172,8 @@ pub enum Arrowhead {
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
/// A head the user drew, with its art.
Custom(Arc<CustomArrowhead>),
}
impl Arrowhead {
@@ -151,23 +223,43 @@ impl Arrowhead {
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
pub fn reach(&self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
Arrowhead::Custom(c) => c.reach(),
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
pub fn half_width(&self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
Arrowhead::Custom(c) => c.half_width(),
_ => 2.0,
}
}
/// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of
/// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits
/// [`CustomArrowhead::stop`] past the end point.
pub fn length(&self) -> f64 {
match self {
Arrowhead::Custom(c) => c.stop() + c.reach(),
_ => 4.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
/// The name the arrowhead menus show: [`Self::label`], or a custom head's own name.
pub fn name(&self) -> &str {
match self {
Arrowhead::Custom(c) => &c.name,
_ => self.label(),
}
}
/// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose
/// own name is [`Self::name`]).
pub fn label(&self) -> &'static str {
match self {
Arrowhead::Triangle => "Triangle",
Arrowhead::TriangleOpen => "Triangle (open)",
@@ -210,6 +302,7 @@ impl Arrowhead {
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
Arrowhead::Custom(_) => "Custom",
}
}
}
+53 -1
View File
@@ -337,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
assert_eq!(serde_json::to_value(a).unwrap(), name);
assert_eq!(serde_json::to_value(&a).unwrap(), name);
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
}
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
}
/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line.
fn custom_head() -> Arrowhead {
use vectorcraft_geom::{PathData, Point, SubPath};
let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path)))
}
#[test]
fn custom_arrowheads_carry_their_art_and_measure_it() {
let head = custom_head();
assert_eq!((head.name(), head.label()), ("Wedge", "Custom"));
assert_eq!(head.reach(), 3.0f64.hypot(2.0));
assert_eq!(head.half_width(), 2.0);
let Arrowhead::Custom(c) = &head else { panic!("custom") };
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
// Saved with the stroke, art and all, beside the built-in heads' names.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
let json = serde_json::to_value(&st).unwrap();
assert_eq!(json["start_arrow"], "Triangle");
assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge");
let back: StrokeLayer = serde_json::from_value(json).unwrap();
assert_eq!(back, st);
// Extended, the tip sits the stop past the end point; on it, only the reach counts.
assert_eq!(head.length(), 1.5 + head.reach());
assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0);
st.arrow_align = ArrowAlign::Tip;
assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0);
}
#[test]
fn custom_arrowheads_out_of_bounds_draw_nothing() {
let Arrowhead::Custom(c) = custom_head() else { panic!("custom") };
let mut path = c.path.clone();
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
// A file can hold what `new` drops: reading it drops it too.
let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1];
let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true)));
assert!(many.path.subpaths.is_empty(), "too many anchors");
// Empty subpaths add no anchors, and still count.
let mut hollow = c.path.clone();
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
}
#[test]
fn arrow_align_defaults_to_extend_and_round_trips() {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
+484 -17
View File
@@ -5,7 +5,8 @@
//! winding and to the start points that keep them from twisting, or to the anchors the Blend
//! tool clicked.
//! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ),
//! opacity, stroke weight, dashes, miter limit and width profiles interpolate; what can't
//! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt,
//! bearing and rotation that brushes read interpolate; what can't
//! (caps, joins, brushes, fonts, symbols, text content) switches halfway.
//! - **Groups** pair their children in stacking order; the children one group has more of grow
//! out of the other group's centre. Compound paths stay compound paths.
@@ -22,7 +23,7 @@ use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::text::TextObject;
@@ -152,6 +153,11 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
}
})
.collect();
// Two gradients that repeat (or reflect) step their count from one to the other; a spread
// that differs switches halfway, as the method does.
if a.gradient.is_spread() && a.gradient.spread == b.gradient.spread {
out.gradient.repeats = lerp_f32(a.gradient.repeat_count() as f32, b.gradient.repeat_count() as f32, t).round() as u32;
}
out.angle = a.angle + (b.angle - a.angle) * t as f64;
out.swatch = None;
if let (Some(ga), Some(gb)) = (a.geom, b.geom) {
@@ -230,7 +236,8 @@ fn lcm(a: usize, b: usize) -> usize {
a.checked_div(x).map_or(0, |q| q * b)
}
/// Interpolate width profiles (none is uniform) at every position either has a width point.
/// Interpolate width profiles (none is uniform) at every position either has a width point,
/// keeping their discontinuous points (a position where either steps gives two points).
fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> Option<WidthProfile> {
if x.is_none() && y.is_none() {
return None;
@@ -239,20 +246,135 @@ fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> O
let (x, y) = (x.unwrap_or(&uniform), y.unwrap_or(&uniform));
let mut at: Vec<f64> = x.points.iter().chain(&y.points).map(|p| p.0).filter(|p| p.is_finite()).collect();
at.sort_by(f64::total_cmp);
at.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let points = at
.into_iter()
.map(|p| {
let ((l1, r1), (l2, r2)) = (x.at(p), y.at(p));
(p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t))
})
.collect();
// Within the distance `around` reads a discontinuous point at, so a point near one keeps it.
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-7);
// Each profile is a smooth curve through its own points: samples between the positions keep
// both curves' shapes where the other profile's points and steps change the tangents. Two
// profiles with points at the same positions need none (so a preset on both keys stays it).
let same_positions = x.points.len() == y.points.len() && x.points.iter().zip(&y.points).all(|(p, q)| (p.0 - q.0).abs() <= 1e-7);
let per_span = if same_positions { 1 } else { (4096 / at.len().max(1)).clamp(1, 8) };
let mut points = Vec::with_capacity(at.len() * per_span + 2);
let mix = |p: f64, (l1, r1): (f64, f64), (l2, r2): (f64, f64)| (p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t));
for (k, &p) in at.iter().enumerate() {
let ((xb, xa), (yb, ya)) = (x.around(p), y.around(p));
points.push(mix(p, xb, yb));
// A discontinuous point ends the curve on each side even where both widths match.
if steps_at(x, p) || steps_at(y, p) {
points.push(mix(p, xa, ya));
}
if let Some(&q) = at.get(k + 1) {
for j in 1..per_span {
let f = p + (q - p) * j as f64 / per_span as f64;
points.push(mix(f, x.at(f), y.at(f)));
}
}
}
Some(WidthProfile { points })
}
/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale and width
/// profile into `o` (a copy of the nearer stroke, so caps, joins, alignment, arrowheads and
/// brushes switch halfway).
/// Whether width profile `w` has a discontinuous point at `p` (two points there, within `1e-7`,
/// as [`WidthProfile::around`] reads them).
fn steps_at(w: &WidthProfile, p: f64) -> bool {
let i = w.points.partition_point(|q| q.0 < p - 1e-7);
w.points.get(i..).unwrap_or_default().iter().take_while(|q| q.0 <= p + 1e-7).count() > 1
}
/// The positions along the stroke where either of two pen recordings has a sample, in order.
fn sample_positions(x: Option<&[(f64, f64)]>, y: Option<&[(f64, f64)]>) -> Vec<f64> {
let mut at: Vec<f64> = x.unwrap_or_default().iter().chain(y.unwrap_or_default()).map(|p| p.0).filter(|p| p.is_finite()).collect();
at.sort_by(f64::total_cmp);
// Within the distance `step_after` reads a step at, so a sample near a step keeps the step.
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
if at.is_empty() {
at = vec![0.0, 1.0];
}
at
}
/// The value pen recording `p` steps to at position `f`, where two or more of its samples share
/// that position (reading at `f` gives the first of them); None where it doesn't step.
fn step_after(p: Option<&[(f64, f64)]>, f: f64) -> Option<f64> {
let p = p?;
let i = p.partition_point(|q| q.0 < f - 1e-9);
let j = p.partition_point(|q| q.0 <= f + 1e-9).checked_sub(1)?;
(j > i && (p.get(i)?.0 - f).abs() <= 1e-9).then(|| p.get(j).map(|q| q.1)).flatten()
}
/// Two pen recordings read at every position either has a sample, as (position, x's value, y's
/// value): `read_x` and `read_y` read them, and `clean` makes a stepped sample's value one they
/// would read. A position where either steps gives two, before and after the step.
fn paired_samples(
x: Option<&[(f64, f64)]>,
y: Option<&[(f64, f64)]>,
read_x: impl Fn(f64) -> f64,
read_y: impl Fn(f64) -> f64,
clean: impl Fn(f64) -> f64,
) -> Vec<(f64, f64, f64)> {
let mut out = Vec::new();
for f in sample_positions(x, y) {
let (a, b) = (read_x(f), read_y(f));
out.push((f, a, b));
let (sa, sb) = (step_after(x, f), step_after(y, f));
if sa.is_some() || sb.is_some() {
out.push((f, sa.map_or(a, &clean), sb.map_or(b, &clean)));
}
}
out
}
/// Interpolate pen pressure or tilt recordings at every position either has a sample, keeping
/// their steps. A stroke without one reads as [`PressureProfile::MID`], as brushes read it; None
/// when neither has one.
fn lerp_pressure(x: Option<&PressureProfile>, y: Option<&PressureProfile>, t: f64) -> Option<PressureProfile> {
if x.is_none() && y.is_none() {
return None;
}
let read = |p: Option<&PressureProfile>, f: f64| p.map_or(PressureProfile::MID, |p| p.at(f));
let clean = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { PressureProfile::MID };
let samples = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean);
PressureProfile::from_samples(samples.into_iter().map(|(f, a, b)| (f, lerp_f64(a, b, t))))
}
/// Interpolate pen angle recordings (bearing or barrel rotation) at every position either has a
/// sample: the steps turn from one key's angle to the other's the shorter way round at the
/// stroke's start, and keep the whole turns each recording makes along the stroke. A stroke
/// without one reads as 0°, as brushes read it; None when neither has one.
fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Option<AngleProfile> {
if x.is_none() && y.is_none() {
return None;
}
let read = |p: Option<&AngleProfile>, f: f64| p.map_or(0.0, |p| p.unwrapped_at(f));
let clean = |v: f64| if v.is_finite() { v } else { 0.0 };
let pairs = paired_samples(x.map(|p| p.points.as_slice()), y.map(|p| p.points.as_slice()), |f| read(x, f), |f| read(y, f), clean);
// Whole turns that bring the two angles within half a turn of each other at the first position.
let d0 = pairs.first().map_or(0.0, |&(_, a, b)| b - a);
let turns = vectorcraft_geom::normalize_deg(d0) - d0;
let value = |a: f64, b: f64| a + (b - a + turns) * t;
// Both curves are straight between two positions; samples are added where the steps turn
// through 90° or more between them, since `AngleProfile::from_samples` joins neighbours the
// shorter way round. A document's recordings can be long, so the added samples are limited.
let mut budget = 4 * PressureProfile::MAX_POINTS;
let mut samples = Vec::with_capacity(pairs.len());
let mut prev: Option<(f64, f64)> = None;
for (f, a, b) in pairs {
let v = value(a, b);
if let Some((pf, pv)) = prev.filter(|p| f - p.0 > 1e-9) {
let parts = ((v - pv).abs() / 90.0).ceil().min((budget + 1) as f64) as usize;
for k in 1..parts {
let g = pf + (f - pf) * k as f64 / parts as f64;
samples.push((g, value(read(x, g), read(y, g))));
}
budget -= parts.saturating_sub(1).min(budget);
}
samples.push((f, v));
prev = Some((f, v));
}
AngleProfile::from_samples(samples)
}
/// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width
/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of
/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway).
fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
let tf = t as f32;
o.paint = lerp_paint(&x.paint, &y.paint, tf);
@@ -262,6 +384,10 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) {
o.dash = lerp_dash(x.dash.as_ref(), y.dash.as_ref(), t);
o.arrow_scale = (lerp_f64(x.arrow_scale.0, y.arrow_scale.0, t), lerp_f64(x.arrow_scale.1, y.arrow_scale.1, t));
o.profile = lerp_profile(x.profile.as_ref(), y.profile.as_ref(), t);
o.pressure = lerp_pressure(x.pressure.as_ref(), y.pressure.as_ref(), t);
o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t);
o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t);
o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t);
}
/// Interpolate appearance stacks: item by item when their structure matches, else the top fill
@@ -385,6 +511,161 @@ fn reverse_closed(sp: &mut SubPath) {
sp.anchors.rotate_right(1);
}
/// How a key's subpaths were turned for its blend, so that its stroke's profiles, pen
/// recordings and arrowheads turn with it: position `u` along the turned subpath is position
/// `start + u` (`start - u` when `reversed`) along the key's own, wrapping round a closed one.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Orient {
start: f64,
reversed: bool,
closed: bool,
}
impl Orient {
fn of(sp: &SubPath) -> Self {
Self { closed: sp.closed, ..Self::default() }
}
/// The subpath now starts at the fraction `f` of its length.
fn rotate(&mut self, f: f64) {
self.start += if self.reversed { -f } else { f };
}
/// The subpath now runs the other way.
fn reverse(&mut self) {
self.start += if self.reversed { -1.0 } else { 1.0 };
self.reversed = !self.reversed;
}
/// As [`start_at`] turns `sp` (call it before).
fn start_at(&mut self, sp: &SubPath, i: usize) {
let n = sp.anchors.len();
if i >= n {
return;
}
if sp.closed {
self.rotate(arc_fraction(sp, i));
} else if i + 1 == n && n > 1 {
self.reverse();
}
}
/// Where a closed subpath now starts, as a fraction of its length; 0 for an open one.
fn seam(&self) -> f64 {
let s = if self.closed { self.start.rem_euclid(1.0) } else { 0.0 };
if s > 1e-9 && s < 1.0 - 1e-9 { s } else { 0.0 }
}
fn is_identity(&self) -> bool {
!self.reversed && self.seam() == 0.0
}
/// Whether two subpaths were turned alike, so one stroke along both turns the same way.
fn same_turn(&self, o: &Self) -> bool {
self.reversed == o.reversed && (self.seam() - o.seam()).abs() < 1e-9
}
}
/// How far along `sp` its anchor `i` sits, as a fraction of its length.
fn arc_fraction(sp: &SubPath, i: usize) -> f64 {
let pos = sp.anchor_arc_positions();
match (pos.get(i), pos.last()) {
(Some(&at), Some(&total)) if total.is_finite() && total > 1e-12 => (at / total).clamp(0.0, 1.0),
_ => 0.0,
}
}
/// Samples (position, value) along a key's subpath, read along the subpath turned as `o` says.
/// A closed subpath starting elsewhere starts the samples there too: the ones before it move
/// past the seam (`wrap` applied), which keeps any step the seam makes, and a value between
/// samples is read with `at`. A reversed subpath then reads them backwards (`flip` applied).
fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wrap: impl Fn(V) -> V, flip: impl Fn(V) -> V) -> Vec<(f64, V)> {
let s = o.seam();
let mut out = points.to_vec();
if s > 0.0
&& let (Some(&(_, first)), Some(&(_, last))) = (points.first(), points.last())
{
let i = points.partition_point(|q| q.0 < s - 1e-9);
let j = points.partition_point(|q| q.0 <= s + 1e-9).max(i);
let (before, after) = match points.get(i..j) {
Some([p, .., q]) => (p.1, q.1),
Some([p]) => (p.1, p.1),
_ => (at(s), at(s)),
};
out = Vec::with_capacity(points.len() + 4);
out.push((0.0, after));
out.extend(points.get(j..).unwrap_or_default().iter().map(|&(t, v)| (t - s, v)));
out.push((1.0 - s, last));
out.push((1.0 - s, wrap(first)));
out.extend(points.get(..i).unwrap_or_default().iter().map(|&(t, v)| (t + 1.0 - s, wrap(v))));
out.push((1.0, wrap(before)));
}
if o.reversed {
out = out.into_iter().rev().map(|(t, v)| (1.0 - t, flip(v))).collect();
}
out
}
/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap
/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its
/// arrowheads.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
if o.is_identity() {
return;
}
let same = |v: f64| v;
if let Some(p) = &mut s.profile {
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
// A width profile is a smooth curve through its points: where the new start splits a span,
// samples of that span keep its curve once its ends become ends of the profile.
let seam = o.seam();
let i = p.points.partition_point(|q| q.0 < seam);
if seam > 0.0
&& let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.points.get(j)), p.points.get(i))
&& seam - a.0 > 1e-9
&& b.0 - seam > 1e-9
{
const SAMPLES: usize = 32;
let (a, b) = (a.0, b.0);
let extra: Vec<(f64, (f64, f64))> =
(1..SAMPLES).map(|k| a + (b - a) * k as f64 / SAMPLES as f64).filter(|f| (f - seam).abs() > 1e-9).map(|f| (f, p.at(f))).collect();
pts.splice(i..i, extra);
}
let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l));
p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect();
}
for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() {
let out = reoriented(&p.points, o, |f| p.at(f), same, same);
p.points = out;
}
for p in [&mut s.bearing, &mut s.rotation].into_iter().flatten() {
// The samples moved past the seam carry the whole turns the recording makes along the
// stroke, so the angle does not jump by them there.
let turns = match (p.points.first(), p.points.last()) {
(Some(a), Some(b)) if (b.1 - a.1).is_finite() => ((b.1 - a.1) / 360.0).round() * 360.0,
_ => 0.0,
};
let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same);
p.points = out;
}
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
}
}
/// `n` with every stroke read along its subpaths turned as `o` says.
fn reorient_strokes(n: &mut Node, o: Orient) {
if o.is_identity() {
return;
}
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
}
}
}
/// Anchor positions of a subpath relative to its box, scaled to unit size.
fn normalised(sp: &SubPath) -> Vec<Vec2> {
let pts = sp.anchors.iter().map(|a| a.p);
@@ -422,6 +703,8 @@ fn best_rotation(a: &SubPath, b: &SubPath) -> usize {
pub struct PathPair {
a: Vec<SubPath>,
b: Vec<SubPath>,
/// How each path's subpaths were turned, where all of them turned alike (else unturned).
orient: (Orient, Orient),
}
impl PathPair {
@@ -433,6 +716,7 @@ impl PathPair {
let cb = b.bounds().map(|r| r.center()).unwrap_or_default();
let degenerate = |like: &SubPath, c: Point| SubPath::new(vec![Anchor::corner(c); like.anchors.len().max(1)], like.closed);
let (mut va, mut vb) = (Vec::with_capacity(n), Vec::with_capacity(n));
let mut orient = (Orient::default(), Orient::default());
for i in 0..n {
let (mut sa, mut sb) = match (a.subpaths.get(i), b.subpaths.get(i)) {
(Some(x), Some(y)) => (x.clone(), y.clone()),
@@ -440,17 +724,21 @@ impl PathPair {
(None, Some(y)) => (degenerate(y, ca), y.clone()),
(None, None) => continue,
};
let (mut oa, mut ob) = (Orient::of(&sa), Orient::of(&sb));
let explicit = i == 0 && (starts.0.is_some() || starts.1.is_some());
if explicit {
if let Some(s) = starts.0 {
oa.start_at(&sa, s);
start_at(&mut sa, s);
}
if let Some(s) = starts.1 {
ob.start_at(&sb, s);
start_at(&mut sb, s);
}
}
let closed = sa.closed && sb.closed && sa.anchors.len() > 2 && sb.anchors.len() > 2;
if closed && (sa.area() * sb.area()) < 0.0 {
ob.reverse();
reverse_closed(&mut sb);
}
let m = sa.anchors.len().max(sb.anchors.len());
@@ -458,12 +746,26 @@ impl PathPair {
grow(&mut sb, m);
if closed && !explicit {
let r = best_rotation(&sa, &sb);
if r != 0 {
ob.rotate(arc_fraction(&sb, r));
}
sb.anchors.rotate_left(r);
}
// One stroke runs along every subpath of a key, each reading it by its own length, so
// it turns only when all of the key's subpaths turned alike.
if i == 0 {
orient = (oa, ob);
}
if i < a.subpaths.len() && !orient.0.same_turn(&oa) {
orient.0 = Orient::default();
}
if i < b.subpaths.len() && !orient.1.same_turn(&ob) {
orient.1 = Orient::default();
}
va.push(sa);
vb.push(sb);
}
Self { a: va, b: vb }
Self { a: va, b: vb, orient }
}
/// The path at `t` (0 = `a`, 1 = `b`).
@@ -578,7 +880,12 @@ impl Lerp {
_ => Shape::Other,
},
};
Self { a: a.clone(), b: b.clone(), shape }
let (mut a, mut b) = (a.clone(), b.clone());
if let Shape::Path { pair, .. } = &shape {
reorient_strokes(&mut a, pair.orient.0);
reorient_strokes(&mut b, pair.orient.1);
}
Self { a, b, shape }
}
/// The object at `t` (0 = `a`, 1 = `b`), with id 0.
@@ -1480,7 +1787,7 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
// Even position of the step, then where the easing puts its shape and its colours.
let u = j as f64 / (n + 1) as f64;
// Easing needs a spine: a blend made without one keeps its steps evenly spaced.
let eased = rail.is_some() && !spec.no_spine;
let eased = rail.is_some() && spec.eases_along_spine();
let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u));
let mut s = lerp.at_eased(t, tc);
if let Some(r) = &rail {
@@ -1495,6 +1802,7 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
#[cfg(test)]
mod tests {
use super::*;
use crate::appearance::Arrowhead;
use vectorcraft_geom::{Rect, shapes};
#[test]
@@ -1656,6 +1964,25 @@ mod tests {
assert!(pair.at(0.5).bounds().unwrap().height() < 1e-6, "the clicked anchors pair up");
}
/// A blend between two gradients that repeat steps the count; one between a gradient that
/// pads and one that repeats switches halfway, as the method does.
#[test]
fn blend_between_repeating_gradients_steps_the_count() {
use vectorcraft_color::GradientSpread;
let spread = |spread, repeats| Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats, ..Gradient::default() })));
let at = |a: &Paint, b: &Paint, t: f32| match lerp_paint(a, b, t) {
Paint::Gradient(g) => (g.gradient.spread, g.gradient.repeat_count()),
p => panic!("a gradient, not {p:?}"),
};
let (two, twenty) = (spread(GradientSpread::Repeat, 2), spread(GradientSpread::Repeat, 20));
assert_eq!(at(&two, &twenty, 0.25), (GradientSpread::Repeat, 7));
assert_eq!(at(&two, &twenty, 0.5), (GradientSpread::Repeat, 11));
assert_eq!(at(&two, &twenty, 1.0), (GradientSpread::Repeat, 20));
let pad = spread(GradientSpread::Pad, 1);
assert_eq!(at(&pad, &twenty, 0.25), (GradientSpread::Pad, 1));
assert_eq!(at(&pad, &twenty, 0.75), (GradientSpread::Repeat, 20));
}
#[test]
fn blend_between_tints_of_one_swatch_keeps_the_link() {
let tinted = |tint: f32| Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint), swatch: Some("Spot".into()), tint };
@@ -1731,6 +2058,146 @@ mod tests {
assert_eq!(p.at(0.5), (1.0, 1.0));
}
#[test]
fn pen_pressure_tilt_and_angles_interpolate_for_brushes() {
let stroked = |pressure: Option<f64>, tilt: Option<f64>, bearing: Option<f64>| {
let mut ap = Appearance::default();
ap.set_stroke(Paint::solid(Color::BLACK));
if let Some(s) = ap.stroke_mut() {
s.brush = Some("Pressure Round".into());
s.pressure = pressure.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] });
s.tilt = tilt.map(|p| PressureProfile { points: vec![(0.0, p), (1.0, p)] });
s.bearing = bearing.map(|a| AngleProfile { points: vec![(0.0, a), (1.0, a)] });
}
ap
};
let at = |ap: &Appearance, f: f64| {
let s = ap.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
let read = |p: Option<&PressureProfile>| p.map_or(PressureProfile::MID, |p| p.at(f));
(read(s.pressure.as_ref()), read(s.tilt.as_ref()), s.bearing.as_ref().map_or(0.0, |p| p.at(f)))
};
let (light, heavy) = (stroked(Some(0.0), Some(0.2), Some(170.0)), stroked(Some(1.0), Some(0.6), Some(-170.0)));
let (p, tilt, bearing) = at(&lerp_appearance(&light, &heavy, 0.25), 0.5);
assert!((p - 0.25).abs() < 1e-9 && (tilt - 0.3).abs() < 1e-9, "a quarter of the way: {p} {tilt}");
assert!((bearing - 175.0).abs() < 1e-9, "the angle turns the shorter way round, through 180°: {bearing}");
assert!((at(&lerp_appearance(&light, &heavy, 0.5), 0.5).2.abs() - 180.0).abs() < 1e-9);
// A stroke drawn without a recording reads as half pressure, half tilt and 0°.
let plain = stroked(None, None, None);
let (p, tilt, bearing) = at(&lerp_appearance(&heavy, &plain, 0.5), 0.0);
assert!((p - 0.75).abs() < 1e-9 && (tilt - 0.55).abs() < 1e-9 && (bearing + 85.0).abs() < 1e-9, "{p} {tilt} {bearing}");
// Profiles that vary along the stroke interpolate at each position.
let mut ramp = stroked(None, None, None);
if let Some(s) = ramp.stroke_mut() {
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
}
let mid = lerp_appearance(&ramp, &heavy, 0.5);
assert!((at(&mid, 0.0).0 - 0.5).abs() < 1e-9 && (at(&mid, 0.5).0 - 0.75).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure));
// A step in a recording (two samples at one position) stays a step.
let mut stepped = stroked(None, None, None);
if let Some(s) = stepped.stroke_mut() {
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] });
}
let mid = lerp_appearance(&stepped, &stepped, 0.5);
assert!(at(&mid, 0.25).0.abs() < 1e-9 && (at(&mid, 0.75).0 - 1.0).abs() < 1e-9, "{:?}", mid.stroke().map(|s| &s.pressure));
// A whole turn recorded along a stroke stays a whole turn in the steps.
let mut turning = stroked(None, None, None);
if let Some(s) = turning.stroke_mut() {
s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] });
}
let rot = |ap: &Appearance, f: f64| ap.stroke().and_then(|s| s.rotation.as_ref()).map_or(0.0, |p| p.at(f));
let same = lerp_appearance(&turning, &turning, 0.5);
assert!((rot(&same, 0.25) - 90.0).abs() < 1e-9 && (rot(&same, 0.5).abs() - 180.0).abs() < 1e-9, "{:?}", same.stroke().map(|s| &s.rotation));
let half = lerp_appearance(&turning, &plain, 0.5);
assert!((rot(&half, 0.5) - 90.0).abs() < 1e-9 && (rot(&half, 1.0).abs() - 180.0).abs() < 1e-9, "{:?}", half.stroke().map(|s| &s.rotation));
// Neither key has a recording: the steps have none either.
let none = lerp_appearance(&plain, &plain, 0.5);
let s = none.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
assert!(s.pressure.is_none() && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none());
}
#[test]
fn a_point_near_the_other_keys_step_keeps_the_step() {
let flat = PressureProfile { points: vec![(0.0, 0.0), (0.4999995, 0.0), (1.0, 0.0)] };
let stepped = PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] };
let p = lerp_pressure(Some(&flat), Some(&stepped), 1.0).unwrap_or_default();
assert!((p.at(0.75) - 1.0).abs() < 1e-9, "{p:?}");
let narrow = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.4999995, 1.0, 1.0), (1.0, 1.0, 1.0)] };
let stepped = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)] };
let w = lerp_profile(Some(&narrow), Some(&stepped), 1.0).unwrap_or_default();
assert!(w.at(0.75).0.abs() < 1e-9, "{w:?}");
// The other key's step doesn't reshape a smooth profile's curve.
let early = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.5, 0.5)] };
let w = lerp_profile(Some(&WidthProfile::lens()), Some(&early), 0.0).unwrap_or_default();
for u in [0.1, 0.125, 0.2, 0.3, 0.4] {
let (got, want) = (w.at(u).0, WidthProfile::lens().at(u).0);
assert!((got - want).abs() < 5e-3, "at {u}: {got} for {want}: {w:?}");
}
let lens = WidthProfile::lens();
assert_eq!(lerp_profile(Some(&lens), Some(&lens), 0.5).and_then(|p| p.preset_id()), Some("lens"));
}
#[test]
fn stroke_profiles_turn_with_a_key_path_started_elsewhere() {
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
let mut ap = Appearance::default();
ap.set_stroke(Paint::solid(Color::BLACK));
if let Some(s) = ap.stroke_mut() {
edit(s);
}
Node::path(NodeId(1), path, ap)
};
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
let pressure = |s: &StrokeLayer, f: f64| s.pressure.as_ref().map_or(PressureProfile::MID, |p| p.at(f));
// An open key clicked at its last anchor runs the other way, and so do its pressure, its
// width profile (whose sides swap) and its arrowheads.
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0)], false));
let light = keyed(line(0.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 0.0)] }));
let ramp = keyed(line(100.0), &|s| {
s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] });
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] });
s.start_arrow = Some(Arrowhead::Triangle);
s.arrow_scale = (200.0, 100.0);
});
let blend = Lerp::new(&light, &ramp, (None, Some(1)));
let s = stroke(&blend.at(0.25));
assert!(pressure(&s, 0.0).abs() < 1e-9 && (pressure(&s, 1.0) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
let s = stroke(&blend.at(1.0));
assert_eq!(s.profile.as_ref().map(|p| p.at(1.0)), Some((0.0, 1.0)), "{:?}", s.profile);
assert_eq!((s.start_arrow, s.end_arrow, s.arrow_scale), (None, Some(Arrowhead::Triangle), (100.0, 200.0)));
// A key whose other subpaths keep their direction keeps its one stroke as it is.
let two = |x: f64| {
let sub = |y: f64| SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y)], false);
PathData::new(vec![sub(0.0), sub(20.0)])
};
let ramps = keyed(two(100.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }));
let s = stroke(&Lerp::new(&keyed(two(0.0), &|_| {}), &ramps, (None, Some(1))).at(1.0));
assert!((pressure(&s, 0.0) - 1.0).abs() < 1e-9, "{:?}", s.pressure);
// A closed key started half way round starts its recordings there too, keeping the step
// where its own start was and the whole turn its rotation makes.
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
let plain = keyed(square(0.0), &|_| {});
let turning = keyed(square(100.0), &|s| {
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] });
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] });
});
let blend = Lerp::new(&plain, &turning, (Some(0), Some(2)));
let s = stroke(&blend.at(1.0));
assert!((pressure(&s, 0.25) - 0.75).abs() < 1e-9 && (pressure(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
let width = s.profile.as_ref().map_or((1.0, 1.0), |p| p.at(0.75));
assert!((width.0 - 0.75).abs() < 1e-6 && (width.1 - 0.75).abs() < 1e-6, "the width steps where the key started: {:?}", s.profile);
// A width curve split by the new start keeps its shape.
let lensed = keyed(square(100.0), &|s| s.profile = Some(WidthProfile::lens()));
let s = stroke(&Lerp::new(&plain, &lensed, (Some(0), Some(1))).at(1.0));
for u in [0.05, 0.125, 0.2, 0.6, 0.7, 0.74, 0.76, 0.8, 0.875, 0.95] {
let (got, want) = (s.profile.as_ref().map_or(1.0, |p| p.at(u).0), WidthProfile::lens().at((u + 0.25) % 1.0).0);
assert!((got - want).abs() < 2e-3, "at {u}: {got} for {want}: {:?}", s.profile);
}
let rot = |t: f64, f: f64| stroke(&blend.at(t)).rotation.as_ref().map_or(0.0, |p| p.unwrapped_at(f));
assert!((vectorcraft_geom::normalize_deg(rot(1.0, 0.25)) + 90.0).abs() < 1e-6, "{:?}", s.rotation);
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
}
#[test]
fn odd_dash_blends_to_solid_with_closed_gaps() {
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
+2 -2
View File
@@ -82,8 +82,8 @@ pub(crate) mod skip;
pub use appearance::StrokeGradientMode;
pub use appearance::{
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset,
SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, CustomArrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile,
ProfilePreset, SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
+6
View File
@@ -119,6 +119,12 @@ impl BlendSpec {
pub fn start(&self, i: usize) -> Option<usize> {
self.starts.get(i).copied().flatten().map(|a| a as usize)
}
/// Whether [`Self::ease`] moves the steps: the blend has a spine ([`Self::no_spine`] is off)
/// and a replaced spine or Align to Path, the cases where the steps are placed along it.
pub fn eases_along_spine(&self) -> bool {
!self.no_spine && (self.spine.is_some() || self.orientation == BlendOrientation::AlignToPath)
}
}
/// The Blend panel's Create Spine setting: whether a new blend gets a spine.
+2 -1
View File
@@ -119,7 +119,8 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
{
out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps));
}
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) {
// A linked opacity mask bends with the object it masks; an unlinked one stays where it is.
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
m.art = Arc::new(map_node(&m.art, w));
}
match &mut out.kind {
+237 -69
View File
@@ -1,6 +1,7 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points,
//! and a bevel ends at the corners of the two segments it joins.
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
@@ -39,10 +40,20 @@ fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2,
/// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there
/// or the miter limit bevels it.
fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> {
let cos = t_in.dot(t_out);
// cos(half the turn) is sin(half the angle between the segments): the miter is side / it.
let half = ((1.0 + cos) / 2.0).max(0.0).sqrt();
if cos >= CORNER_COS || half * limit < 1.0 {
let half = ((1.0 + t_in.dot(t_out)) / 2.0).max(0.0).sqrt();
if half * limit < 1.0 {
return None;
}
let ([a, b], out) = bevel(at, t_in, t_out, side)?;
Some([a, at + out * (side / half), b])
}
/// The bevel at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its path:
/// the outer corners of the two segments' strokes and the unit direction out of the turn, or
/// `None` when the path doesn't turn there.
fn bevel(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<([Point; 2], Vec2)> {
if t_in.dot(t_out) >= CORNER_COS {
return None;
}
let out = unit(t_in - t_out);
@@ -51,7 +62,7 @@ fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[P
let n = Vec2::new(-t.y, t.x);
if n.dot(out) >= 0.0 { n } else { -n }
};
Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side])
Some(([at + outer(t_in) * side, at + outer(t_out) * side], out))
}
/// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as
@@ -187,26 +198,44 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
}
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
/// ends of an open path? Else it reaches evenly round it.
/// Does bounding this stroke need its path's shape: miter spikes, bevels, projecting caps,
/// arrowheads, an alignment that depends on whether the path is closed, or butt caps, which
/// stop at the ends of an open path? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
self.join != LineJoin::Round
|| self.cap != LineCap::Round
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
/// joint between segments paints ([`round_join_box`]), a shallow one included.
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
/// are measured apart. A segment in the middle is measured only when its own box grown by
/// `side`, which holds everything it paints, is not inside the box so far.
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
/// Does this stroke stop at the corners of its segments along a subpath that is `closed` or
/// open, where its caps are butt caps on an open subpath or its joins are bevels or miters?
/// Dashes with round or projecting caps can end at a corner, so with them only butt caps stop.
fn stops_at_corners(&self, closed: bool) -> bool {
let capped_dashes = self.cap != LineCap::Butt && self.dash.as_ref().is_some_and(Dash::is_dashed);
(self.cap == LineCap::Butt && !closed) || (self.join != LineJoin::Round && !capped_dashes)
}
/// Does this stroke reach past a subpath that is `closed` or open by a margin that follows the
/// direction of its segments at their corners: where it stops at them
/// ([`Self::stops_at_corners`]) or paints miter spikes, which dashes with round or projecting
/// caps also paint?
fn reaches_by_corners(&self, closed: bool) -> bool {
self.stops_at_corners(closed) || self.join == LineJoin::Miter
}
/// The box this stroke's body paints along `segs`, the segments with length of a subpath, short
/// of its caps, joined with `within`: each segment's [`swept_box`] and, with round joins on an
/// open subpath, the arc each joint between segments paints ([`round_join_box`]), a shallow one
/// included. A bevel stays inside the boxes of the segments it joins. `None` when `segs` is
/// empty. Butt dashes stop inside the same box. The caps other than butt ones, the heads and
/// miter tips are measured apart. A segment in the middle is measured only when its own box
/// grown by `side`, which holds everything it paints, is not inside the box so far, which
/// starts as `within` and the first and last segments' boxes.
fn body_along(&self, segs: &[PathSeg], side: f64, within: Rect) -> Option<Rect> {
let (first, last) = (segs.first()?, segs.last()?);
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)).union(within);
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
});
@@ -217,24 +246,28 @@ impl StrokeLayer {
}
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
/// reach of the arrowheads round their end points.
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
let els = bp.elements();
let subs = subpaths(bp);
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
// subpath's own box needed.
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
let mut even = even_only.then_some(bounds);
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
// A butt cap stops at an open subpath's end, and a bevel, or a miter the limit bevels, at
// the two segments' corners, so such a subpath is measured along its segments. Every
// subpath reaches evenly unless one is measured that way; only then is each subpath's own
// box needed.
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
let mut even = even_only.then_some(bounds);
for (r, closed) in subs {
let side = self.side_reach(closed);
let butt = self.cap == LineCap::Butt && !closed;
if !butt {
let along = self.stops_at_corners(closed);
if !along {
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
}
if side <= 0.0 {
@@ -242,10 +275,10 @@ impl StrokeLayer {
}
let square = self.cap == LineCap::Square && !closed;
let miters = measure_tips && self.join == LineJoin::Miter;
if !(butt || square || miters || !even_only) {
if !(along || square || miters || !even_only) {
continue;
}
let segs = drawn(&els[r]);
let segs = drawn(&els[r.clone()]);
if miters {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
@@ -253,13 +286,24 @@ impl StrokeLayer {
}
}
}
if butt {
if let Some(body) = self.butt_body(&segs, side) {
out = out.union(body);
if along {
// The path's bounds are in the box already, so only the segments that can reach
// past them are measured.
match self.body_along(&segs, side, out) {
Some(body) => out = out.union(body),
// A subpath with no length paints at most its caps' dot.
None if !butt => {
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
}
None => {}
}
continue;
}
if !even_only {
if self.cap == LineCap::Round && !closed {
for (at, _) in ends(&segs).into_iter().flatten() {
out = out.union(Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
}
}
} else if !even_only {
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
}
if square {
@@ -279,7 +323,8 @@ impl StrokeLayer {
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
/// ([`Self::body_along`]).
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
self.reach_along(bp, bounds, None, true)
}
@@ -329,6 +374,9 @@ impl StrokeLayer {
let segs = drawn(&els[r]);
let (half, region) = self.body(closed);
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
// keeps the round reach at the ends.
let squared = self.profile.is_none() && self.stops_at_corners(closed);
// Every segment near enough to reach `p`: with a width profile the wider side of a
// farther segment can paint past the nearest one, so the nearest alone is not enough.
let near = segs.iter().enumerate().filter_map(|(i, s)| {
@@ -365,7 +413,8 @@ impl StrokeLayer {
}
})
};
if d <= half * factor.max(0.0) + tol && on_side(region, d) {
if d <= half * factor.max(0.0) + tol && on_side(region, d) && (!squared || self.paints_at_end(&segs, closed, (i, nr.t), p, half, tol))
{
return true;
}
}
@@ -393,6 +442,35 @@ impl StrokeLayer {
false
}
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
/// the segment that `t` is at, by more than `tol`, and past it when a round cap or a round join
/// paints there, when the path does not turn at that end, or when `p` is within `tol` of the
/// bevel's triangle. Projecting caps and
/// miter spikes are checked apart. A curve that bends more tightly than `side` ([`gentle`])
/// counts as painting round its ends.
fn paints_at_end(&self, segs: &[PathSeg], closed: bool, (i, t): (usize, f64), p: Point, side: f64, tol: f64) -> bool {
let (n, at_start) = (segs.len(), t <= 1e-9);
let Some(seg) = segs.get(i) else { return true };
if (!at_start && t < 1.0 - 1e-9) || !(matches!(seg, PathSeg::Line(_)) || gentle(seg, side)) {
return true;
}
let (at, out) = if at_start { (seg.start(), -tangent(seg, 0.0)) } else { (seg.end(), tangent(seg, 1.0)) };
if (p - at).dot(out) <= tol {
return true;
}
// The segment on the other side of this end, `None` at the end of an open subpath.
let other = if at_start { (i > 0 || closed).then(|| (i + n - 1) % n) } else { (i + 1 < n || closed).then(|| (i + 1) % n) };
let Some(other) = other.and_then(|o| segs.get(o)) else { return self.cap == LineCap::Round };
if self.join == LineJoin::Round {
return true;
}
let (t_in, t_out) = if at_start { (tangent(other, 1.0), tangent(seg, 0.0)) } else { (tangent(seg, 1.0), tangent(other, 0.0)) };
// A joint where the path does not turn has no bevel: the stroke runs on through it.
bevel(at, t_in, t_out, side).is_none_or(|([a, b], _)| in_convex(&[at, a, b], p, tol))
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
@@ -400,13 +478,15 @@ impl StrokeLayer {
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let Some(kind) = (if end { &self.end_arrow } else { &self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol
&& along <= kind.length() * hw + self.width / 2.0 + tol
&& along >= -kind.reach() * hw - tol
}
}
}
@@ -426,7 +506,7 @@ impl Appearance {
}
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
/// (miter spikes, bevels, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
@@ -437,17 +517,21 @@ impl Appearance {
})
}
/// Does this appearance have a visible butt-capped stroke?
pub fn has_butt_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
/// Does this appearance have a visible stroke that stops at the corners of its segments on an
/// open subpath or a closed one, or paints miter spikes: butt caps, or bevel and miter joins
/// ([`StrokeLayer::reaches_by_corners`])?
pub fn has_cornered_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.reaches_by_corners(false))
}
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
/// out of proportion changes.
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_butt_stroke() {
/// Does a visible stroke of this appearance that stops at the corners of its segments (butt
/// caps on an open subpath, bevel and miter joins) or paints miter spikes, dashed ones with
/// round or projecting caps included, run along a subpath of `bp` where it does so, with a
/// segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at those corners, and at miter tips, depends on their direction, which a
/// scale out of proportion changes.
pub fn has_slanted_stroke_corners(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_cornered_stroke() {
return false;
}
let slanted = |v: Vec2| {
@@ -455,9 +539,10 @@ impl Appearance {
(d.x * d.y).abs() > 1e-9
};
let els = bp.elements();
subpaths(bp)
.into_iter()
.filter(|(_, closed)| !closed)
let subs = subpaths(bp);
let cornered = |closed: bool| self.painted_strokes().any(|s| s.reaches_by_corners(closed));
subs.into_iter()
.filter(|(_, closed)| cornered(*closed))
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
}
@@ -468,28 +553,28 @@ impl Appearance {
}
}
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
/// How many symbol instances [`crate::Node::has_slanted_stroke_corners`] looks into for one object
/// before it answers yes without looking further.
pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
/// answers yes.
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
/// yes.
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
}
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
}
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
}
}
@@ -566,6 +651,79 @@ mod tests {
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
#[test]
fn a_bevel_stops_at_the_corners_of_the_segments_it_joins() {
// A 40 × 100 pt triangle stroked 20 pt: a miter limit of 2 or a bevel join bevels its
// 22.6° tip at (20, 0), so the stroke reaches 10 · 20 / √10400 pt above it, not 10 pt.
let mut tri = BezPath::new();
tri.move_to((0.0, 100.0));
tri.line_to((20.0, 0.0));
tri.line_to((40.0, 100.0));
tri.close_path();
let tb = tri.bounding_box();
let (top, side) = (-200.0 / 10400.0_f64.sqrt(), 1000.0 / 10400.0_f64.sqrt());
let limited = stroke(20.0, |s| s.miter_limit = 2.0);
let bevel = stroke(20.0, |s| {
s.join = LineJoin::Bevel;
s.cap = LineCap::Round;
});
let b = limited.bounds_on(&tri, tb);
assert!((b.y0 - top).abs() < 1e-9, "{b:?}");
// The limit keeps the base corners' miters, whose tips reach about 12.2 pt left and right.
assert!(b.x0 < -12.0 && b.x1 > 52.0, "{b:?}");
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0);
*ap.stroke_mut().unwrap() = bevel.clone();
let b = ap.stroked_bounds(tb, || tri.clone());
for (got, want) in [(b.x0, -side), (b.y0, top), (b.x1, 40.0 + side), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// Open, the same corner is beveled and the round caps reach the half weight round the ends.
let chevron = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
let b = bevel.bounds_on(&chevron, chevron.bounding_box());
for (got, want) in [(b.x0, -10.0), (b.y0, top), (b.x1, 50.0), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// A round join, and the round caps of dashes, which can end at the tip, reach round it.
let round = stroke(20.0, |s| s.join = LineJoin::Round);
assert!((round.bounds_on(&tri, tb).y0 + 10.0).abs() < 1e-9);
let mut dashed = bevel.clone();
dashed.dash = Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false });
assert!((dashed.bounds_on(&chevron, chevron.bounding_box()).y0 + 10.0).abs() < 1e-9);
}
#[test]
fn a_click_past_a_bevel_or_a_butt_end_misses() {
// 5 pt above the triangle's tip is within the half weight of it, but past the bevel, which
// reaches about 1.96 pt above it. A round join paints there.
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
let (above, on) = (Point::new(20.0, -5.0), Point::new(20.0, -1.5));
for join in [LineJoin::Bevel, LineJoin::Miter] {
let st = stroke(20.0, |s| (s.join, s.miter_limit) = (join, 2.0));
assert!(!st.hits(&tri, FillRule::NonZero, above, 0.5), "{join:?}");
assert!(st.hits(&tri, FillRule::NonZero, on, 0.0), "{join:?}");
}
assert!(stroke(20.0, |s| s.join = LineJoin::Round).hits(&tri, FillRule::NonZero, above, 0.5));
// 1.5 pt past a butt end of a 4 pt line misses, and a quarter point within it hits; a round
// cap paints past it.
let line = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
let butt = stroke(4.0, |s| s.cap = LineCap::Butt);
assert!(!butt.hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
assert!(butt.hits(&line, FillRule::NonZero, Point::new(1.0, -0.2), 0.25));
assert!(stroke(4.0, |s| s.cap = LineCap::Round).hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
}
#[test]
fn a_joint_too_shallow_to_bevel_paints_past_both_segments_ends() {
// The path turns by about 0.57° at (100, -0.5), too little to bevel, so the stroke runs on
// through the joint: 3.5 pt above it is past the end of both segments and still painted.
let kink = polyline(&[(0.0, 0.0), (100.0, -0.5), (200.0, 0.0)]);
let above = Point::new(100.0, -4.0);
for join in [LineJoin::Bevel, LineJoin::Miter, LineJoin::Round] {
assert!(stroke(10.0, |s| s.join = join).hits(&kink, FillRule::NonZero, above, 0.0), "{join:?}");
}
}
/// An open path through `points`.
fn polyline(points: &[(f64, f64)]) -> BezPath {
let mut bp = BezPath::new();
@@ -691,15 +849,25 @@ mod tests {
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let id = vectorcraft_geom::Affine::IDENTITY;
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
assert!(!ap.has_slanted_stroke_corners(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
// Square ends, slanted segments in the middle.
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&apex, id));
// A rotation slants a vertical line; a round cap is never slanted.
assert!(ap.has_slanted_stroke_corners(&apex, id));
// A rotation slants a vertical line.
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
assert!(ap.has_slanted_stroke_corners(&v, vectorcraft_geom::Affine::rotate(0.3)));
// With round caps, the miter join still stops at the corners of the slanted segments, on a
// closed path too; round caps and round joins never do.
ap.stroke_mut().unwrap().cap = LineCap::Round;
assert!(!ap.has_slanted_butt_stroke(&apex, id));
assert!(ap.has_slanted_stroke_corners(&apex, id));
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
ap.stroke_mut().unwrap().join = LineJoin::Bevel;
assert!(ap.has_slanted_stroke_corners(&tri, id));
assert!(!ap.has_slanted_stroke_corners(&square(), id));
ap.stroke_mut().unwrap().join = LineJoin::Round;
assert!(!ap.has_slanted_stroke_corners(&apex, id));
assert!(!ap.has_slanted_stroke_corners(&tri, id));
}
#[test]
@@ -723,11 +891,11 @@ mod tests {
}
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let symbols = d.symbol_boxes();
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(top.has_slanted_stroke_corners(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
// One instance of S1 holds three instances, all looked into.
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
assert!(!one.has_slanted_stroke_corners(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
}
#[test]
+3 -1
View File
@@ -57,7 +57,9 @@ pub struct CharStyle {
#[serde(default)]
pub all_caps: bool,
/// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns
/// a feature on, `"-liga"` off.
/// a feature on, `"-liga"` off, and `"salt=2"` turns a feature with alternates on at the font's
/// alternate number 2 (the value the shaper gets; a plain `"salt"` is value 1). Runs that
/// differ only in this list are shaped together, each with its own features.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub features: Vec<String>,
/// Character style (Character Styles panel) these attributes come from; None = Normal.
+10
View File
@@ -237,6 +237,10 @@ pub struct ParaStyle {
/// 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,
/// Bunri-Kinshi (Paragraph panel menu): a line never breaks inside an inseparable pair (two em
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
/// with kinsoku None, where it has no effect. Off by default.
pub bunri_kinshi: bool,
/// 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.
@@ -339,6 +343,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku_type: KinsokuShoriType,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
bunri_kinshi: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -375,6 +381,7 @@ impl From<ParaStyle> for ParaStyleFile {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -401,6 +408,7 @@ impl From<ParaStyle> for ParaStyleFile {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -431,6 +439,7 @@ impl From<ParaStyleFile> for ParaStyle {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -456,6 +465,7 @@ impl From<ParaStyleFile> for ParaStyle {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
+7 -6
View File
@@ -29,7 +29,7 @@ use crate::group::{has_own_paint, paints};
use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
has_item_geometry, has_pathfinder, is_geometry, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
};
fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
@@ -41,8 +41,8 @@ fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
fn clear_item_effects(item: &mut AppearanceItem) {
match item {
AppearanceItem::Fill(f) => f.effects.retain(|e| !is_geometry(&e.id)),
AppearanceItem::Stroke(s) => s.effects.retain(|e| !is_geometry(&e.id)),
AppearanceItem::Fill(f) => f.effects = crate::raster::without_geometry(&f.effects),
AppearanceItem::Stroke(s) => s.effects = crate::raster::without_geometry(&s.effects),
}
}
@@ -337,7 +337,7 @@ fn moved_type_group(n: &Node) -> Option<Node> {
g.knockout = Knockout::Off;
g.knockout_shape = n.knockout_shape;
g.extras_mut().mask = n.extras().mask.clone();
g.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
g.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
Some(g)
}
@@ -397,7 +397,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
return None;
}
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
m.appearance.items.clear();
m.appearance.contents_index = None;
Some(m)
@@ -439,7 +440,7 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
m.appearance.effects.retain(|e| !is_geometry(&e.id));
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
Some((g, rule, ctx, m))
}
+5 -3
View File
@@ -94,6 +94,8 @@ fn lengths_of(id: &str) -> Lengths {
"stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]),
"brushStrokes.accentedEdges" => always(&["edgeWidth"]),
"artistic.paletteKnife" => always(&["strokeSize"]),
"artistic.coloredPencil" => always(&["pencilWidth"]),
"artistic.paintDaubs" => always(&["brushSize"]),
"brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]),
"brushStrokes.spatter" => always(&["sprayRadius"]),
"brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]),
@@ -258,14 +260,14 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"distort.roughen",
"Roughen…",
DT,
"{size: 0..100 (5), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}",
"{size: 0..100 (5; 0 keeps the outline and adds its points along it), relative: bool (true: % of size; false: pt), detail: per inch 0..100 (10), points: \"smooth\"|\"corner\", seed: int (0)}",
json!({"size": 5.0, "relative": true, "detail": 10.0, "points": "smooth", "seed": 0}),
),
g(
"distort.transform",
"Transform…",
DT,
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), 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 and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are), 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; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
),
g(
@@ -387,7 +389,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"artistic.paintDaubs",
"Paint Daubs…",
ARTISTIC,
"{brushSize: 1..50 (10; dab centres farther apart), sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
"{brushSize: 1..50 (10; spacing of the dab centers in document units),sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
json!({"brushSize": 10.0, "sharpness": 25.0, "brushType": "simple"}),
),
r(
+22 -1
View File
@@ -3,6 +3,7 @@
use serde_json::Value;
use vectorcraft_geom::kurbo::ParamCurveArclen;
use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
use vectorcraft_pathops::addons::pathtools::insert_at;
use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points};
@@ -79,7 +80,8 @@ const MAX_ROUGHEN_POINTS: usize = 2000;
/// Roughen: resample at `detail` points per inch and jitter each point by up to `size`. Where
/// that would make more than `max` anchors, the points are spaced further apart until it doesn't
/// (stacked Roughens multiply their points, #3578).
/// (stacked Roughens multiply their points, #3578). At size 0 no point moves: each segment is
/// split into its pieces, evenly along its length, and the outline stays as it is.
pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
let size = num(p, "size", 5.0).clamp(0.0, 1e4);
let amp = if flag(p, "relative", true) { size / 100.0 * mean_size(b) } else { size };
@@ -89,6 +91,23 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i).arclen(0.1))).collect();
let spacing = fit_piece(&lens, spacing, MAX_ROUGHEN_POINTS, max.saturating_sub(path.anchor_count()));
let mut lens = lens.iter();
if amp == 0.0 {
// Each segment's pieces, cut at equal lengths as `pathtools::add_points` cuts them.
let mut subs = Vec::with_capacity(path.subpaths.len());
for sp in &path.subpaths {
let mut places = vec![];
for (i, &coarse) in (0..sp.segment_count()).zip(&mut lens) {
let k = pieces(coarse, spacing, MAX_ROUGHEN_POINTS);
let c = sp.segment(i);
let len = c.arclen(ROUGHEN_ARCLEN_ACCURACY);
if len > 1e-9 && len.is_finite() {
places.extend((1..k).map(|j| (i, c.inv_arclen(len * j as f64 / k as f64, ROUGHEN_ARCLEN_ACCURACY))));
}
}
subs.push(insert_at(sp, &places).0);
}
return PathData::new(subs);
}
let smooth = smooth_points(p);
let seed = seed(p);
let mut subs = vec![];
@@ -118,6 +137,8 @@ pub fn roughen(path: &PathData, b: Rect, p: &Value, max: usize) -> PathData {
PathData::new(subs)
}
const ROUGHEN_ARCLEN_ACCURACY: f64 = 1e-4;
/// The move and the number of copies of a Transform effect with params `p` that only moves what
/// it applies to, as [`transform_map`] reads them; `None` when it also scales, rotates or reflects,
/// or moves by a random share, or moves pattern paints along (Transform Patterns), or scales
+3 -2
View File
@@ -265,7 +265,7 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
fn without_geometry_effects(n: &mut Node) {
if n.appearance.effects.iter().any(|e| crate::is_geometry(&e.id)) {
let mut ap = (*n.appearance).clone();
ap.effects.retain(|e| !crate::is_geometry(&e.id));
ap.effects = crate::raster::without_geometry(&ap.effects);
n.appearance = ap.into();
}
}
@@ -794,7 +794,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
carry.apply(&mut m.appearance);
}
}
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id));
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
if paint {
let shapes = member_shapes(doc, &m);
let bounds = m.geometric_bounds();
+519
View File
@@ -690,6 +690,525 @@ fn a_transform_on_a_group_paints_each_copy_with_its_own_gradient() {
}
}
/// A white 10 pt square with id `id` at the origin.
fn white_square(id: u64) -> Node {
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0))
}
/// `n` masked by `art`, linked or not.
fn masked_by(mut n: Node, art: Node, linked: bool) -> Node {
let mut mask = vectorcraft_doc::OpacityMask::new(art, true);
mask.linked = linked;
n.extras_mut().mask = Some(Box::new(mask));
n
}
/// The geometry effects that reshape a group's members, one at a time.
fn reshaping_effects() -> Vec<Effect> {
let fx = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
let corners = serde_json::json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]});
vec![
fx("distort.transform", serde_json::json!({"moveH": 30})),
fx("distort.transform", serde_json::json!({"rotate": 90})),
fx("distort.twist", serde_json::json!({"angle": 90})),
fx("distort.freeDistort", corners),
fx("warp.arc", serde_json::json!({})),
fx("distort.roughen", serde_json::json!({"size": 5, "seed": 3})),
fx("distort.zigZag", serde_json::json!({})),
fx("distort.puckerBloat", serde_json::json!({"amount": 50})),
fx("distort.tweak", serde_json::json!({})),
fx("path.offsetPath", serde_json::json!({"offset": 3})),
fx("stylize.roundCorners", serde_json::json!({"radius": 3})),
]
}
/// A group's geometry effect reshapes the art of a member's linked opacity mask as it reshapes the
/// member: a mask drawn over the member still covers it. An unlinked mask stays where it is.
#[test]
fn a_groups_geometry_effects_reshape_a_members_linked_mask_with_it() {
let square = white_square(1);
let original = square.path_data().cloned();
for e in reshaping_effects() {
for linked in [true, false] {
let member = masked_by(square.clone(), white_square(4), linked);
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(e.clone());
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
let mask = member.extras().mask.as_deref().unwrap();
assert!(member.path_data().cloned() != original, "{}: the member is reshaped", e.id);
let want = if linked { member.path_data().cloned() } else { original.clone() };
assert_eq!(mask.art.path_data().cloned(), want, "{} (linked: {linked})", e.id);
assert_eq!(mask.linked, linked);
}
}
}
/// The mask of a group inside the group, the mask of a path in it, a mask inside that mask's art and
/// an inverted mask all take the outer group's effect with the paths they mask.
#[test]
fn a_groups_geometry_effects_reshape_nested_and_inverted_masks() {
for e in reshaping_effects() {
let innermost = masked_by(white_square(7), white_square(8), true);
let path = masked_by(white_square(1), masked_by(white_square(6), innermost, true), true);
let mut inner = masked_by(Node::group(NodeId(5), vec![Arc::new(path)]), white_square(4), true);
if let Some(m) = inner.extras_if_any().and_then(|x| x.mask.as_mut()) {
m.invert = true;
}
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(e.clone());
let art = evaluate_container(None, &g).unwrap();
let inner = &art.children().unwrap()[0];
let path = &inner.children().unwrap()[0];
let want = path.path_data().cloned();
let mask_of = |n: &Node| n.extras().mask.as_deref().map(|m| (*m.art).clone()).unwrap();
let (outer_mask, path_mask) = (mask_of(inner), mask_of(path));
assert!(inner.extras().mask.as_deref().is_some_and(|m| m.invert));
assert_eq!(outer_mask.path_data().cloned(), want, "{}: the inner group's inverted mask", e.id);
assert_eq!(path_mask.path_data().cloned(), want, "{}: the path's mask", e.id);
assert_eq!(mask_of(&path_mask).path_data().cloned(), want, "{}: the mask inside the mask's art", e.id);
assert_eq!(mask_of(&mask_of(&path_mask)).path_data().cloned(), want, "{}: one level deeper", e.id);
}
}
/// A Transform effect's copies of a path with a linked mask are objects of their own, each with the
/// mask moved with it; the original keeps its mask where it was.
#[test]
fn each_transform_copy_of_a_masked_member_carries_its_mask() {
let member = masked_by(white_square(1), white_square(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
let params = serde_json::json!({"moveH": 30, "copies": 2});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let copies = art.children().unwrap()[0].children().expect("the object and its copies are objects of their own");
assert_eq!(copies.len(), 3);
for c in copies {
let mask = c.extras().mask.as_deref().unwrap();
assert_eq!(mask.art.geometric_bounds(), c.geometric_bounds());
}
}
/// A Transform effect's copies of the paths of a member group give the group's linked mask the same
/// copies: the mask covers each copy.
#[test]
fn a_member_groups_mask_takes_the_transform_copies_of_its_paths() {
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
let params = serde_json::json!({"moveH": 30, "copies": 1});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let inner = &art.children().unwrap()[0];
let want = inner.geometric_bounds();
assert_eq!(want, Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "the path and its copy");
assert_eq!(inner.extras().mask.as_deref().unwrap().art.geometric_bounds(), want);
}
/// A mask's art of several objects takes Transform copies whole, as the art it masks does: each copy
/// of the mask's art is a group of its objects, so the copies do not interleave object by object.
#[test]
fn a_masks_art_of_several_objects_is_copied_whole() {
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
let params = serde_json::json!({"moveH": 30, "copies": 1});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
let copies = mask.children().unwrap();
assert_eq!(copies.len(), 2, "the mask's art and its copy");
for c in copies {
let ids: Vec<NodeId> = c.children().into_iter().flatten().map(|m| m.id).collect();
assert_eq!(ids, [NodeId(4), NodeId(5)], "each copy holds the mask's objects");
}
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)));
}
/// The linked mask of a mask's art that is copied whole takes the same Transform copies.
#[test]
fn the_mask_of_a_masks_art_copied_whole_takes_its_copies() {
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
let mask_art = masked_by(parts, white_square(6), true);
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
let params = serde_json::json!({"moveH": 30, "copies": 1});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 45.0, 10.0)), "the mask's art and its copy");
let own = &mask.extras().mask.as_deref().expect("the mask's art keeps its own mask").art;
assert_eq!(own.geometric_bounds(), Some(Rect::new(0.0, 0.0, 40.0, 10.0)), "its mask covers the copy too");
}
/// The mask of a mask's art copied whole stays in the budget while that art is copied: when the
/// budget has no room for that mask's copy, the art keeps its shape with its masks.
#[test]
fn the_mask_of_a_masks_art_copied_whole_counts_against_the_budget() {
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
let parts = Node::group(NodeId(3), vec![Arc::new(white_square(4)), sq(5, 5.0, Color::WHITE)]);
let mask_art = masked_by(parts, white_square(6), true);
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
let mut art = Node::group(NodeId(10), vec![Arc::new(inner)]);
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
// Room for the four squares and the copies of three of them, not for the copy of the fourth.
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 7 * one };
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
let inner = &art.children().unwrap()[0];
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
assert_eq!(inner.geometric_bounds(), square, "the path keeps its shape");
let mask = &inner.extras().mask.as_deref().unwrap().art;
assert_eq!(mask.geometric_bounds(), Some(Rect::new(0.0, 0.0, 15.0, 10.0)), "and so does its mask");
}
/// When a member group's linked mask can't take all the Transform copies its paths take (past the
/// budget), the art keeps its shape under the effect, so the mask still covers the paths.
#[test]
fn art_whose_mask_would_take_fewer_copies_keeps_its_shape() {
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 1}), visible: true };
let member = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
// Room for the path, its mask and a copy of the path, not for a copy of the mask.
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 3 * one };
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
let member = &art.children().unwrap()[0];
let square = Some(Rect::new(0.0, 0.0, 10.0, 10.0));
assert_eq!(member.geometric_bounds(), square, "the path keeps its shape");
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), square, "and so does its mask");
}
/// The copies of a path with a linked mask count the art of the mask each copy carries against the
/// budget: they stop where the masks would pass it.
#[test]
fn transform_copies_count_the_art_of_their_masks() {
let transform = Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 30, "copies": 2}), visible: true };
let member = masked_by(white_square(1), white_square(4), true);
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
let one = crate::Budget::of(white_square(1).path_data().unwrap()).lines;
// Room for the path, its mask and one copy of both, not for a second copy.
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 4 * one };
crate::reshape::reshape_leaves_within(&mut art, &[&transform], budget, None);
let copies = art.children().unwrap()[0].children().expect("the object and its copy are objects of their own");
assert_eq!(copies.len(), 2);
for c in copies {
assert_eq!(c.extras().mask.as_deref().unwrap().art.geometric_bounds(), c.geometric_bounds());
}
}
/// A Transform effect that scales strokes moves a group's paths as objects, their masks with them.
/// The mask of a member group, whose art holds a path with a mask of its own, moves with the group's
/// paths too.
#[test]
fn a_transform_that_moves_paths_as_objects_moves_a_member_groups_nested_mask() {
let mask_art = masked_by(white_square(4), white_square(5), true);
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), mask_art, true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner), sq(3, 20.0, Color::BLACK)]);
let params = serde_json::json!({"moveH": 30, "strokes": true});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let inner = &art.children().unwrap()[0];
let want = inner.children().unwrap()[0].geometric_bounds();
assert_eq!(want, Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
let mask = &inner.extras().mask.as_deref().unwrap().art;
assert_eq!(mask.geometric_bounds(), want, "the group's mask");
assert_eq!(mask.extras().mask.as_deref().unwrap().art.geometric_bounds(), want, "the mask inside its art");
}
/// A group's Transform effect moves an image member's linked opacity mask with the image, and its
/// copies' masks with the copies; an unlinked mask stays.
#[test]
fn a_groups_transform_moves_an_image_members_linked_mask() {
for linked in [true, false] {
for copies in [0, 2] {
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), white_square(4), linked);
let mut g = Node::group(NodeId(10), vec![Arc::new(image)]);
let params = serde_json::json!({"moveH": 30, "copies": copies});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let first = &art.children().unwrap()[0];
let images: Vec<&Node> = match first.children() {
Some(ch) => ch.iter().map(|c| &**c).collect(),
None => vec![first],
};
assert_eq!(images.len(), copies + 1);
for im in images {
let mask = im.extras().mask.as_deref().unwrap();
let want = if linked { im.geometric_bounds() } else { Some(Rect::new(0.0, 0.0, 10.0, 10.0)) };
assert_eq!(mask.art.geometric_bounds(), want, "linked {linked}, copies {copies}");
}
}
}
}
/// When a path in a member's mask art would pass the effects' budget, the whole mask stays as it
/// was, rather than part of its art moving with the member, and the member keeps its shape with it.
#[test]
fn a_mask_whose_art_passes_the_budget_stays_whole() {
// Bloat bends a path's sides into curves drawn with more lines the larger they are: many more
// on the mask's large square.
let bloat = Effect { id: "distort.puckerBloat".into(), params: serde_json::json!({"amount": 50}), visible: true };
let large = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 1000.0, 1000.0)), Appearance::default());
let mask_art = Node::group(NodeId(3), vec![Arc::new(white_square(4)), Arc::new(large.clone())]);
let member = masked_by(white_square(1), mask_art.clone(), true);
let mut art = Node::group(NodeId(10), vec![Arc::new(member)]);
// Room for the member and the mask's small square to take the effect, not for the large one.
let bounds = art.geometric_bounds().unwrap();
let ctx = crate::GeomContext { seed: 10, ..crate::GeomContext::of(&art) };
let square = white_square(1).path_data().cloned().unwrap();
let made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), &square, bounds, &ctx)).lines;
let budget = crate::Budget { anchors: usize::MAX / 4, lines: 2 * made + crate::Budget::of(large.path_data().unwrap()).lines };
let large_made = crate::Budget::of(&crate::apply_geometry_with(std::slice::from_ref(&bloat), large.path_data().unwrap(), bounds, &ctx)).lines;
assert!(large_made > crate::Budget::of(large.path_data().unwrap()).lines, "the large square's curves cost more lines");
crate::reshape::reshape_leaves_within(&mut art, &[&bloat], budget, None);
let member = &art.children().unwrap()[0];
assert_eq!(member.path_data(), Some(&square), "the member keeps its shape with its mask");
assert_eq!(*member.extras().mask.as_deref().unwrap().art, mask_art, "the mask stays whole");
}
/// Live objects in a member's linked mask are evaluated before the group's geometry effects run
/// over the mask's art, so the mask still covers the member: a Repeat in it moves and bends with
/// the member.
#[test]
fn a_groups_effects_reshape_a_live_object_in_a_members_mask() {
let mut grid = vectorcraft_doc::RepeatSpec::grid(vec![Arc::new(white_square(5))], 0.0, 0.0);
if let vectorcraft_doc::RepeatKind::Grid { rows, cols, .. } = &mut grid.kind {
(*rows, *cols) = (1, 1);
}
let repeat = Node::new(NodeId(4), NodeKind::Repeat(grid));
let drawn: Vec<Node> = crate::expand_live(None, &repeat);
let leaf = |n: &Node| {
let mut found = None;
n.walk(&mut |c| found = found.take().or_else(|| c.path_data().cloned()));
found
};
assert_eq!(drawn.iter().find_map(leaf), white_square(1).path_data().cloned(), "the Repeat draws one square over the member");
for e in [reshaping_effects()[0].clone(), reshaping_effects()[4].clone()] {
let member = masked_by(white_square(1), repeat.clone(), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(e.clone());
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
let mask = &member.extras().mask.as_deref().unwrap().art;
assert!(member.path_data() != white_square(1).path_data(), "{}: the member is reshaped", e.id);
assert_eq!(leaf(mask), member.path_data().cloned(), "{}: the mask's square takes the effect with it", e.id);
}
}
/// Type in a member's linked mask is outlined before the group's Transform effect moves the mask's
/// art with the member.
#[test]
fn a_groups_transform_moves_type_in_a_members_mask() {
if skip_without_craft_fonts() {
return;
}
let member = masked_by(white_square(1), type_h(), true);
let before = crate::reshape::outline_text(&type_h()).unwrap().geometric_bounds().unwrap();
let mut g = Node::group(NodeId(10), vec![Arc::new(member)]);
g.appearance.effects.push(reshaping_effects()[0].clone());
let art = evaluate_container(None, &g).unwrap();
let mask = &art.children().unwrap()[0].extras().mask.as_deref().unwrap().art;
let mut text = false;
mask.walk(&mut |c| text |= matches!(c.kind, NodeKind::Text(_)));
assert!(!text, "the type is outlined");
let after = mask.geometric_bounds().unwrap();
assert!((after.x0 - before.x0 - 30.0).abs() < 0.5 && (after.y0 - before.y0).abs() < 0.5, "{before:?} -> {after:?}");
}
/// The linked mask of a compound path in a group, and of a path in a layer, takes the geometry
/// effects with the art it masks.
#[test]
fn a_compound_paths_and_a_layers_members_masks_take_the_effects() {
let geometry = |n: &Node| crate::reshape::leaf_geometry(n).map(|(p, _)| p);
for e in reshaping_effects() {
let square = white_square(1);
let compound = Node::new(NodeId(1), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: FillRule::NonZero });
let compound = masked_by(compound, white_square(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(compound), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(e.clone());
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
assert!(geometry(member) != square.path_data().cloned(), "{}: the compound path is reshaped", e.id);
assert_eq!(geometry(&member.extras().mask.as_deref().unwrap().art), geometry(member), "{}: compound path", e.id);
let mut layer = Node::layer(NodeId(10), "Layer", vectorcraft_doc::LayerColor::Preset(0));
if let Some(ch) = layer.children_mut() {
ch.extend([Arc::new(masked_by(square.clone(), white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
}
layer.appearance.effects.push(e.clone());
let art = evaluate_container(None, &layer).unwrap();
let member = &art.children().unwrap()[0];
assert!(member.path_data() != square.path_data(), "{}: the layer's path is reshaped", e.id);
assert_eq!(member.extras().mask.as_deref().unwrap().art.path_data(), member.path_data(), "{}: layer", e.id);
}
}
/// A group's Transform effect moves a symbol instance member's linked mask with the instance.
#[test]
fn a_groups_transform_moves_a_symbol_instance_members_linked_mask() {
let instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(instance, white_square(4), true)), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(reshaping_effects()[0].clone());
let art = evaluate_container(None, &g).unwrap();
let instance = &art.children().unwrap()[0];
let NodeKind::SymbolInstance { xf, .. } = &instance.kind else { panic!("an instance: {instance:?}") };
assert!((xf.translation().x - 30.0).abs() < 1e-9, "the instance moves: {xf:?}");
let mask = instance.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
assert!((mask.x0 - 30.0).abs() < 1e-9 && (mask.x1 - 40.0).abs() < 1e-9, "its mask moves with it: {mask:?}");
}
/// With Scale Strokes & Effects on, a group's Transform effect scales the stroke of an image
/// member's linked mask as it scales that of a path member's mask.
#[test]
fn a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike() {
let stroked =
Node::path(NodeId(4), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0));
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let image = masked_by(Node::new(NodeId(1), NodeKind::Image(Box::new(im))), stroked.clone(), true);
let path = masked_by(white_square(2), stroked, true);
let mut g = Node::group(NodeId(10), vec![Arc::new(image), Arc::new(path)]);
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "strokes": true});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let width = |n: &Node| n.extras().mask.as_deref().unwrap().art.appearance.stroke().map(|s| s.width);
let ch = art.children().unwrap();
assert_eq!(width(&ch[1]), Some(4.0), "the path's mask");
assert_eq!(width(&ch[0]), width(&ch[1]), "the image's mask");
}
/// With Transform Objects off and Scale Strokes & Effects on, a group's Transform effect scales the
/// strokes of a member's linked mask as it scales the member's, and moves neither.
#[test]
fn a_transform_of_strokes_only_scales_a_members_mask_strokes() {
let stroked = |id: u64| {
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0))
};
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(stroked(1), stroked(4), true))]);
let params = serde_json::json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
let mask = &member.extras().mask.as_deref().unwrap().art;
assert_eq!(member.appearance.stroke().map(|s| s.width), Some(4.0), "the member's stroke");
assert_eq!(mask.appearance.stroke().map(|s| s.width), Some(4.0), "the mask's stroke");
assert_eq!(mask.geometric_bounds(), member.geometric_bounds());
}
/// The art of a member group's mask is copied as it was before the first effect: a mask of one
/// path takes a second Transform effect's copies path by path, as the path it masks does, though
/// the first effect (with Scale Strokes & Effects) made it a group of copies.
#[test]
fn a_masks_art_is_copied_as_it_was_before_the_first_effect() {
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), white_square(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
for strokes in [true, false] {
let params = serde_json::json!({"moveH": 30, "copies": 2, "strokes": strokes});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
}
let art = evaluate_container(None, &g).unwrap();
let inner = &art.children().unwrap()[0];
let mask = &inner.extras().mask.as_deref().unwrap().art;
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds());
let kinds = |n: &Node| n.children().unwrap().iter().map(|c| std::mem::discriminant(&c.kind)).collect::<Vec<_>>();
let paths = &inner.children().unwrap()[0];
assert_eq!(kinds(paths).len(), 3, "the first effect's three paths");
assert!(paths.children().unwrap().iter().all(|c| matches!(c.kind, NodeKind::Compound { .. })), "each with its copies");
assert_eq!(kinds(mask), kinds(paths), "the mask's art takes the copies as the paths do");
}
/// A 10 × 10 image with id `id` at the origin.
fn image_node(id: u64) -> Node {
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
Node::new(NodeId(id), NodeKind::Image(Box::new(im)))
}
/// A linked mask whose art is an image moves with the path it masks under a group's Transform
/// effect, and a member group's image mask takes the copies its paths take.
#[test]
fn a_groups_transform_moves_a_linked_mask_whose_art_is_an_image() {
let mut g = Node::group(NodeId(10), vec![Arc::new(masked_by(white_square(1), image_node(4), true)), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(reshaping_effects()[0].clone());
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
assert_eq!(member.geometric_bounds(), Some(Rect::new(30.0, 0.0, 40.0, 10.0)));
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), member.geometric_bounds());
let inner = masked_by(Node::group(NodeId(2), vec![Arc::new(white_square(1))]), image_node(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(inner)]);
let params = serde_json::json!({"moveH": 30, "copies": 2});
g.appearance.effects.push(Effect { id: "distort.transform".into(), params, visible: true });
let art = evaluate_container(None, &g).unwrap();
let inner = &art.children().unwrap()[0];
assert_eq!(inner.geometric_bounds(), Some(Rect::new(0.0, 0.0, 70.0, 10.0)));
let mask = &inner.extras().mask.as_deref().unwrap().art;
assert_eq!(mask.geometric_bounds(), inner.geometric_bounds(), "the image and its copies");
}
/// An image in a linked mask's art takes no geometry effect but Transform, so under a Warp effect
/// the art keeps its shape with its mask.
#[test]
fn art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp() {
let member = masked_by(white_square(1), Node::group(NodeId(3), vec![Arc::new(image_node(4))]), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(member), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(reshaping_effects()[4].clone());
let art = evaluate_container(None, &g).unwrap();
let member = &art.children().unwrap()[0];
assert_eq!(member.path_data(), white_square(1).path_data(), "the path keeps its shape");
assert_eq!(member.extras().mask.as_deref().unwrap().art.geometric_bounds(), Some(Rect::new(0.0, 0.0, 10.0, 10.0)));
}
/// A Warp effect bends an image's pixels but not the art of its linked mask, so art with such an
/// image keeps its shape under the warp, with the image and its mask.
#[test]
fn art_with_a_masked_image_keeps_its_shape_under_a_warp() {
let image = masked_by(image_node(1), white_square(4), true);
let mut g = Node::group(NodeId(10), vec![Arc::new(image.clone()), sq(2, 20.0, Color::BLACK)]);
g.appearance.effects.push(reshaping_effects()[4].clone());
let art = evaluate_container(None, &g).unwrap();
let ch = art.children().unwrap();
assert_eq!(*ch[0], image, "the image and its mask");
assert_eq!(ch[1].path_data(), sq(2, 20.0, Color::BLACK).path_data(), "the path keeps its shape");
}
/// A symbol instance in perspective projects the linked masks of the objects in its art with them.
#[test]
fn perspective_projects_the_masks_in_a_symbols_art() {
let art = Node::group(NodeId(20), vec![Arc::new(masked_by(white_square(21), white_square(22), true))]);
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let mut at = vectorcraft_doc::PerspectiveAttachment::new("left", 0.0);
at.projection = Some([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.01, 0.0, 1.0]);
instance.extras_mut().perspective = Some(Box::new(at));
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
let mut masked = vec![];
out.walk(&mut |c| masked.extend(c.extras().mask.as_deref().map(|m| (c.path_data().cloned(), m.art.path_data().cloned()))));
let [(path, mask)] = masked.as_slice() else { panic!("one masked path: {masked:?}") };
assert!(path != &white_square(21).path_data().cloned(), "the path is projected");
assert_eq!(mask, path, "and so is its mask");
}
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
/// pitch, each crossing every bar of the other direction: n² crossings.
fn crossing_bars(n: usize, effect: &str) -> Node {
+3 -3
View File
@@ -78,7 +78,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
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 raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects, without_geometry};
pub use 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,
@@ -89,8 +89,8 @@ pub use revolve::{
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+117 -4
View File
@@ -1,11 +1,13 @@
//! Raster (painted) effects: descriptions for the renderer.
use serde_json::Value;
use std::borrow::Cow;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Color};
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::merged_params;
use crate::pixel::{self, PixelFx, PixelSpace};
@@ -384,9 +386,10 @@ fn opacity(p: &Value) -> f32 {
(num(p, "opacity", 75.0) / 100.0).clamp(0.0, 1.0) as f32
}
/// The visible raster effects of `effects`, in stack order.
/// The visible raster effects of `effects`, in stack order, each following the Transform effects
/// listed after it ([`followed`]).
pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
effects
followed(effects)
.iter()
.filter(|e| e.visible)
.filter_map(|e| {
@@ -426,6 +429,116 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
.collect()
}
/// `effects` with each raster effect following the visible Transform effects listed after it
/// ([`follow_transform`]): effects apply in the order they are listed, so a Transform effect
/// transforms what the raster effects before it paint, whatever its Scale Strokes & Effects says.
/// A hidden raster effect follows too, so it draws the same when it is shown after the Transform
/// effect has been expanded. A raster effect that a Transform effect making copies or moving at
/// random follows stays as it is, as does one after the last Transform effect. Borrowed when
/// nothing changes.
pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
if !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
return Cow::Borrowed(effects);
}
let mut out: Option<Vec<Effect>> = None;
// The linear part of the Transform effects after the effect at hand, the last one outermost;
// `None` once one of them makes copies or moves at random.
let mut after = Some(Affine::IDENTITY);
for (i, e) in effects.iter().enumerate().rev() {
if e.id == "distort.transform" {
after = after.and_then(|a| transform_step(e).map(|s| a * s));
continue;
}
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
let list = out.get_or_insert_with(|| effects.to_vec());
if let Some(e) = list.get_mut(i) {
follow_transform(e, a);
}
}
out.map_or(Cow::Borrowed(effects), Cow::Owned)
}
/// `effects` without their geometry effects, each raster effect following the Transform effects
/// it loses ([`followed`]): what an object, or a fill or stroke, keeps once its geometry effects
/// are applied to its art.
pub fn without_geometry(effects: &[Effect]) -> Vec<Effect> {
followed(effects).iter().filter(|e| !crate::is_geometry(&e.id)).cloned().collect()
}
/// Make the raster effects of `effects`, all listed before Transform effect `t`, follow `t` as
/// [`followed`] makes them follow it, for art that applies its effects one at a time. `false`
/// when `t` leaves them as they are.
pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
let mut changed = false;
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
follow_transform(e, a);
changed = true;
}
changed
}
/// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the
/// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform
/// effect among them that makes copies or moves at random.
pub(crate) fn held_back(effects: &[Effect]) -> usize {
let Some(last) = effects.iter().rposition(|e| transform_step(e).is_none()) else { return 0 };
effects.get(..last).unwrap_or_default().iter().filter(|e| !crate::is_geometry(&e.id)).count()
}
/// Does `e` stop the raster effects listed before it from following the Transform effects after
/// it ([`followed`]): is it a visible Transform effect that makes copies or moves at random?
pub(crate) fn holds_back(e: &Effect) -> bool {
transform_step(e).is_none()
}
/// What `e` does to the raster effects listed before it ([`followed`]): the linear part of its map
/// when it is a visible Transform effect that moves the art once, the identity when it is no
/// Transform effect, is hidden or has Transform Objects off (the art stays where it is), and `None`
/// when it makes copies or moves at random.
fn transform_step(e: &Effect) -> Option<Affine> {
if e.id != "distort.transform" || !e.visible {
return Some(Affine::IDENTITY);
}
let p = merged_params(&e.id, &e.params);
if !flag(&p, "objects", true) {
return Some(Affine::IDENTITY);
}
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
}
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
/// around the art.
fn follows(id: &str) -> bool {
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
}
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
/// `a`. Effects that [`follows`] leaves out stay as they are.
fn follow_transform(e: &mut Effect, a: Affine) {
if !follows(&e.id) {
return;
}
let offset = (e.id == "stylize.dropShadow").then(|| {
let p = merged_params(&e.id, &e.params);
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
});
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
crate::scale_effect(e, k);
}
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
if !e.params.is_object() {
e.params = Value::Object(Map::new());
}
e.params["x"] = json!(o.x);
e.params["y"] = json!(o.y);
}
}
/// How far the visible raster effects of `effects` paint beyond `bounds`, the (effected)
/// geometry's, in document units. Geometry effects are accounted for by evaluating them.
pub fn outset(effects: &[Effect], bounds: Rect) -> f64 {
+550 -87
View File
@@ -12,7 +12,7 @@
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
//! them ([`image_rows`]).
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -590,7 +590,7 @@ fn as_art_opts(
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);
project_leaves(&mut art, &h, paint_doc);
}
// The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip
// group).
@@ -604,13 +604,33 @@ fn as_art_opts(
out.knockout = vectorcraft_doc::Knockout::Off;
out.knockout_shape = n.knockout_shape;
out.extras_mut().mask = n.extras().mask.clone();
out.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
out.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
Some(out)
}
/// Map every path under `art` (and its gradients) through the projective map `h`, curves split
/// finely enough to follow it.
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography) {
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
/// masks of the objects under it, through the projective map `h`, curves split finely enough to
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
/// first ([`outlined_members`], with the symbols of `doc`).
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
project_paths(art, h);
each_linked_mask_mut(art, false, 0, &mut |m| {
*m = outlined_mask_art(doc, m);
project_paths(m, h);
});
}
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
/// ([`outlined_members`]), and as art that keeps its look ([`as_art`]) when it is type itself.
fn outlined_mask_art(doc: Option<&Document>, art: &Node) -> Node {
match art.kind {
NodeKind::Text(_) => as_art(doc, art, None).unwrap_or_else(|| art.clone()),
_ => outlined_members(doc, art),
}
}
/// The paths of [`project_leaves`] outside the art of masks.
fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
let f = |p: vectorcraft_geom::Point| h.apply(p).unwrap_or(p);
let piece = art.geometric_bounds().map_or(1.0, |b| (b.width().max(b.height()) / 64.0).max(0.25));
let project = |path: &mut PathData| *path = vectorcraft_doc::live::map_nonlinear(path, piece, f);
@@ -687,58 +707,151 @@ fn hoist_copies(art: &mut Node) {
/// 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. A deferred live-effect
/// plug-in is listed by its index in `owner`, the effect list `fx` was taken from, or in `fx` when
/// `owner` does not hold it.
/// `owner` does not hold it. The art of the linked opacity masks of the objects in `art` (not of
/// `art` itself) takes each effect as the paths it masks do ([`Step::reshape_masks`]), with the
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
/// masks keeps its shape under that effect.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
}
let mut leaves_safe = true;
for_each_leaf(art, &mut |leaf| {
if !leaves_safe {
return;
}
if let Some((_, rule)) = leaf_geometry(leaf) {
let has_stroke = leaf.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
if rule != FillRule::NonZero || has_stroke {
leaves_safe = false;
}
}
});
let masked = has_linked_mask(art, false);
if masked {
each_linked_mask_mut(art, false, 0, &mut |m| *m = outlined_mask_art(doc, m));
}
let mut masks_safe = true;
each_linked_mask(art, false, 0, &mut |_, m| masks_safe &= leaves_safe(m));
let art_stroke = art.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
let style_safe = leaves_safe && !art_stroke;
let style_safe = leaves_safe(art) && masks_safe && !art_stroke;
let listed = fx;
let opt_fx = crate::geometry::optimize_geometry_effects(fx, style_safe);
let fx = opt_fx.as_slice();
let seed = art.id.0;
let mut used = art_cost(art);
each_linked_mask(art, false, 0, &mut |_, m| used = used.plus(art_cost(m)));
let max = budget.at_least(used);
// Read before the effects run: a path's own copies don't make it art of several objects.
// Read before the effects run: a path's own copies don't make it art of several objects. The
// same holds for the art of each mask, listed by the object it masks.
let copy_whole = copies_whole(art);
let mut wholes = HashMap::new();
each_linked_mask(art, false, 0, &mut |id, m| {
wholes.entry(id).or_insert_with(|| copies_whole(m));
});
let mut warped = WarpedImages::new();
for e in fx {
let Some(bounds) = warped.bounds(art) else { break };
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
if (ran.masks || ran.short)
&& let Some((was, cost)) = before
{
*art = was;
used = cost;
continue;
}
if let Some(carry) = ran.whole {
whole.push(carry);
}
}
cut_warped_images(art, &warped);
whole
}
/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its
/// merged params, the reference box and seed of the object's art, where a deferred live-effect
/// plug-in is listed, whether each Transform copy becomes an object, the document that the
/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks.
struct Step<'a> {
e: &'a Effect,
params: &'a serde_json::Value,
bounds: Rect,
seed: u64,
effect: Option<usize>,
apart: bool,
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
}
/// What [`Step::run`] did to a piece of art.
struct Ran {
/// A path in the art kept its shape (past the budget).
kept: bool,
/// The linked opacity mask of an object in the art stayed as it was while the paths it masks
/// took the effect, or could have ([`Step::reshape_masks`]).
masks: bool,
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
/// (past the budget or out of reach), where a linked mask could take a different number.
short: bool,
/// How what paints the art as a whole follows the effect, when it does.
whole: Option<crate::Carry>,
}
impl Ran {
/// Nothing in the art kept its shape or made fewer copies, and every linked mask in it moved.
fn complete(&self) -> bool {
!self.kept && !self.masks && !self.short
}
}
impl Step<'_> {
/// Run the effect over `art`, whose paths and those of the linked opacity masks in it keep to
/// `max` together with what they cost so far (`used`). `copy_whole` is [`copies_whole`] of the
/// art, or of a mask's art, before the first effect. `warped` lists the images Warp effects
/// bend in the art ([`WarpedImages`]); a mask's art has none. With `own`, `art` is the art of a
/// mask, and its own linked mask takes the effect too. `depth` counts the masks `art` is in. A
/// live-effect plug-in that paints its pieces leaves a mask's art, and art that holds objects
/// with linked masks, as they are and reports the masks as stayed: a mask can't take the
/// pieces as the art it masks does. So does a Warp effect that bends an image with a linked
/// mask.
#[allow(clippy::too_many_arguments)]
fn run(
&self,
art: &mut Node,
max: Budget,
used: &mut Budget,
copy_whole: bool,
mut warped: Option<&mut WarpedImages>,
own: bool,
depth: usize,
) -> Ran {
let (e, params, bounds, seed) = (self.e, self.params, self.bounds, self.seed);
let stayed = Ran { kept: false, masks: true, short: false, whole: None };
if let Some(plugin) = painted_plugin(e) {
let at = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
if own || has_linked_mask(art, false) {
return stayed;
}
let at = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
for_each_leaf(art, &mut |leaf| {
let Some((path, _)) = leaf_geometry(leaf) else { return };
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
if let Some(made) = paint_leaf(leaf, plugin, &params, bounds, room, doc, at) {
used = used.minus(before).plus(made);
if let Some(made) = paint_leaf(leaf, plugin, params, bounds, room, self.doc, at) {
*used = used.minus(before).plus(made);
}
});
continue;
return Ran { kept: false, masks: false, short: false, whole: None };
}
// A Warp effect that bends images ([`mark_warped_images`]) bends an image's pixels, not the
// art of its linked mask.
let warp = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id).filter(|_| crate::warp::bends(&e.id, params));
if warp.is_some() && has_masked_image(art) {
return stayed;
}
// Placed gradients follow a Transform effect, Free Distort and the Warp effects
// ([`crate::Carry`]): under Free Distort and Warp (`boxes`) each path's move and scale from
// its bounds before the effect to its bounds after it. Under those and the other effects,
// the placed gradients of type's outlines in `art` (`outline_text`) move and scale with
// the outlines' bounds.
let follows = crate::Carry::follows(&e.id, &params, bounds, seed);
let follows = crate::Carry::follows(&e.id, params, bounds, seed);
let boxes = follows && crate::Carry::by_bounds(&e.id);
let mut outlines = vec![];
if !follows || boxes {
@@ -754,30 +867,61 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
// The images earlier Warps bend are measured by their pieces only when a group's
// gradient needs the bounds.
if !groups.is_empty()
&& let Some(images) = warped.when_cut(art)
&& let Some(images) = warped.as_deref().and_then(|w| w.when_cut(art))
{
groups.clear();
group_marks(art, &mut vec![], &HashSet::new(), Some(images), &mut groups);
}
}
// The ids of the paths that kept their shape (past the budget), and their places in the
// order [`for_each_leaf`] visits the paths.
// order [`for_each_leaf`] visits the paths; and the ids of the paths whose linked masks
// moved with them as they were transformed as objects.
let mut kept_ids = HashSet::new();
let mut kept_leaves = HashSet::new();
let mut leaf_at = 0usize;
let mut moved_ids = HashSet::new();
let transform = (e.id == "distort.transform").then(|| {
let (m, copies) = crate::distort::transform_map(bounds, &params, seed);
let options = crate::distort::TransformOptions::of(&params);
(m, copies, options, crate::distort::transform_affine(bounds, &params, seed))
let (m, copies) = crate::distort::transform_map(bounds, params, seed);
let options = crate::distort::TransformOptions::of(params);
(m, copies, options, crate::distort::transform_affine(bounds, params, seed))
});
// In a mask's art, images and symbol instances take only a Transform effect
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
// it masks does.
if own && transform.is_none() && (is_placed(art) || placed_count(art) > 0) {
return Ran { kept: false, masks: true, short: false, whole: None };
}
// Art of several objects is copied whole, so the copies don't interleave member by member.
// The copies of its members carry their linked masks, moved with them.
if let Some((m, copies, options, _)) = transform
&& copies > 0
&& copy_whole
{
used = copy_art(art, m, copies, copy_scaling(options), max);
continue;
if !own {
*used = copy_art(art, m, copies, copy_scaling(options), max);
return Ran { kept: false, masks: false, short: false, whole: None };
}
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
// [`copy_art`] counts only the members.
let before = copy_cost(art);
let rest = used.minus(before).plus(art.extras().mask.as_deref().map_or(Budget { anchors: 0, lines: 0 }, |k| copy_cost(&k.art)));
let made = copy_art(art, m, copies, copy_scaling(options), max.minus(rest));
*used = rest.plus(made);
let short = art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
let none = HashSet::new();
let masks = self.reshape_own_mask(art, &Skip { moved: &none, kept: &none }, max, used, depth);
return Ran { kept: false, masks, short, whole: None };
}
// A shortfall in the copies matters for the objects a linked mask above them covers, which
// the mask would take a different number of copies than, and anywhere in a mask's art.
let watch = transform.is_some_and(|(_, copies, options, _)| copies > 0 && options.objects) && (own || has_linked_mask(art, false));
let mut covered = HashSet::new();
if watch && !own {
masked_ids(art, false, &mut covered);
}
let counts = |id: NodeId| watch && (own || covered.contains(&id));
let mut short = false;
for_each_leaf(art, &mut |leaf| {
let at = leaf_at;
leaf_at += 1;
@@ -790,36 +934,55 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
// strokes; a gradient paints each copy by itself, not the one piece the copies
// make together; and Expand Appearance (`apart`) makes each copy an object.
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
// Each copy of a path with a linked mask carries the mask, moved with it.
let separate = copies > 0
&& (apart
&& (self.apart
|| leaf.appearance.has_unplaced_gradient()
|| leaf.appearance.has_placed_gradient()
|| paints_copies_apart(&leaf.appearance, rule));
|| paints_copies_apart(&leaf.appearance, rule)
|| leaf.extras().mask.as_ref().is_some_and(|m| m.linked));
// The copies of a path replace it by a group of them, the path included.
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
used = used.minus(before).plus(made);
if !moved {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, None);
*used = used.minus(before).plus(made);
if moved {
// With Transform Objects off the path stays, and its mask takes the
// effect's stroke and pattern changes as its own art.
if options.objects {
moved_ids.insert(leaf.id);
}
short |= counts(leaf.id) && copied(leaf) <= copies;
} else {
kept_ids.insert(leaf.id);
}
return;
}
if separate {
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);
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
*used = used.minus(before).plus(made);
moved_ids.insert(leaf.id);
short |= counts(leaf.id) && copied(leaf) <= copies;
return;
}
}
let stage = effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
let Some(out) = apply_one(&e.id, &params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
let stage = self.effect.map(|effect| vectorcraft_plugins::deferred::Stage { object: seed, effect, item: None });
let Some(out) = apply_one(&e.id, params, &path, bounds, &GeomContext { seed, stage, ..GeomContext::of(leaf) }, room) else {
kept_ids.insert(leaf.id);
kept_leaves.insert(at);
return;
};
used = used.minus(before).plus(Budget::of(&out));
// A Transform effect's copies of a path are subpaths of it, each with the path's anchors.
if counts(leaf.id)
&& let Some((_, copies, _, _)) = transform
{
short |= out.anchor_count() < path.anchor_count().saturating_mul(copies.saturating_add(1));
}
*used = used.minus(before).plus(Budget::of(&out));
if follows && !boxes {
// A gradient fitted to the path fits the path's own bounds.
let carry = crate::Carry::of(&e.id, &params, bounds, path.bounds(), None, seed);
let carry = crate::Carry::of(&e.id, params, bounds, path.bounds(), None, seed);
if carry.moves(&leaf.appearance) {
carry.apply(&mut leaf.appearance);
}
@@ -832,36 +995,230 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
// Warp bends images too: each one's pixels follow the warp's map over the same box. The
// images are cut into pieces once, after the last effect ([`cut_warped_images`]). An image
// whose clipping frame kept its shape (past the budget) keeps its pixels as they are.
if let Some(style) = e.id.strip_prefix("warp.").and_then(crate::warp::WarpStyle::from_id)
&& crate::warp::bends(&e.id, &params)
if let Some(style) = warp
&& let Some(warped) = warped.as_deref_mut()
{
let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, &params));
let f: WarpMap = Rc::from(crate::warp::warp_map(bounds, style, params));
warped.reserve(art);
mark_warped_images(art, &f, &kept_leaves, false, &mut 0, &mut warped);
mark_warped_images(art, &f, &kept_leaves, false, &mut 0, warped);
}
if let Some((m, copies, options, _)) = transform
&& options.objects
{
transform_placed(art, m, copies);
// A mask's art that is one image or symbol instance is placed as the only member of a
// group of it.
let root = is_placed(art);
if root {
let id = art.id;
let one = std::mem::replace(art, Node::group(id, vec![]));
*art = Node::group(id, vec![Arc::new(one)]);
}
let placed = if watch { masked_placed(art, own) } else { 0 };
transform_placed(art, m, copies, copy_scaling(options));
short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1));
if root && let Some([one]) = art.children().map(Vec::as_slice) {
*art = (**one).clone();
}
}
if outlines.iter().any(Option::is_some) {
rebase_type_outlines(art, &mut outlines.into_iter());
}
// Under Transform copies, a mask takes the copies as the paths it masks do; the copies of a
// path with a mask of its own each carry it ([`copy_leaf`]).
let masks = self.reshape_masks(art, own, &Skip { moved: &moved_ids, kept: &kept_ids }, max, used, depth);
// What paints the art as a whole, and the own fills and strokes of the groups inside it,
// 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 images = if groups.is_empty() { None } else { warped.when_cut(art) };
let images = if groups.is_empty() { None } else { warped.as_deref().and_then(|w| w.when_cut(art)) };
let held = (!groups.is_empty() || !kept_ids.is_empty()) && group_marks(art, &mut vec![], &kept_ids, images, &mut after).1;
if !groups.is_empty() {
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, &params, bounds, from, to, seed));
carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed));
}
if follows && !held {
whole.push(crate::Carry::of(&e.id, &params, bounds, Some(bounds), warped.bounds(art), seed));
let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art));
let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed));
Ran { kept: !kept_ids.is_empty(), masks, short, whole }
}
/// Run the effect over the art of the linked opacity mask of `n` (with `own`) and of each path,
/// compound path, group and layer under it, with the art's reference box, as the paths the mask
/// covers take it: the mask moves and bends with what it masks. The mask of an object
/// transformed as an object moved with it already and is left as it is. A mask stays as it was
/// past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks, and for the reasons
/// [`Step::reshape_own_mask`] gives. Returns whether a mask stayed for one of those reasons.
fn reshape_masks(&self, n: &mut Node, own: bool, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
return false;
}
let mut stayed = own && self.reshape_own_mask(n, skip, max, used, depth);
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
for c in children.iter_mut() {
if has_linked_mask(c, true) {
stayed |= self.reshape_masks(Arc::make_mut(c), true, skip, max, used, depth);
}
}
}
stayed
}
/// Run the effect over the art of the linked opacity mask of `n` itself, when `n` is a path,
/// compound path, group or layer that `skip` does not list as moved. The mask stays as it was
/// when a path it masks kept its shape, and when its own art could not take the effect whole: a
/// path in it would keep its shape, its copies would stop short, or a mask inside it would stay
/// (no mask is left half moved). Returns whether the mask stayed for one of those reasons.
fn reshape_own_mask(&self, n: &mut Node, skip: &Skip, max: Budget, used: &mut Budget, depth: usize) -> bool {
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !reshapes_mask_of(n) || skip.moved.contains(&n.id) {
return false;
}
let stays = holds_any(n, skip.kept);
let id = n.id;
let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return false };
let before = *used;
let mut art = (*m.art).clone();
let whole = self.wholes.get(&id).copied().unwrap_or_else(|| copies_whole(&art));
let ran = (!stays).then(|| self.run(&mut art, max, used, whole, None, true, depth + 1));
match ran {
Some(ran) if ran.complete() => {
// What paints the mask's art as a whole follows the effect as the art does.
if let Some(carry) = ran.whole
&& carry.moves(&art.appearance)
{
carry.apply(&mut art.appearance);
}
m.art = Arc::new(art);
false
}
_ => {
*used = before;
true
}
}
}
cut_warped_images(art, &warped);
whole
}
/// The objects whose linked masks [`Step::reshape_masks`] leaves as they are: those transformed
/// as objects (`moved`), and those holding a path that kept its shape (`kept`).
struct Skip<'a> {
moved: &'a HashSet<NodeId>,
kept: &'a HashSet<NodeId>,
}
/// Is `n` an object whose linked opacity mask a geometry effect on the art it is in reshapes with
/// it: a path, compound path, group or layer? An image or symbol instance moves its mask only
/// with the map a Transform effect places it by ([`transform_placed`]).
fn reshapes_mask_of(n: &Node) -> bool {
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. })
}
/// Does `n` (with `own`) or a path, compound path, group or layer under it carry a linked opacity
/// mask that [`Step::reshape_masks`] reshapes?
fn has_linked_mask(n: &Node, own: bool) -> bool {
let mine = own && reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked);
mine || match &n.kind {
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_linked_mask(c, true)),
_ => false,
}
}
/// Run `f` on the id of `n` (with `own`) and of each path, compound path, group and layer under it
/// that carries a linked opacity mask, with the art of that mask, and on the masks inside that
/// art, as [`Step::reshape_masks`] reaches them: `depth` masks deep already, up to
/// [`vectorcraft_doc::depth::MAX_DEPTH`].
fn each_linked_mask(n: &Node, own: bool, depth: usize, f: &mut dyn FnMut(NodeId, &Node)) {
if depth >= vectorcraft_doc::depth::MAX_DEPTH {
return;
}
if own
&& reshapes_mask_of(n)
&& let Some(m) = n.extras().mask.as_deref().filter(|m| m.linked)
{
f(n.id, &m.art);
each_linked_mask(&m.art, true, depth + 1, f);
}
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &n.kind {
for c in children {
each_linked_mask(c, true, depth, f);
}
}
}
/// [`each_linked_mask`] that changes the art of each mask: `f` runs on a mask's art before the
/// masks inside it are reached.
fn each_linked_mask_mut(n: &mut Node, own: bool, depth: usize, f: &mut dyn FnMut(&mut Node)) {
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_linked_mask(n, own) {
return;
}
if own
&& reshapes_mask_of(n)
&& let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
{
let art = Arc::make_mut(&mut m.art);
f(art);
each_linked_mask_mut(art, true, depth + 1, f);
}
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } = &mut n.kind {
for c in children.iter_mut() {
if has_linked_mask(c, true) {
each_linked_mask_mut(Arc::make_mut(c), true, depth, f);
}
}
}
}
/// Does [`Step::reshape_masks`] reshape the linked opacity mask of `n` itself?
fn has_own_linked_mask(n: &Node) -> bool {
reshapes_mask_of(n) && n.extras().mask.as_ref().is_some_and(|m| m.linked)
}
/// Add to `out` the ids of the objects under `n` that the linked opacity mask of an object above
/// them covers (every one of them with `under`).
fn masked_ids(n: &Node, under: bool, out: &mut HashSet<NodeId>) {
for c in n.children().into_iter().flatten() {
if under {
out.insert(c.id);
}
masked_ids(c, under || has_own_linked_mask(c), out);
}
}
/// How many images and symbol instances under `n` the linked opacity mask of an object above them
/// covers (every one of them with `under`).
fn masked_placed(n: &Node, under: bool) -> usize {
n.children().into_iter().flatten().map(|c| usize::from(under && is_placed(c)) + masked_placed(c, under || has_own_linked_mask(c))).sum()
}
/// Is `n`, or anything under it, one of `ids`?
fn holds_any(n: &Node, ids: &HashSet<NodeId>) -> bool {
if ids.is_empty() {
return false;
}
let mut any = false;
n.walk(&mut |c| any |= ids.contains(&c.id));
any
}
/// Do the paths under `n` that [`for_each_leaf`] visits all fill by the non-zero rule without a
/// stroke that paints? Effects then reshape their outlines alike in any order that the
/// optimization of [`crate::geometry::optimize_geometry_effects`] takes.
fn leaves_safe(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => {
let has_stroke = n.appearance.stroke().is_some_and(|s| !s.paint.is_none() && s.width > 0.0);
leaf_geometry(n).is_none_or(|(_, rule)| rule == FillRule::NonZero && !has_stroke)
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().all(|c| leaves_safe(c)),
_ => true,
}
}
/// Is there an image with a linked opacity mask among the members of `n`, or among its groups'
/// and layers' members, which [`mark_warped_images`] walks?
fn has_masked_image(n: &Node) -> bool {
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return false };
children.iter().any(|c| match c.kind {
NodeKind::Image(_) => c.extras().mask.as_ref().is_some_and(|m| m.linked),
_ => has_masked_image(c),
})
}
/// Largest factor a Transform effect's Scale Strokes & Effects scales one object's strokes by
@@ -888,8 +1245,9 @@ fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::S
/// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its
/// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them
/// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform
/// Objects off the geometry stays and the options apply once. Returns what the leaf costs after,
/// and `false` when the path kept its shape because the moved path would pass `budget`.
/// Objects off the geometry stays and the options apply once. The effects `kept` names keep their
/// values on the leaf and on each copy ([`keep_listed`]). Returns what the leaf costs after, and
/// `false` when the path kept its shape because the moved path would pass `budget`.
fn transform_leaf(
leaf: &mut Node,
path: &PathData,
@@ -897,6 +1255,7 @@ fn transform_leaf(
copies: usize,
options: crate::distort::TransformOptions,
budget: Budget,
kept: Kept,
) -> (Budget, bool) {
let scaling = copy_scaling(options);
if !options.objects {
@@ -909,6 +1268,7 @@ fn transform_leaf(
if options.patterns {
vectorcraft_doc::pattern::transform_pattern_paints(leaf, m);
}
keep_listed(leaf, kept);
return (Budget::of(path), true);
}
if copies == 0 {
@@ -918,9 +1278,10 @@ fn transform_leaf(
return (Budget::of(path), false);
}
leaf.transform(m, scaling);
keep_listed(leaf, kept);
return (Budget::of(&moved), true);
}
(copy_leaf(leaf, path, m, copies, scaling, budget), true)
(copy_leaf(leaf, path, m, copies, scaling, budget, kept), true)
}
/// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a
@@ -1066,9 +1427,10 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::
/// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
/// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's
/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original
/// included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
/// strokes would scale past [`MAX_STROKE_SCALE`]. The effects `kept` names keep their values on
/// each copy, before its cost is counted ([`keep_listed`]). Returns what the copies cost, the
/// original included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget, kept: Kept) -> Budget {
let mut made = Budget::of(path).plus(effects_cost(leaf, path));
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
let mut xf = Affine::IDENTITY;
@@ -1081,8 +1443,11 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
}
let mut copy = leaf.clone();
copy.transform(xf, scaling);
keep_listed(&mut copy, kept);
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
let cost = Budget::of(&moved).plus(effects_cost(&copy, &moved));
let mut cost = Budget::of(&moved).plus(effects_cost(&copy, &moved));
// Each copy carries the art of its linked masks, moved with it.
each_linked_mask(&copy, true, 0, &mut |_, m| cost = cost.plus(art_cost(m)));
if !budget.fits(made.plus(cost)) || !copy.geometric_bounds().is_some_and(crate::distort::within_reach) {
break;
}
@@ -1225,9 +1590,12 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
/// effects. In paint order, each such fill or stroke is a path of its own: the leaf's geometry after
/// the geometry effects of that fill or stroke before its first such Transform effect, transformed
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
/// stroke's weight and dashes, the distances of its remaining effects and its pattern follow the
/// map. The reference box is that geometry's bounds and the seed is the leaf's id, as the renderer
/// draws a fill's or stroke's own effects. The geometry effects after the Transform effect then
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
/// pattern follow the map, and the raster effects before it that follow it take their followed
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
/// stroke's own effects. The geometry effects after the Transform effect then
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
/// 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`
@@ -1300,9 +1668,16 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let params = merged_params(&fx[at].id, &fx[at].params);
// Where each effect the piece keeps sits among the item's effects.
let kept: Vec<usize> = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect();
// A Transform effect after this one that makes copies or moves at random holds the raster
// effects before this one back from every Transform effect ([`crate::raster::followed`]).
let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back);
// The effects before the Transform effect that it keeps, each raster effect following the
// geometry effects before it ([`crate::raster::without_geometry`]) unless held back.
let kept_before: Vec<Effect> =
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(before) };
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();
let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest;
let mut one = Appearance { items: vec![it.clone()], ..Default::default() };
if carry.moves(&one) {
@@ -1324,7 +1699,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
@@ -1332,16 +1707,22 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(tb, &params, ctx.seed);
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 rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest.clone();
let mut p = piece(vec![it]);
if carry.moves(&p.appearance) {
carry.apply(&mut p.appearance);
}
set_geometry(&mut p, g.clone(), rule);
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
let after = kept_before.len();
let keep = |k: usize| k >= after || !options.objects;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, Some((&rest, &keep)));
*used = used.plus(made);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
let from = crate::raster::held_back(before);
if moved && !held_later {
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
}
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -1358,27 +1739,45 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). 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 effect, at the effect's own distances. A Transform effect with Transform Patterns or Scale
/// Strokes & Effects on transforms each path as [`transform_leaf`] does, and leaves the values of
/// the effects after it, and with Transform Objects off those before it, as they are
/// ([`keep_listed`]).
/// 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`. `(seed, source,
/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the
/// piece was made from, and the index among that item's effects of each effect the piece kept,
/// which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) {
/// for each piece it returns ([`paint_piece`]). The raster effects before a Transform effect
/// follow it ([`follow_piece`]), except the first `held` effects, which a Transform effect before
/// the piece's effects that makes copies or moves at random holds back, and the effects before
/// such a Transform effect among the piece's effects. 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`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the
/// fill or stroke the piece was made from, and the index among that item's effects of each effect
/// the piece kept, which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), held: usize, 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() {
count = count.max(item.effects().len());
}
});
// The effects before a Transform effect among the piece's effects that makes copies or moves at
// random are held back from the Transform effects before it too.
let mut held = held;
for_each_leaf(p, &mut |l| {
if let Some(last) = l.appearance.items.first().and_then(|item| item.effects().iter().rposition(crate::raster::holds_back)) {
held = held.max(last);
}
});
for j in 0..count {
let Some(bounds) = p.geometric_bounds() else { break };
let from = held.min(j);
let mut holds = false;
for_each_leaf(p, &mut |leaf| {
let Some(item) = leaf.appearance.items.first().cloned() else { return };
let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return };
holds |= crate::raster::holds_back(&e);
// The effects before this one as they were before it moved the path.
let was = item.effects().get(from..j).unwrap_or_default();
let Some((path, rule)) = leaf_geometry(leaf) else { return };
// What the other paths leave of the budget.
let before = Budget::of(&path);
@@ -1395,8 +1794,12 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
let (_, copies) = crate::distort::transform_map(bounds, &params, seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(bounds, &params, seed);
let (made, _) = transform_leaf(leaf, &path, map, copies, options, room);
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, Some((item.effects(), &keep)));
*used = used.minus(before).plus(made);
if moved {
follow_piece(leaf, was, from, &e);
}
return;
}
let appearance = leaf.appearance.clone();
@@ -1413,7 +1816,11 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
carry.apply(&mut leaf.appearance);
}
set_geometry(leaf, out, rule);
follow_piece(leaf, was, from, &e);
});
if holds {
held = held.max(j);
}
}
for_each_leaf(p, &mut |leaf| {
for item in &mut leaf.appearance.items {
@@ -1422,6 +1829,53 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
});
}
/// The effects a Transform effect in a fill's or stroke's own list leaves as they were
/// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its
/// indices keep their values. `None` for an object's own Transform effect.
type Kept<'a> = Option<(&'a [Effect], &'a dyn Fn(usize) -> bool)>;
/// Put back on the fills and strokes of each path under `p` the effect `kept`'s list holds at each
/// index it takes, in place of what a Transform effect in their own list scaled or moved with its
/// options ([`transform_leaf`]). The effects after the Transform effect apply to the art it made,
/// and with Transform Objects off the effects before it keep their values too. A piece's fills and
/// strokes share one list: a live-effect plug-in that paints what it returns gives each paint a copy
/// of the fill or stroke ([`vectorcraft_plugins::painted::items`]).
fn keep_listed(p: &mut Node, kept: Kept) {
let Some((was, keep)) = kept else { return };
for_each_leaf(p, &mut |leaf| {
for item in &mut leaf.appearance.items {
for (k, (e, old)) in item.effects_mut().iter_mut().zip(was).enumerate() {
if keep(k) {
e.clone_from(old);
}
}
}
});
}
/// Make the raster effects of each of `leaf`'s fills and strokes from index `from` on follow
/// Transform effect `t`, listed after them, once `t` has moved the leaf
/// ([`crate::raster::follow_one`]). The fills and strokes are copies of one fill or stroke (those a
/// painted plug-in returns, [`vectorcraft_plugins::painted::items`]), with the same effects. `was`
/// holds those effects of the first one as they were before `t` was applied: each one that
/// follows takes the value [`crate::raster::followed`] gives it, in place of what Scale Strokes &
/// Effects made of it, and the others keep theirs.
fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
let mut follow = was.to_vec();
if !crate::raster::follow_one(&mut follow, t) {
return;
}
for item in &mut leaf.appearance.items {
for (k, (new, old)) in follow.iter().zip(was).enumerate() {
if new != old
&& let Some(e) = item.effects_mut().get_mut(from + k)
{
*e = new.clone();
}
}
}
}
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
/// order. A group inside one of them is part of it.
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
@@ -1622,17 +2076,20 @@ fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine {
/// Apply the Transform effect's map `m` to every image and symbol instance under `n`, as
/// [`for_each_leaf`] does to paths: the map goes into the object's placement, and `copies` more
/// follow, each mapped once more than the last. Without copies the object itself takes the map,
/// as a path does.
fn transform_placed(n: &mut Node, m: Affine, copies: usize) {
transform_placed_within(n, m, copies, crate::distort::MAX_COPY_OBJECTS)
/// as a path does. The art of each one's linked opacity mask takes the map with `scaling`, as a
/// path's mask does.
fn transform_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling) {
let mut room = crate::distort::MAX_COPY_OBJECTS.saturating_sub(placed_count(n));
copy_placed(n, m, copies, scaling, &mut room);
}
/// [`transform_placed`] whose copies make at most `max` image and symbol instance nodes of the art,
/// the originals included: each copy adds the object once more, and a Transform after this one
/// copies the lot again, so copies stop where the result would pass `max` (#2042).
#[cfg(test)]
pub(crate) fn transform_placed_within(n: &mut Node, m: Affine, copies: usize, max: usize) {
let mut room = max.saturating_sub(placed_count(n));
copy_placed(n, m, copies, &mut room);
copy_placed(n, m, copies, vectorcraft_doc::Scaling::default(), &mut room);
}
/// Rows and columns of the pieces a Warp effect cuts an image into (VectorCraft's own number).
@@ -1864,11 +2321,11 @@ fn is_placed(n: &Node) -> bool {
/// document order, each copy taking one from `room` (what the art can still grow by), until the
/// budget is full. As with a path, the copies stop before one reaches past
/// [`crate::distort::within_reach`].
fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, room: &mut usize) {
let Some(children) = n.children_mut() else { return };
for c in children.iter_mut() {
if !is_placed(c) {
copy_placed(Arc::make_mut(c), m, copies, room);
copy_placed(Arc::make_mut(c), m, copies, scaling, room);
continue;
}
let src = (**c).clone();
@@ -1887,6 +2344,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, room: &mut usize) {
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
one.appearance.transform_gradients(xf);
}
// So does the art of its linked opacity mask.
if xf != Affine::IDENTITY
&& let Some(m) = one.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked)
{
Arc::make_mut(&mut m.art).transform(xf, scaling);
}
one
};
if copies == 0 {
+61 -12
View File
@@ -8,7 +8,9 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, L
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds};
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -507,6 +509,60 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
Ok(out)
}
/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol
/// instances, blends and clipping groups already resolved), in document coordinates: with the
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for
/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in
/// after a fill's or stroke's Revolve are looked up in `doc`.
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
let faces = |path: &PathData, b: Rect, options: Revolve| -> Result<Vec<PathData>, String> {
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect())
};
if is_container(n) {
let index = n
.appearance
.effects
.iter()
.position(|e| e.visible && is_revolve(&e.id))
.ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let mut shapes = members(n, "Revolve")?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, fx_options(fx))?;
let mut out = vec![];
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, options)?);
}
return Ok(out);
}
let (path, _) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
if surface_item(&solid_paints(n)).is_none() {
return Err("the revolved object has no fill or stroke".into());
}
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
return faces(&path, b, fx_options(fx));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id))
&& let Some(fx) = item.effects().get(index)
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&p, b, fx_options(fx))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let index = n
@@ -558,17 +614,11 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(surface));
// Later geometry acts on the projected art as a whole through container evaluation.
remaining = n
.appearance
.effects
.iter()
.enumerate()
.filter(|(i, e)| !is_revolve(&e.id) && (!is_geometry(&e.id) || *i > index))
.map(|(_, e)| e.clone())
.collect();
remaining = past_effect(&n.appearance.effects, index);
remaining.retain(|e| !is_revolve(&e.id));
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining.retain(|e| !is_geometry(&e.id));
remaining = crate::without_geometry(&remaining);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
@@ -835,8 +885,7 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
// One shadow for every member's surface, behind them all.
let mut children = children;
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
+21 -11
View File
@@ -22,6 +22,9 @@ pub(crate) use source::{resolve, resolve_for};
pub(crate) mod shadow;
pub(crate) mod wireframe;
pub use wireframe::three_d_wireframe_in;
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
@@ -978,17 +981,10 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = n
.appearance
.effects
.iter()
.enumerate()
.filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index))
.map(|(_, e)| e.clone())
.collect();
remaining = past_effect(&n.appearance.effects, index);
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
remaining = crate::without_geometry(&n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in &paints {
@@ -1024,14 +1020,28 @@ fn group_solid_art(n: &Node) -> Option<Node> {
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(n, fx, &shapes)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
Some(art)
}
/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the
/// art it projects. Each raster effect before it follows the Transform effects among those
/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at
/// random ([`crate::raster::holds_back`]); the effects after it stay as they are.
pub(crate) fn past_effect(effects: &[Effect], index: usize) -> Vec<Effect> {
let (before, after) = effects.split_at(index.min(effects.len()));
let after = after.get(1..).unwrap_or_default();
let kept: Vec<Effect> = if after.iter().any(crate::raster::holds_back) {
before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect()
} else {
crate::without_geometry(before)
};
kept.into_iter().chain(after.iter().cloned()).collect()
}
/// One solid of a 3D object as a mesh, with the color it is painted.
#[derive(Clone, Debug, PartialEq)]
pub struct SolidMesh {
+276
View File
@@ -0,0 +1,276 @@
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
//! can be edited on their own.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
use vectorcraft_three_d::Facet;
use super::{
INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile,
region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options,
};
use crate::{GeomContext, is_geometry};
/// The most distinct edges one object's wireframe may have.
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
/// The grid points are rounded to before edges are compared, in points: two faces that share an
/// edge give it once.
const GRID: f64 = 1.0 / 1024.0;
const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)";
/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D
/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as
/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path;
/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry
/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a
/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D
/// effect, when its solids can't be built, when the canvas draws the source art in their place, when
/// they draw no face, or past [`MAX_WIRE_EDGES`] edges.
pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if !crate::has_revolve(n) && !has_solid(n) {
return Err(NO_EFFECT.into());
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
// The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries
// it first). When neither draws, past their limits, the canvas shows the source art and there
// is no surface to expand.
let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some();
if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) {
// The builders' own error says why, when there is one. Revolve's art is cut for Revolve,
// as the canvas cuts it.
if crate::has_revolve(n) {
crate::revolve::revolve_face_paths(doc, &*resolve_for(doc, n, label, false)?)?;
} else {
solid_face_paths(doc, &*resolve(doc, n, label)?)?;
}
return Err(format!("{label} draws the source art for this object instead of its 3D surface"));
}
// Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas
// cuts it ([`crate::revolve_art_in`]).
let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? };
let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces = after_geometry(doc, n, faces, revolve);
let wire = edges(&faces)?;
if wire.is_empty() {
return Err(format!("{label} draws no faces for this object"));
}
Ok(wire)
}
/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them
/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude &
/// Bevel, Inflate or Rotate.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<PathData>, revolve: bool) -> Vec<PathData> {
let fx = &n.appearance.effects;
let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) };
let Some(index) = drawn else { return faces };
reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
}
/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as
/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect
/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep
/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform,
/// and the document.
pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext) -> Vec<PathData> {
let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
if after.is_empty() {
return faces;
}
let id = NodeId(ctx.seed);
let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect());
crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc);
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect
/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer,
/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect
/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`.
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if is_container(n) {
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let mut shapes = members(n, label_of(&fx.id))?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
return facet_paths(fx, &shapes);
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's
/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out,
/// as it is left out of the drawn art.
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
let label = label_of(&fx.id);
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
let p = crate::merged_params(&fx.id, &fx.params);
let mut out = vec![];
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (area, rule) = region(&s.path, s.rule, item);
out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path));
}
}
return Ok(out);
}
let (parts, bounds) = solid_parts(shapes, b);
let built: Vec<Result<Vec<Facet>, String>> = if fx.id == INFLATE {
let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect();
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
} else {
parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect()
};
for ((item, ..), f) in parts.iter().zip(built) {
match f {
Ok(f) => out.extend(f.iter().map(Facet::path)),
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
}
}
Ok(out)
}
/// A point on the [`GRID`].
type Snap = (i64, i64);
fn snap(p: Point) -> Snap {
((p.x / GRID).round() as i64, (p.y / GRID).round() as i64)
}
fn reversed(c: CubicBez) -> CubicBez {
CubicBez::new(c.p3, c.p2, c.p1, c.p0)
}
/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]).
pub(crate) fn edges(faces: &[PathData]) -> Result<Vec<PathData>, String> {
let mut seen: HashSet<[Snap; 4]> = HashSet::new();
let mut segments: Vec<CubicBez> = vec![];
for sp in faces.iter().flat_map(|f| &f.subpaths) {
for i in 0..sp.segment_count() {
let mut c = sp.segment(i);
if sp.segment_is_line(i) {
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
}
if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
continue;
}
let key = [c.p0, c.p1, c.p2, c.p3].map(snap);
// A segment that starts and ends on one grid point with its handles there too draws nothing.
if key.iter().all(|k| *k == key[0]) {
continue;
}
let back = [key[3], key[2], key[1], key[0]];
if seen.contains(&back) || !seen.insert(key) {
continue;
}
if segments.len() >= MAX_WIRE_EDGES {
return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges"));
}
segments.push(c);
}
}
Ok(chain(&segments))
}
/// `segments` joined end to end: each path starts at the first segment not yet used and takes in
/// the unused segments that meet its ends until none is left at either end, or it closes.
fn chain(segments: &[CubicBez]) -> Vec<PathData> {
let mut at: HashMap<Snap, Vec<usize>> = HashMap::new();
for (i, c) in segments.iter().enumerate() {
at.entry(snap(c.p0)).or_default().push(i);
if snap(c.p3) != snap(c.p0) {
at.entry(snap(c.p3)).or_default().push(i);
}
}
let mut used = vec![false; segments.len()];
// The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it.
let mut take = |used: &mut Vec<bool>, point: Snap, leave: bool| -> Option<CubicBez> {
let list = at.get_mut(&point)?;
while let Some(&i) = list.last() {
if used.get(i).copied().unwrap_or(true) {
list.pop();
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let c = *segments.get(i)?;
let starts = snap(c.p0) == point;
return Some(if starts == leave { c } else { reversed(c) });
}
None
};
let mut out = vec![];
for (i, first) in segments.iter().enumerate() {
if used.get(i).copied().unwrap_or(true) {
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let mut run: VecDeque<CubicBez> = VecDeque::from([*first]);
// A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment
// that comes back to its start stays open, with its two ends on one point.
let closes = |run: &VecDeque<CubicBez>| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3));
while !closes(&run) {
let Some(end) = run.back().map(|c| snap(c.p3)) else { break };
let Some(c) = take(&mut used, end, true) else { break };
run.push_back(c);
}
while !closes(&run) {
let Some(start) = run.front().map(|c| snap(c.p0)) else { break };
let Some(c) = take(&mut used, start, false) else { break };
run.push_front(c);
}
out.push(PathData::single(subpath(&run, closes(&run))));
}
out
}
/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor.
fn subpath(run: &VecDeque<CubicBez>, closed: bool) -> SubPath {
let mut anchors: Vec<Anchor> = vec![];
if let Some(first) = run.front() {
let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 };
anchors.push(Anchor::with_handles(first.p0, h_in, first.p1));
}
for (k, c) in run.iter().enumerate() {
let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1);
anchors.push(Anchor::with_handles(c.p3, c.p2, h_out));
}
// A closed run's last anchor is its first, whose in handle already comes from the last segment.
if closed {
anchors.pop();
}
SubPath::new(anchors, closed)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,235 @@
use serde_json::{Value, json};
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId};
use vectorcraft_geom::{BezPath, Rect};
use super::*;
fn square(x: f64, y: f64, size: f64) -> PathData {
let mut b = BezPath::new();
b.move_to((x, y));
b.line_to((x + size, y));
b.line_to((x + size, y + size));
b.line_to((x, y + size));
b.close_path();
PathData::from_bezpath(&b)
}
/// A filled 100 pt square without a stroke, with effect `id` and `params`.
fn solid_square(id: &str, params: Value) -> Node {
let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
n
}
/// Every segment of `wire`, each as its two ends on the grid.
fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> {
wire.iter()
.flat_map(|p| &p.subpaths)
.flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i)))
.map(|c| (snap(c.p0), snap(c.p3)))
.collect()
}
fn bounds(paths: &[PathData]) -> Rect {
paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
/// The paths of the faces `art` draws (every leaf of the art).
fn face_paths(art: &Node) -> Vec<PathData> {
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
#[test]
fn two_faces_that_share_an_edge_give_it_once() {
let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap();
let segs = segments(&wire);
assert_eq!(segs.len(), 7, "{segs:?}");
for (i, a) in segs.iter().enumerate() {
for b in segs.iter().skip(i + 1) {
assert!(a != b && (a.1, a.0) != *b, "{a:?} twice");
}
}
}
#[test]
fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() {
let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap();
assert_eq!(wire.len(), 1);
assert!(wire[0].subpaths[0].closed);
assert_eq!(wire[0].subpaths[0].anchors.len(), 4);
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0));
b.close_path();
let wire = edges(&[PathData::from_bezpath(&b)]).unwrap();
let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i)));
assert!(curved, "{wire:?}");
}
/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on
/// one point, since a path of one anchor has no segment.
#[test]
fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() {
let p = Point::new(0.0, 0.0);
let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)];
let face = PathData::single(SubPath::new(anchors, false));
assert_eq!(face.subpaths[0].segment_count(), 1);
let wire = edges(&[face]).unwrap();
assert_eq!(wire.len(), 1);
let sp = &wire[0].subpaths[0];
assert_eq!(sp.segment_count(), 1, "{sp:?}");
assert!(!sp.segment_is_line(0));
}
#[test]
fn edges_without_length_or_with_non_finite_points_are_left_out() {
let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false));
let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false));
assert!(edges(&[point, bad]).unwrap().is_empty());
assert!(edges(&[]).unwrap().is_empty());
}
#[test]
fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert_eq!(segments(&wire).len(), 9, "{wire:?}");
// The wireframe covers what the effect draws, in the same place.
let art = super::super::solid_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
}
#[test]
fn the_classic_wireframe_surface_expands_to_all_twelve_edges() {
let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"}));
assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12);
}
#[test]
fn revolve_inflate_and_rotate_expand_too() {
for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] {
let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}"));
assert!(!wire.is_empty(), "{id}");
assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}");
}
// Rotate is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same
/// place.
#[test]
fn revolve_classic_and_rotate_classic_expand_too() {
let n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert!(!wire.is_empty());
let art = crate::revolve_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
// On a fill, with a geometry effect after it.
let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap());
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}");
// Rotate (Classic) is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face
/// of the drawn surface: two faces that touch stay two outlines.
#[test]
fn later_geometry_effects_reshape_each_face_on_its_own() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()];
let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n));
assert_eq!(out.len(), 2, "{out:?}");
let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap());
assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}");
assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}");
}
/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface.
#[test]
fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let mut n = solid_square(id, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}");
}
}
/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only
/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again.
#[test]
fn a_geometry_effect_before_the_drawn_3d_effect_is_not_applied_again() {
let mut n = solid_square(crate::REVOLVE, json!({}));
n.appearance.effects.insert(0, crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
let alone = bounds(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.insert(0, crate::new_effect(super::super::EXTRUDE, &json!({})).unwrap());
let both = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((both.x0 - alone.x0).abs() < 1e-6 && (both.x1 - alone.x1).abs() < 1e-6, "{alone:?} {both:?}");
}
/// A clipping group with Revolve and Rotate draws Revolve, which cuts the art's fills as one piece
/// in the top fill's place. Its wireframe is cut the same way, so art with more fills than a 3D
/// effect takes members still expands, to the edges of Revolve alone.
#[test]
fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
let mut art = Node::path(NodeId(3), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let fill = art.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
art.appearance.items = vec![fill; super::super::MAX_MEMBERS + 4];
let mut clip = Node::path(NodeId(2), square(100.0, 100.0, 50.0), Appearance::default());
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let mut n = Node::new(NodeId(1), vectorcraft_doc::NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true });
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({})).unwrap());
let alone = segments(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
assert!(crate::revolve_art_in(None, &n).is_some(), "the canvas draws Revolve");
let both = segments(&three_d_wireframe_in(None, &n).unwrap());
assert_eq!(both, alone);
}
#[test]
fn an_object_without_a_visible_3d_effect_is_an_error() {
let mut n = solid_square(super::super::EXTRUDE, json!({}));
n.appearance.effects[0].visible = false;
assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect"));
n.appearance.effects.clear();
assert!(three_d_wireframe_in(None, &n).is_err());
}
+21 -11
View File
@@ -4,7 +4,8 @@
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]).
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
//! custom heads, whose stroke ends halfway along their length.
use std::borrow::Cow;
@@ -37,8 +38,14 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
let last = subs.last().filter(|s| !s.1).map(|s| s.0.clone());
let cap = cap_extent(st.cap, st.width);
let (hw0, hw1) = (st.arrow_weight(false), st.arrow_weight(true));
let start = st.start_arrow.zip(first).map(|(k, r)| (k, r, inset(k, hw0, cap)));
let end = st.end_arrow.zip(last).map(|(k, r)| (k, r, inset(k, hw1, cap)));
let start = st.start_arrow.clone().zip(first).map(|(k, r)| {
let i = inset(&k, hw0, cap);
(k, r, i)
});
let end = st.end_arrow.clone().zip(last).map(|(k, r)| {
let i = inset(&k, hw1, cap);
(k, r, i)
});
if start.is_none() && end.is_none() {
return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] };
}
@@ -56,7 +63,8 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
} else {
(end_pt + outward * inset, outward)
};
heads.push(Arrow { kind, outline: shape(kind, tip, dir, hw), tip, dir, inset });
let outline = shape(&kind, tip, dir, hw);
heads.push(Arrow { kind, outline, tip, dir, inset });
};
if let Some((k, r, i)) = start {
place(k, r, true, i, hw0);
@@ -181,12 +189,12 @@ pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) {
return (0.0, 0.0);
}
let cap = cap_extent(st.cap, st.width);
let inset_of = |kind: Option<Arrowhead>, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(st.start_arrow, false), inset_of(st.end_arrow, true))
let inset_of = |kind: &Option<Arrowhead>, end: bool| kind.as_ref().map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(&st.start_arrow, false), inset_of(&st.end_arrow, true))
}
/// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end.
fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
fn inset(kind: &Arrowhead, hw: f64, cap: f64) -> f64 {
let l = len(hw);
// Solid heads: halfway in, far enough that the cap stays behind the tip.
let solid = |back: f64| (back / 2.0).max(cap);
@@ -199,6 +207,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l),
// The inner corner of the chevron: arm / sin(half angle).
Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap),
Arrowhead::Custom(c) => (c.stop() * hw).max(cap),
_ => match local_stop(kind) {
Stop::At(u) => (u * hw).max(cap),
Stop::Wall(back) => hollow(back * hw),
@@ -207,7 +216,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
}
/// Outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along `dir`.
fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
fn shape(kind: &Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
let n = Vec2::new(-dir.y, dir.x);
let l = len(hw);
let half = l / 2.0;
@@ -265,7 +274,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
fn local_stop(kind: &Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
Arrowhead::HexagonOpen => Stop::Wall(HEX),
@@ -288,8 +297,8 @@ fn local_stop(kind: Arrowhead) -> Stop {
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
/// is generated here, and a custom head's outline is its own.
fn local(kind: &Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0));
@@ -385,6 +394,7 @@ fn local(kind: Arrowhead) -> BezPath {
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+4
View File
@@ -134,6 +134,10 @@ impl Plan {
fn fitted(mut segs: Vec<PathSeg>, mut lens: Vec<f64>, closed: bool, period: f64) -> Self {
let n = segs.len();
// A subpath with no segments (a lone moveto) has no runs to fit.
if n == 0 {
return Self::exact(segs, lens, closed, period);
}
// Corners: where segments with length meet at a kink (zero-length ones have no direction).
let live: Vec<usize> = (0..n).filter(|&i| lens[i] > EPS).collect();
let mut corners: Vec<usize> = live.windows(2).filter(|w| kink(&segs[w[0]], &segs[w[1]])).map(|w| w[1]).collect();
+61 -12
View File
@@ -32,6 +32,12 @@ const SHARP: f64 = 1.25;
const HAIRPIN: f64 = 4.0;
/// Rows of a mesh across the stroke (more where the gradient has stops).
const MESH_ROWS: usize = 16;
/// The most stops of the gradient [`gradient_meshes`] puts rows or columns at
/// ([`Gradient::fitted`]: past it, the stops that change the colors least are left out).
pub(crate) const MAX_MESH_STOPS: usize = 1024;
/// The most points of one mesh [`gradient_meshes`] makes, unless a single pair of ribs needs more:
/// a subpath with more ribs than leave room for a row at each stop becomes several meshes.
pub(crate) const MAX_MESH_POINTS: usize = 1 << 20;
/// The most of a subpath one column of a mesh along the stroke spans.
const MESH_STEP: f64 = 1.0 / 32.0;
/// The most of a subpath one slice spans while a width profile shapes the across gradient.
@@ -367,9 +373,12 @@ pub struct Slice {
}
impl Slice {
/// The slice's paint: its piece of `g` as a linear gradient placed from `from` to `to`.
pub fn paint(&self, g: &Gradient) -> Paint {
let gradient = g.span(self.span.0 as f32, self.span.1 as f32);
/// The slice's paint: its piece of `unrolled` as a linear gradient placed from `from` to `to`.
/// `unrolled` is the stroke's gradient as [`Gradient::unrolled`] gives it (unrolled once for
/// all the slices), so one that repeats or reflects runs its stops that many times along (or
/// across) the stroke.
pub fn paint(&self, unrolled: &Gradient) -> Paint {
let gradient = unrolled.span(self.span.0 as f32, self.span.1 as f32);
let end = if self.from.distance(self.to) > 1e-9 { self.to } else { self.from + Vec2::new(1.0, 0.0) };
let geom = GradientGeom { start: self.from, end, aspect: 1.0, focal: None };
Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), angle: geom.angle_deg(), ..GradientPaint::new(gradient) }))
@@ -471,40 +480,72 @@ pub fn written_slices(bp: &BezPath, rule: FillRule, st: &StrokeLayer, outlines:
_ => vectorcraft_pathops::stroke_region(outlines).to_bezpath(),
};
let grow = if g.stops.iter().all(|s| s.opacity >= 1.0) { SLICE_GROW } else { 0.0 };
let unrolled = g.unrolled();
let slices = gradient_slices(bp, rule, st, SLICE_TOL, SLICE_MARGIN, grow)
.into_iter()
.map(|s| {
let paint = s.paint(g);
let paint = s.paint(&unrolled);
(s.shape, paint)
})
.collect();
Some(WrittenSlices { clip, slices })
}
/// How far before and after a sharp step between two colors (two stops at one offset, as a
/// gradient that repeats has where one run meets the next) [`mesh_marks`] puts a mesh row or
/// column, as a fraction of the gradient's length.
const STEP_GAP: f64 = 1e-4;
/// Where along gradient `g` (0 to 1) Outline Stroke's mesh puts a row or column for its stops
/// ([`Gradient::expanded_stops`]): at each stop, and for two stops at one offset (a sharp step,
/// or where a reflecting gradient turns back) also [`STEP_GAP`] before and after it, so the mesh
/// takes the color on each side.
fn mesh_marks(g: &Gradient) -> Vec<f64> {
let offsets: Vec<f64> = g.expanded_stops().iter().map(|s| f64::from(s.0)).collect();
let shared = |i: usize| {
let t = offsets.get(i).copied().unwrap_or(0.0);
let near = |j: Option<usize>| j.and_then(|j| offsets.get(j)).is_some_and(|&u| (u - t).abs() < 1e-6);
near(i.checked_sub(1)) || near(i.checked_add(1))
};
let mut out = Vec::with_capacity(offsets.len() + 2);
for (i, &t) in offsets.iter().enumerate() {
out.push(t);
if shared(i) {
out.extend([(t - STEP_GAP).max(0.0), (t + STEP_GAP).min(1.0)]);
}
}
out
}
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
/// stroke's outline), coloured as [`gradient_slices`] paint it.
/// stroke's outline), coloured as [`gradient_slices`] paint it. The gradient's stops are fitted to
/// [`MAX_MESH_STOPS`], and a subpath whose mesh would hold more than [`MAX_MESH_POINTS`] points is
/// split into meshes of fewer ribs ([`rib_pieces`]).
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
let fitted = g.fitted(MAX_MESH_STOPS);
let across = st.gradient_mode == StrokeGradientMode::Across;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
let marks: Vec<f64> = if across { vec![] } else { g.expanded_stops().iter().map(|s| s.0 as f64).collect() };
let marks: Vec<f64> = if across { vec![] } else { mesh_marks(&fitted) };
let max_dt = match (across, st.profile.is_some()) {
(false, _) => MESH_STEP,
(true, true) => PROFILE_STEP,
(true, false) => 1.0,
};
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
let mut us: Vec<f64> = if across {
(0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(g.expanded_stops().iter().map(|s| s.0 as f64)).collect()
} else {
vec![0.5]
};
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(mesh_marks(&fitted)).collect() } else { vec![0.5] };
us.sort_by(f64::total_cmp);
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let us = &us;
let g = &*fitted;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
// A mesh is a point for each row (and its two edges) on each rib: a strip with more ribs than
// that leaves room for is split into meshes of fewer ribs.
let per_mesh = MAX_MESH_POINTS / (us.len() + 2);
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
.into_iter()
.filter(|ribs| ribs.len() > 1)
.flat_map(|ribs| rib_pieces(ribs.len(), per_mesh).into_iter().map(move |r| ribs.get(r).unwrap_or_default().to_vec()))
.map(|ribs| {
let (rows, cols) = (us.len() + 1, ribs.len() - 1);
// Each level across: a point on each rib and the gradient position there.
@@ -541,3 +582,11 @@ pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradi
})
.collect()
}
/// The ribs (index ranges of `n`, at least two) of each mesh [`gradient_meshes`] makes of a strip:
/// at most `per_mesh` ribs each (at least two), each starting on the last rib of the one before,
/// so the meshes meet without a gap.
pub(crate) fn rib_pieces(n: usize, per_mesh: usize) -> Vec<std::ops::Range<usize>> {
let per_mesh = per_mesh.max(2);
(0..n.saturating_sub(1)).step_by(per_mesh - 1).map(|start| start..(start + per_mesh).min(n)).collect()
}
+5 -5
View File
@@ -280,7 +280,7 @@ fn no_heads_borrows_the_path_and_closed_paths_get_none() {
#[test]
fn tip_mode_shortens_the_stroke_by_the_head_and_puts_the_tip_on_the_end_point() {
for kind in Arrowhead::ALL {
let st = arrows(kind, ArrowAlign::Tip, LineCap::Butt);
let st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Butt);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let [h] = &p.heads[..] else { panic!("one head") };
@@ -335,7 +335,7 @@ fn extend_mode_keeps_the_path_and_overhangs_by_the_inset() {
#[test]
fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
for (kind, cap) in [(Arrowhead::CircleOpen, LineCap::Round), (Arrowhead::SquareOpen, LineCap::Square), (Arrowhead::TriangleOpen, LineCap::Butt)] {
let st = arrows(kind, ArrowAlign::Tip, cap);
let st = arrows(kind.clone(), ArrowAlign::Tip, cap);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let h = &p.heads[0];
@@ -361,7 +361,7 @@ fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
fn round_caps_never_poke_past_the_tip() {
for kind in Arrowhead::ALL {
for scale in [10.0, 100.0, 300.0] {
let mut st = arrows(kind, ArrowAlign::Tip, LineCap::Round);
let mut st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Round);
st.arrow_scale = (scale, scale);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
@@ -403,8 +403,8 @@ fn degenerate_paths_and_patterns_neither_panic_nor_hang() {
for pat in patterns {
for off in [0.0, -7.0, 1e12, f64::INFINITY] {
let st = stroke(2.0, |s| {
s.start_arrow = Some(kind);
s.end_arrow = Some(kind);
s.start_arrow = Some(kind.clone());
s.end_arrow = Some(kind.clone());
s.arrow_align = align;
s.cap = cap;
s.dash = Some(dashed(pat, off));
+29 -2
View File
@@ -50,7 +50,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0));
assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself");
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
@@ -73,7 +73,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
#[test]
fn the_stroke_ends_inside_every_head() {
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
// Just in front of where the line stops, on its centre line.
let end = h.tip - h.dir * (h.inset - 0.1);
assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset);
@@ -112,3 +112,30 @@ fn half_arrows_barb_on_their_own_side() {
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5);
assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0);
}
#[test]
fn custom_heads_draw_their_own_art_at_the_tip() {
use vectorcraft_doc::CustomArrowhead;
use vectorcraft_geom::{PathData, SubPath};
// From the tip back 3 units, 2 to the right of the line and 1 to the left.
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
let kind = Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), wedge)));
let h = head(kind.clone());
// Weight 2: drawn back to x 94, right of +x is +y on a y-down page.
let b = h.outline.bounding_box();
assert!((b.x0 - 94.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.y1 - 4.0).abs() < 1e-9, "{b:?}");
assert_eq!(h.outline.winding(Point::new(95.0, 1.0)), h.outline.winding(Point::new(95.0, 0.5)));
assert_ne!(h.outline.winding(Point::new(95.0, 1.0)), 0);
// The line stops halfway along the head.
assert!((h.inset - 3.0).abs() < 1e-9, "inset {}", h.inset);
// Extended, the tip sits the inset past the end point, and scaling scales the art.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.arrow_scale) = (Some(kind), (200.0, 100.0));
let mut l = BezPath::new();
l.move_to((0.0, 0.0));
l.line_to((100.0, 0.0));
let p = stroke_pieces(&l, &st);
let [s] = &p.heads[..] else { panic!("one head") };
assert!((s.tip.x + 6.0).abs() < 1e-9 && s.dir.x < 0.0, "tip {:?}", s.tip);
assert!((s.outline.bounding_box().width() - 12.0).abs() < 1e-9);
}
+14
View File
@@ -37,6 +37,20 @@ fn near(a: f64, b: f64, tol: f64) -> bool {
// ---------------------------------------------------------------- dashes fitted to corners
/// A subpath with no segments (a lone moveto, as an HP-GL wedge of almost no radius gives) is
/// dashed fitted to corners without a panic, and the other subpaths keep their dashes.
#[test]
fn fitted_dashes_take_a_subpath_with_no_segments() {
let mut b = BezPath::new();
b.move_to((5.0, 5.0));
b.extend(line(100.0));
let d = dash(&b, &fitted(&[10.0, 5.0], 0.0)).expect("dashed");
assert!(moves(&d.path) > 1 && length(&d.path) > 0.0, "{:?}", d.path);
let mut lone = BezPath::new();
lone.move_to((0.0, 0.0));
assert!(dash(&lone, &fitted(&[10.0, 5.0], 0.0)).is_some_and(|d| d.path.elements().is_empty()));
}
#[test]
fn every_corner_of_a_rectangle_falls_mid_dash() {
// 100 × 50 with 12/6: the long sides hold 6 periods (scaled by 100/108), the short ones 3
@@ -286,6 +286,94 @@ fn a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone() {
assert_covered(&hairpin, &st);
}
/// A gradient along or across a stroke that repeats or reflects runs its stops that many times
/// along (or across) it: a slice's paint, and Outline Stroke's meshes, give each point the color
/// the spread gives its place.
#[test]
fn a_spread_gradient_runs_its_stops_along_the_stroke_that_many_times() {
use vectorcraft_color::GradientSpread;
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
for (mode, spread) in [StrokeGradientMode::Along, StrokeGradientMode::Across]
.into_iter()
.flat_map(|m| [GradientSpread::Reflect, GradientSpread::Repeat].map(|s| (m, s)))
{
let mut st = stroke(10.0, mode);
let g = Gradient { spread, repeats: 3, ..Gradient::default() };
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
for s in slices(&bp, &st) {
let Paint::Gradient(p) = s.paint(&g.unrolled()) else { panic!("a gradient slice") };
let geom = p.geom.unwrap();
for u in [0.1, 0.5, 0.9] {
let at = s.from + (s.to - s.from) * u;
let t = s.span.0 + (s.span.1 - s.span.0) * u;
// Where two runs meet, Repeat's color is the next run's start or the last one's end.
if (t * 3.0 - (t * 3.0).round()).abs() < 1e-9 {
continue;
}
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
let got = p.gradient.sample(geom.param_at(vectorcraft_color::GradientKind::Linear, at) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-3), "{mode:?} at {t}: {want:?} vs {got:?}");
}
}
// Outline Stroke: the mesh comes back to white where each run starts again, and reaches
// black where each run ends, on both sides of a sharp step between runs.
let count = |g: &Gradient, hex: &str| {
gradient_meshes(&bp, FillRule::NonZero, &st, g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == hex).count()
};
for hex in ["#ffffff", "#000000"] {
let (spread, pad) = (count(&g, hex), count(&Gradient::default(), hex));
assert!(spread > pad, "{mode:?} {:?} {hex}: {spread} vs {pad}", g.spread);
}
}
}
/// Where a reflecting gradient turns back past a narrow last stop, Outline Stroke's mesh keeps that
/// stop's color.
#[test]
fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
use vectorcraft_color::GradientSpread;
let bp = poly(&[(0.0, 0.0), (120.0, 0.0)], false);
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.995, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
let mut st = stroke(10.0, mode);
let g = Gradient { spread: GradientSpread::Reflect, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops.clone()) };
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
let whites =
gradient_meshes(&bp, FillRule::NonZero, &st, &g).iter().flat_map(|m| m.points.iter()).filter(|p| p.color.to_hex() == "#ffffff").count();
// The gradient turns back at white 50 times.
assert!(whites >= 50, "{mode:?}: {whites}");
}
}
/// Outline Stroke's mesh across a stroke of many ribs, with a gradient of many stops repeated 100
/// times: each mesh holds at most so many points, and every run still starts on its first color.
#[test]
fn a_mesh_across_many_ribs_and_stops_stays_bounded() {
use vectorcraft_color::GradientSpread;
let pts: Vec<(f64, f64)> = (0..1200).map(|i| (i as f64 * 10.0, if i % 2 == 0 { 0.0 } else { 10.0 })).collect();
let bp = poly(&pts, false);
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(1.0 - i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) };
let mut st = stroke(4.0, StrokeGradientMode::Across);
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
let meshes = gradient_meshes(&bp, FillRule::NonZero, &st, &g);
assert!(!meshes.is_empty());
for m in &meshes {
assert!(m.points.len() <= super::gradient::MAX_MESH_POINTS, "{} points", m.points.len());
// A row at the start of each of the 100 runs, on every rib, is white.
let light = m.points.iter().filter(|p| p.color.to_rgb()[0] > 0.97).count();
assert!(light >= 100 * (m.cols as usize + 1), "{light} light points of {}", m.points.len());
}
// A strip of more ribs than one mesh has room for is split into meshes that share their end
// ribs, every rib in one of them.
use super::gradient::rib_pieces;
assert_eq!(rib_pieces(5, 3), [0..3, 2..5]);
assert_eq!(rib_pieces(4, 3), [0..3, 2..4]);
let one = rib_pieces(2, 1000);
assert_eq!((one.len(), one.first()), (1, Some(&(0..2))));
assert_eq!(rib_pieces(3, 0), [0..2, 1..3]);
}
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
/// 256 do.
+44 -2
View File
@@ -78,6 +78,35 @@ fn a_butt_capped_open_path_is_measured_where_it_paints() {
}
}
#[test]
fn beveled_corners_are_measured_where_they_paint() {
let mut tip = BezPath::new();
tip.move_to((0.0, 100.0));
tip.line_to((20.0, 0.0));
tip.line_to((40.0, 100.0));
tip.close_path();
let mut chevron = BezPath::new();
chevron.move_to((0.0, 100.0));
chevron.line_to((20.0, 0.0));
chevron.line_to((40.0, 100.0));
// A rectangle with no width turns back at its top and bottom.
let flat = vectorcraft_geom::shapes::rectangle(Rect::new(3.0, 100.0, 3.0, 150.0)).to_bezpath();
let ps = paths();
for (name, bp) in [("tip", &tip), ("chevron", &chevron), ("zigzag", &ps[1]), ("triangle", &ps[2]), ("flat", &flat)] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
for (join, limit) in [(LineJoin::Bevel, 10.0), (LineJoin::Miter, 1.0), (LineJoin::Miter, 2.0), (LineJoin::Miter, 10.0)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 20.0);
(st.cap, st.join, st.miter_limit) = (cap, join, limit);
let painted = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath().bounding_box();
let bounds = st.bounds_on(bp, bp.bounding_box());
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
assert!((got - want).abs() < 0.05, "{name} {cap:?} {join:?} {limit}: measured {bounds:?}, paints {painted:?}");
}
}
}
}
}
#[test]
fn bounds_and_clicks_cover_what_every_stroke_paints() {
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
@@ -99,14 +128,27 @@ fn bounds_and_clicks_cover_what_every_stroke_paints() {
}
}
/// Custom heads: one wholly behind its tip, and a long one reaching as far in front of its tip as
/// behind it (its tip sits halfway along it past the end point with Extend).
fn custom_heads() -> Vec<Arrowhead> {
use vectorcraft_geom::{Point as P, SubPath};
let head = |name: &str, pts: &[(f64, f64)]| {
let pts: Vec<P> = pts.iter().map(|&(x, y)| P::new(x, y)).collect();
let path = PathData::single(SubPath::polyline(&pts, true));
Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(name.into(), path)))
};
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
}
#[test]
fn bounds_and_clicks_cover_every_arrowhead() {
let bp = &paths()[0];
for kind in Arrowhead::ALL {
for kind in Arrowhead::ALL.into_iter().chain(custom_heads()) {
for align in [ArrowAlign::Extend, ArrowAlign::Tip] {
for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) =
(Some(kind.clone()), Some(kind.clone()), align, (scale, scale), cap);
check(bp, &st, &format!("{kind:?} {align:?} {scale}%"));
}
}
+91
View File
@@ -4,6 +4,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
use super::*;
mod rasterfollow;
mod scale;
mod transformfx;
@@ -1251,6 +1252,96 @@ fn roughen_smooth_makes_no_cusps() {
}
}
#[test]
fn roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly() {
use vectorcraft_geom::AnchorKind;
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
let (a, b) = (Point::new(0.0, 0.0), Point::new(300.0, 0.0));
let curve = PathData::single(SubPath::new(
vec![
vectorcraft_geom::Anchor::with_handles(a, a, Point::new(10.0, 40.0)),
vectorcraft_geom::Anchor::with_handles(b, Point::new(100.0, 200.0), b),
],
false,
));
let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 50.0));
// Two subpaths with lines and curves: a closed one whose last segment is a line, and an open
// one that ends with a line.
let (c, d, e, f) = (Point::new(100.0, 100.0), Point::new(200.0, 0.0), Point::new(300.0, 0.0), Point::new(300.0, 100.0));
let mixed = PathData::new(vec![
SubPath::new(
vec![
vectorcraft_geom::Anchor::corner(a),
vectorcraft_geom::Anchor::with_handles(Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(160.0, 20.0)),
vectorcraft_geom::Anchor::with_handles(c, Point::new(160.0, 80.0), c),
],
true,
),
SubPath::new(
vec![
vectorcraft_geom::Anchor::with_handles(d, d, Point::new(220.0, 60.0)),
vectorcraft_geom::Anchor::with_handles(e, Point::new(280.0, 60.0), e),
vectorcraft_geom::Anchor::corner(f),
],
false,
),
]);
for path in [square(), ellipse, curve, mixed] {
let all: Vec<_> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i))).collect();
let off = |q: Point| all.iter().map(|c| c.nearest(q, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt();
for params in
[json!({"size": 0}), json!({"size": 0, "points": "corner"}), json!({"size": 0, "relative": false, "points": "corner", "seed": 7})]
{
let out = run("distort.roughen", params.clone(), &path);
assert!(out.anchor_count() > path.anchor_count(), "{params}: the points are added");
assert_eq!(out.subpaths.len(), path.subpaths.len(), "{params}");
for (sp, got) in path.subpaths.iter().zip(&out.subpaths) {
assert_eq!(got.closed, sp.closed);
// Walk the result one original segment at a time: its pieces end on the segment's end anchor.
let mut at = 0;
for i in 0..sp.segment_count() {
let (orig, end) = (sp.segment(i), sp.anchors[(i + 1) % sp.anchors.len()]);
let start = got.anchors[at];
let was = sp.anchors[i];
assert_eq!((start.p, start.kind, start.has_in(), start.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}");
let mut pieces = vec![];
loop {
let piece = got.segment(at);
for j in 0..=8 {
let q = piece.eval(j as f64 / 8.0);
assert!(off(q) < 1e-6, "{params}: {q:?} is {} off the outline", off(q));
}
pieces.push(piece.arclen(1e-6));
at += 1;
if piece.p3.distance(end.p) < 1e-9 {
break;
}
// A point the effect added: a corner without handles on a line, a smooth
// point whose handles follow the curve.
let added = got.anchors[at];
if sp.segment_is_line(i) {
assert_eq!((added.kind, added.has_in(), added.has_out()), (AnchorKind::Corner, false, false), "{params}");
} else {
assert_eq!(added.kind, AnchorKind::Smooth, "{params}");
let (hi, ho) = (added.h_in - added.p, added.h_out - added.p);
assert!(hi.cross(ho).abs() < 1e-6 * hi.hypot() * ho.hypot() && hi.dot(ho) < 0.0, "{params}: {added:?}");
}
}
assert!(pieces.len() > 1, "{params}: segment {i} is split");
assert!(close(pieces.iter().sum::<f64>(), orig.arclen(1e-6), 1e-3), "{params}: {pieces:?}");
let (lo, hi) = pieces.iter().fold((f64::INFINITY, 0.0f64), |(lo, hi), &l| (lo.min(l), hi.max(l)));
assert!(hi - lo < 1e-3, "{params}: segment {i}'s pieces from {lo} to {hi}");
}
assert_eq!(at, got.segment_count(), "{params}");
if !sp.closed {
let (last, was) = (got.anchors[at], sp.anchors[sp.anchors.len() - 1]);
assert_eq!((last.p, last.kind, last.has_in(), last.has_out()), (was.p, was.kind, was.has_in(), was.has_out()), "{params}");
}
}
}
}
}
#[test]
fn zigzag_ridge_count_and_amplitude() {
let out = run("distort.zigZag", json!({"ridges": 4, "points": "corner", "size": 10}), &square());
+421
View File
@@ -0,0 +1,421 @@
//! Raster effects listed before a Transform effect follow it: the Transform effect transforms
//! what they paint.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
use crate::{RasterFx, bake_document, expand_outlined, raster_effects};
fn fx(id: &str, params: Value) -> Effect {
Effect { id: id.into(), params, visible: true }
}
fn shadow(x: f64, y: f64, blur: f64) -> Effect {
fx("stylize.dropShadow", json!({"x": x, "y": y, "blur": blur}))
}
fn transform(params: Value) -> Effect {
fx("distort.transform", params)
}
/// The offset and blur of the first Drop Shadow `effects` draw.
fn drawn_shadow(effects: &[Effect]) -> (f64, f64, f64) {
match raster_effects(effects).first() {
Some(RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
fn close(a: (f64, f64, f64), b: (f64, f64, f64)) -> bool {
(a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 && (a.2 - b.2).abs() < 1e-9
}
/// A 50 pt red square with `effects`.
fn square(id: u64, effects: Vec<Effect>) -> Node {
let mut n = Node::path(
NodeId(id),
shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)),
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0),
);
n.appearance.effects = effects;
n
}
#[test]
fn a_transform_after_a_drop_shadow_scales_its_offset_and_blur() {
for strokes in [false, true] {
let effects = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200, "strokes": strokes}))];
assert!(close(drawn_shadow(&effects), (20.0, 20.0, 8.0)), "Scale Strokes & Effects {strokes}: {:?}", drawn_shadow(&effects));
}
}
#[test]
fn a_drop_shadow_after_a_transform_keeps_its_offset() {
let effects = [transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 10.0, 4.0)];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
}
#[test]
fn the_offset_follows_an_uneven_scale_a_rotation_and_a_reflection() {
let uneven = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 100}))];
assert!(close(drawn_shadow(&uneven), (20.0, 10.0, 4.0 * 2f64.sqrt())), "{:?}", drawn_shadow(&uneven));
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
let turned = [shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90}))];
let (dx, dy, blur) = drawn_shadow(&turned);
assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9 && (blur - 4.0).abs() < 1e-9, "{dx} {dy} {blur}");
let reflected = [shadow(10.0, 0.0, 4.0), transform(json!({"reflectX": true}))];
assert!(close(drawn_shadow(&reflected), (-10.0, 0.0, 4.0)), "{:?}", drawn_shadow(&reflected));
}
#[test]
fn transforms_after_the_shadow_apply_in_order() {
let effects = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))];
let (dx, dy, _) = drawn_shadow(&effects);
assert!(dx.abs() < 1e-9 && (dy + 20.0).abs() < 1e-9, "{dx} {dy}");
// Only the Transform after a shadow moves it.
let between = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), shadow(0.0, 10.0, 0.0)];
let drawn = raster_effects(&between);
let offsets: Vec<(f64, f64)> = drawn
.iter()
.filter_map(|r| match r {
RasterFx::DropShadow { dx, dy, .. } => Some((*dx, *dy)),
_ => None,
})
.collect();
assert_eq!(offsets, vec![(20.0, 0.0), (0.0, 10.0)]);
}
#[test]
fn transforms_that_leave_the_art_or_copy_it_leave_the_shadow() {
for params in [
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "copies": 1}),
json!({"scaleH": 200, "scaleV": 200, "random": true}),
] {
let effects = [shadow(10.0, 10.0, 4.0), transform(params.clone())];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{params}: {:?}", drawn_shadow(&effects));
}
let mut hidden = transform(json!({"scaleH": 200, "scaleV": 200}));
hidden.visible = false;
let effects = [shadow(10.0, 10.0, 4.0), hidden];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
}
/// A hidden shadow kept when the Transform effect is applied (Expand Appearance) draws as it would
/// have before, once it is shown.
#[test]
fn a_hidden_shadow_follows_the_transform_it_loses() {
let mut hidden = shadow(10.0, 10.0, 4.0);
hidden.visible = false;
let kept = crate::raster::without_geometry(&[hidden, transform(json!({"scaleH": 200, "scaleV": 200}))]);
assert_eq!(kept.len(), 1);
let mut shown = kept[0].clone();
shown.visible = true;
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
}
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
#[test]
fn rasterize_before_a_transform_keeps_its_options() {
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
}
/// An SVG filter keeps its options: it paints in its own user space.
#[test]
fn an_svg_filter_before_a_transform_keeps_its_options() {
let filter = fx(crate::SVG_FILTER, json!({"origin": [10, 10]}));
let effects = [filter.clone(), transform(json!({"scaleH": 200, "scaleV": 200, "rotate": 90}))];
assert_eq!(crate::raster::followed(&effects)[0], filter);
assert_eq!(crate::raster::without_geometry(&effects), vec![filter]);
}
/// The offset of every Drop Shadow drawn on `n` and the nodes under it, from the object's effects
/// and from each fill's and stroke's.
fn shadows_in(n: &Node) -> Vec<(f64, f64)> {
let mut out = vec![];
n.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
for list in lists {
for r in raster_effects(list) {
if let RasterFx::DropShadow { dx, dy, .. } = r {
out.push((dx, dy));
}
}
}
});
out
}
fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9)
}
/// A square whose fill carries `effects` of its own.
fn fill_square(id: u64, effects: Vec<Effect>) -> Node {
let mut n = square(id, vec![]);
if let Some(item) = n.appearance.items.first_mut() {
*item.effects_mut() = effects;
}
n
}
/// A fill's own Transform effect transforms the fill's raster effects before it: drawn as they are
/// (no options), drawn through the art the Transform Patterns or Scale Strokes & Effects option
/// makes, expanded and baked. Scale Strokes & Effects does not scale a shadow that follows the
/// Transform effect a second time.
#[test]
fn a_fills_shadow_follows_the_fills_own_transform() {
let cases = [
(json!({"rotate": 90}), (0.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (0.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "strokes": true}), (20.0, 0.0)),
(json!({"scaleH": 200, "scaleV": 200, "patterns": true}), (20.0, 0.0)),
(json!({"reflectX": true, "patterns": true}), (-10.0, 0.0)),
];
for (params, want) in cases {
let n = fill_square(11, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
// Drawn and expanded through its art when an option makes some.
if crate::has_transform_art(&n) {
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[want]), "{params}: drawn {:?}", shadows_in(&art));
let expanded = expand_outlined(None, &n, None).unwrap();
assert!(near(&shadows_in(&expanded), &[want]), "{params}: expanded {:?}", shadows_in(&expanded));
} else {
assert!(near(&shadows_in(&n), &[want]), "{params}: drawn {:?}", shadows_in(&n));
}
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let b = baked.node(NodeId(11)).unwrap();
assert!(near(&shadows_in(b), &[want]), "{params}: baked {:?}", shadows_in(b));
}
}
/// A Transform effect after a fill's own Transform effect with Scale Strokes & Effects on turns the
/// shadow between them, which the first one leaves as it is; a Transform effect that moves at random
/// holds the shadow before it back from the Transform effects after it.
#[test]
fn a_fills_later_transform_turns_the_shadow_after_its_first() {
let n = fill_square(
12,
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90}))],
);
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[(0.0, -10.0)]), "{:?}", shadows_in(&art));
let held = fill_square(
13,
vec![
shadow(10.0, 0.0, 0.0),
transform(json!({"scaleH": 200, "scaleV": 200, "random": true, "strokes": true})),
transform(json!({"rotate": 90})),
],
);
let art = crate::reshape(None, &held, None).unwrap();
let drawn = shadows_in(&art);
assert!(drawn.len() == 1 && drawn[0].0 > 0.0 && drawn[0].1.abs() < 1e-9, "{drawn:?}");
}
/// A fill's own Transform effect with Transform Patterns or Scale Strokes & Effects on leaves the
/// fill's raster effects after it as they are: they paint around the transformed art, its copies
/// included. With Transform Objects off it leaves the raster effects before it as they are too.
/// Drawn, expanded and baked alike.
#[test]
fn a_fills_own_transform_leaves_the_shadow_after_it() {
let cases = [
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 120, "copies": 1, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}))],
// A later Transform effect with an option leaves the shadow after it as well.
vec![
transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true})),
transform(json!({"scaleH": 150, "scaleV": 150, "strokes": true})),
shadow(10.0, 0.0, 0.0),
],
];
for effects in cases {
let n = fill_square(18, effects.clone());
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{effects:?}: drawn {drawn:?}");
let expanded = shadows_in(&expand_outlined(None, &n, None).unwrap());
assert!(!expanded.is_empty() && near(&expanded, &vec![(10.0, 0.0); expanded.len()]), "{effects:?}: expanded {expanded:?}");
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let b = shadows_in(baked.node(NodeId(18)).unwrap());
assert!(!b.is_empty() && near(&b, &vec![(10.0, 0.0); b.len()]), "{effects:?}: baked {b:?}");
}
}
/// A geometry effect after a fill's own Transform effect with Scale Strokes & Effects on reshapes
/// the transformed art by its own distance, as it does after an object's Transform effect.
#[test]
fn a_fills_own_transform_leaves_the_offset_after_it() {
let offset = fx("path.offsetPath", json!({"offset": 5}));
let scaled = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
let n = fill_square(19, vec![scaled.clone(), offset.clone()]);
let on_fill = crate::reshape(None, &n, None).unwrap();
let on_object = crate::reshape(None, &square(20, vec![scaled, offset]), None).unwrap();
let (fill, object) = (on_fill.geometric_bounds().unwrap(), on_object.geometric_bounds().unwrap());
// The 50 pt square scaled to 100 pt about its center, then offset by 5 pt on each side.
assert!((fill.width() - 110.0).abs() < 1e-6 && (fill.height() - 110.0).abs() < 1e-6, "{fill:?}");
assert!((fill.width() - object.width()).abs() < 1e-6 && (fill.x0 - object.x0).abs() < 1e-6, "{fill:?} {object:?}");
let expanded = expand_outlined(None, &n, None).unwrap().geometric_bounds().unwrap();
assert!((expanded.width() - 110.0).abs() < 1e-6 && (expanded.x0 - fill.x0).abs() < 1e-6, "expanded {expanded:?}");
}
/// The SVG filters on `n` and the nodes under it, from the object's effects and from each fill's
/// and stroke's.
fn filters_in(n: &Node) -> Vec<Effect> {
let mut out = vec![];
n.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
out.extend(lists.flatten().filter(|e| e.id == crate::SVG_FILTER).cloned());
});
out
}
/// An SVG filter after a fill's own Transform effect with Scale Strokes & Effects on keeps its
/// scale and the origin of its user space, as it does after the same Transform effect without
/// options and after an object's own Transform effect.
#[test]
fn a_fills_own_transform_leaves_the_svg_filter_after_it() {
let filter = fx(crate::SVG_FILTER, json!({"scale": 1.0, "origin": [10.0, 10.0]}));
for params in [
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "patterns": true}),
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
] {
let art = crate::reshape(None, &fill_square(21, vec![transform(params.clone()), filter.clone()]), None).unwrap();
let drawn = filters_in(&art);
assert!(!drawn.is_empty() && drawn.iter().all(|e| *e == filter), "{params}: {drawn:?}");
}
let object = square(22, vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true})), filter.clone()]);
let art = crate::reshape(None, &object, None).unwrap();
assert!(!filters_in(&art).is_empty() && filters_in(&art).iter().all(|e| *e == filter), "{:?}", filters_in(&art));
}
/// The 3D effects keep the shadow before a Transform effect that shapes the art they project, the
/// object's and its fill's 3D effect alike.
#[test]
fn a_shadow_before_a_transform_follows_it_into_3d_art() {
let before = vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let mut on_object = before.clone();
on_object.push(fx(three_d, json!({})));
let projected = art(&square(14, on_object)).unwrap();
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the object: {:?}", shadows_in(&projected));
let mut on_fill = square(15, before.clone());
if let Some(item) = on_fill.appearance.items.first_mut() {
*item.effects_mut() = vec![fx(three_d, json!({}))];
}
let projected = art(&on_fill).unwrap();
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the fill: {:?}", shadows_in(&projected));
}
}
#[test]
fn glows_blurs_and_feathers_scale_with_the_transform_after_them() {
let effects = [
fx("stylize.outerGlow", json!({"blur": 5})),
fx("stylize.innerGlow", json!({"blur": 5})),
fx("stylize.feather", json!({"radius": 5})),
fx("blur.gaussian", json!({"radius": 5})),
transform(json!({"scaleH": 50, "scaleV": 50})),
];
let sizes: Vec<f64> = raster_effects(&effects)
.iter()
.map(|r| match r {
RasterFx::OuterGlow { blur, .. } | RasterFx::InnerGlow { blur, .. } => *blur,
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => *radius,
other => panic!("unexpected {other:?}"),
})
.collect();
assert_eq!(sizes, vec![2.5; 4]);
// How far the shadow paints past the object follows too.
let shadowed = [shadow(10.0, 10.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::outset(&shadowed, Rect::new(0.0, 0.0, 100.0, 100.0)), 20.0);
}
#[test]
fn pixel_filter_sizes_scale_with_the_transform_after_them() {
let effects = [
fx("artistic.coloredPencil", json!({"pencilWidth": 5})),
fx("artistic.paintDaubs", json!({"brushSize": 10})),
transform(json!({"scaleH": 200, "scaleV": 200})),
];
let drawn = raster_effects(&effects);
assert!(matches!(drawn.first(), Some(RasterFx::Pixel(crate::PixelFx::ColoredPencil { width, .. })) if (width - 10.0).abs() < 1e-9), "{drawn:?}");
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
}
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
/// before the 3D effect, as it does without the 3D effect.
#[test]
fn a_copying_transform_after_3d_holds_the_shadow_back() {
for later in [json!({"copies": 1}), json!({"scaleH": 150, "scaleV": 150, "random": true})] {
let plain = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(later.clone())];
assert!(close(drawn_shadow(&plain), (10.0, 0.0, 0.0)), "{later}: {:?}", drawn_shadow(&plain));
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let effects = vec![plain[0].clone(), plain[1].clone(), fx(three_d, json!({})), plain[2].clone()];
let projected = art(&square(16, effects)).unwrap();
let drawn = shadows_in(&projected);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{three_d} {later}: {drawn:?}");
}
}
}
/// In a fill's own effects, a Transform effect that makes copies after a Transform effect with
/// Transform Patterns on holds back the shadow before both, and before a Transform effect between
/// them.
#[test]
fn a_fills_copying_transform_holds_back_the_shadow_before_an_earlier_transform() {
let patterns = transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true}));
let copies = transform(json!({"copies": 1}));
let lists = [
vec![shadow(10.0, 0.0, 0.0), patterns.clone(), copies.clone()],
vec![shadow(10.0, 0.0, 0.0), patterns, transform(json!({"rotate": 90})), copies],
];
for effects in lists {
let n = fill_square(17, effects.clone());
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{} effects: {drawn:?}", effects.len());
}
}
#[test]
fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() {
let effects = vec![shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
// A path drawn through its art (Scale Strokes & Effects on), expanded.
let mut with_options = effects.clone();
with_options[1] = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
let n = square(7, with_options);
let expanded = expand_outlined(None, &n, None).unwrap();
assert!(close(drawn_shadow(&expanded.appearance.effects), (20.0, 20.0, 8.0)), "{:?}", expanded.appearance.effects);
// A path and a group, baked for export.
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, square(8, effects.clone())).unwrap();
let mut g = Node::group(NodeId(9), vec![std::sync::Arc::new(square(10, vec![]))]);
g.appearance.effects = effects.clone();
d.insert(Some(layer), 1, g).unwrap();
let baked = bake_document(&d).unwrap();
for id in [8, 9] {
let b = baked.node(NodeId(id)).unwrap();
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{id}: {:?}", b.appearance.effects);
assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects);
}
}
+3 -3
View File
@@ -222,7 +222,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
}
#[test]
fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() {
fn a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects() {
let mut n = stroke_with_effect(json!({}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true})));
@@ -231,10 +231,10 @@ fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects
let art = reshape(None, &n, None).unwrap();
let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap();
let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") };
// The Offset Path, scaled from 5 to 15, applies to the transformed fill's path.
// The Offset Path applies to the transformed fill's path at its own 5 pt.
assert!(f.effects.is_empty(), "{:?}", f.effects);
let w = fill.geometric_bounds().unwrap().width();
assert!(close(w, 330.0), "{w}");
assert!(close(w, 310.0), "{w}");
}
#[test]
+5
View File
@@ -4,6 +4,7 @@ pub mod actionset;
mod addons;
mod apiref;
pub(crate) mod appearance;
pub mod arrowheads;
mod assets;
mod attributes;
pub mod brushlib;
@@ -105,6 +106,7 @@ mod variablecmds;
pub(crate) mod views;
pub mod wand;
pub mod webexport;
mod wireframe;
mod xform;
use serde::Serialize;
@@ -297,6 +299,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
// Split out of `paint` (M3.8); kept next to it so lists in registry order (the command
// palette, `engine.commands`) show them where they always were.
v.extend(stroke::specs());
v.extend(arrowheads::specs());
v.extend(appearance::specs());
v.extend(style::specs());
v.extend(swatch::specs());
@@ -308,6 +311,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(effectcmd::specs());
v.extend(wireframe::specs());
v.extend(pathops::specs());
v.extend(compoundshape::specs());
v.extend(typecmd::specs());
@@ -771,6 +775,7 @@ pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
pub use plugin_call::{Location, key_location, location_in, location_keys};
pub(crate) use vectorcraft_doc::range::parse_range;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
+1 -1
View File
@@ -137,7 +137,7 @@ fn legend(s: &mut Session, p: &Value) -> Result<Value> {
let parent = st.target_parent()?;
let text_size = (size / 7.0).clamp(4.0, 12.0);
let pad = (size / 12.0).clamp(1.0, 8.0);
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }));
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
let count = swatches.len();
// Each chip's fill links to its swatch, as paint.setFill {swatch} links art: editing a global or
// spot swatch then recolours the legend too.
+7 -2
View File
@@ -1,11 +1,16 @@
//! Cutting Tools (`addon.cutting.*`), a built-in add-on that prepares art for cutting. Stencil
//! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together
//! ([`stencil`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialog are the UI's.
//! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art
//! for vinyl cutting ([`weed`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are
//! the UI's.
mod stencil;
mod weed;
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
stencil::specs()
let mut v = stencil::specs();
v.extend(weed::specs());
v
}
@@ -89,7 +89,12 @@ fn bridges(s: &mut Session, p: &Value) -> Result<Value> {
};
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
let spec = BridgeSpec { width, count: count as usize, direction };
let bridged = stencil_bridges(&refs, spec).map_err(|e| EngineError::Other(e.to_string()))?;
let bridged = stencil_bridges(&refs, spec).map_err(|e| match e {
vectorcraft_pathops::PathOpsError::TooComplex => {
EngineError::Other("Stencil Bridges: the selected art is too large or too detailed to bridge".into())
}
e => EngineError::Other(e.to_string()),
})?;
(bridged, style_of(&top), roots)
};
let summary = |id: Option<NodeId>, original: Option<NodeId>| {
@@ -277,6 +277,34 @@ fn bad_params_are_refused() {
assert!(s.execute("addon.cutting.bridges", &json!({"width": 4})).is_ok(), "good params run");
}
#[test]
fn art_too_detailed_to_bridge_is_refused_with_a_message_that_says_so() {
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("dense", |d, sel| {
// More anchors than Stencil Bridges measures.
let mut zigzag = kurbo::BezPath::new();
zigzag.move_to((100.0, 100.0));
for i in 1..=vectorcraft_pathops::addons::stencil::MAX_STENCIL_SEGMENTS {
zigzag.line_to((100.0 + i as f64 * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
}
zigzag.close_path();
let huge = vectorcraft_geom::PathData::from_bezpath(&zigzag);
let n = vectorcraft_doc::Node::path(d.alloc_id(), huge, vectorcraft_doc::Appearance::default());
let id = n.id;
d.insert(parent, usize::MAX, n)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(&mut s, &[id]);
let steps = undo_steps(&s);
let e = s.execute("addon.cutting.bridges", &json!({"width": 4})).unwrap_err().to_string();
assert!(e.contains("Stencil Bridges: the selected art is too large or too detailed to bridge"), "{e}");
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn selected_objects_without_outlines_stay_where_they_are() {
for keep in [true, false] {
@@ -0,0 +1,160 @@
//! Weed Box and Lines (`addon.cutting.weed`), a command of the built-in Cutting Tools add-on for
//! vinyl cutting: around the selected art it adds a weed box (a rectangle at a margin around the
//! art) and weeding lines across it that stop at the art, so the waste vinyl around the art lifts
//! off in pieces (<https://help.arlon.com/what-is-a-weeding-border>). The art is measured by the
//! outlines a cutter cuts ([`geometry`]).
mod geometry;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::super::super::edit::selected_roots;
use super::super::super::object::choice;
use super::super::super::paint::swatch_solid;
use super::super::super::pathops::{length_given, number_given};
use super::super::super::{CommandSpec, bad, cmd, has_selection, switch_or, text_param};
use crate::{EngineError, Result, Session};
/// Weed Box and Lines' command.
pub const WEED: &str = "addon.cutting.weed";
/// Which way the weeding lines run.
pub const DIRECTIONS: [&str; 3] = ["horizontal", "vertical", "both"];
/// The largest margin, gap or spacing, in points.
const MAX_DISTANCE: f64 = 100_000.0;
/// The most weeding lines each way.
const MAX_COUNT: usize = 1000;
/// The most pieces of weeding line one run adds.
const MAX_PIECES: usize = 100_000;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.cutting.weed",
"Weed Box and Lines…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
has_selection,
weed
)]
}
/// The distance `p` gives for `key` (0..[`MAX_DISTANCE`]), or `default`.
fn distance(p: &Value, key: &str, default: f64) -> Result<f64> {
match length_given(p, key, WEED)? {
None => Ok(default),
Some(v) if (0.0..=MAX_DISTANCE).contains(&v) => Ok(v),
Some(_) => Err(bad(WEED, format!("`{key}` must be from 0 to {MAX_DISTANCE} pt"))),
}
}
/// How many lines divide a side `length` long: `count`, or as few as keep them at most `spacing`
/// apart.
fn lines_across(length: f64, count: Option<usize>, spacing: Option<f64>) -> Result<usize> {
let n = match spacing {
// `length / spacing` strips, rounded up, need one line fewer.
Some(s) => ((length / s - 1e-9).ceil() - 1.0).max(0.0),
None => return Ok(count.unwrap_or(1)),
};
if n > MAX_COUNT as f64 {
return Err(bad(WEED, format!("`spacing` makes more than {MAX_COUNT} lines across the box")));
}
Ok(n as usize)
}
/// Where the Weeding group goes: `parent`, or, when `parent` is inside a clip group or clipping
/// sublayer (a group edited in isolation), the container around the outermost of them. A clipping
/// path would hide the lines and the box, which lie outside the art.
fn outside_clips(d: &Document, parent: Option<NodeId>) -> Option<NodeId> {
let clips = |id: NodeId| d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. }));
let (mut at, mut out) = (parent, parent);
while let Some(p) = at {
let up = d.parent_of(p);
if clips(p) {
match up {
Some(up) if d.is_editable(up) => out = Some(up),
_ => break,
}
}
at = up;
}
out
}
fn weed(s: &mut Session, p: &Value) -> Result<Value> {
let margin = distance(p, "margin", 9.0)?;
let gap = distance(p, "gap", 0.0)?;
let with_box = switch_or(p, "box", true, WEED)?;
let direction = choice(p, WEED, "direction", &DIRECTIONS)?.unwrap_or("both");
let count = match number_given(p, "count", WEED)? {
None => None,
Some(n) if n.fract() == 0.0 && (0.0..=MAX_COUNT as f64).contains(&n) => Some(n as usize),
Some(_) => return Err(bad(WEED, format!("`count` must be a whole number from 0 to {MAX_COUNT}"))),
};
let spacing = match length_given(p, "spacing", WEED)? {
None => None,
Some(v) if v > 0.0 && v <= MAX_DISTANCE => Some(v),
Some(_) => return Err(bad(WEED, format!("`spacing` must be more than 0 and at most {MAX_DISTANCE} pt"))),
};
if count.is_some() && spacing.is_some() {
return Err(bad(WEED, "give `count` or `spacing`, not both"));
}
let weight = match length_given(p, "weight", WEED)? {
None => 0.3,
Some(v) if (0.01..=1000.0).contains(&v) => v,
Some(_) => return Err(bad(WEED, "`weight` must be from 0.01 to 1000 pt")),
};
let swatch = text_param(p, "swatch", WEED)?.unwrap_or(REGISTRATION);
let stroke = swatch_solid(&s.doc()?.doc, swatch, None).map_err(|e| bad(WEED, e))?;
let roots = selected_roots(s)?;
if roots.is_empty() {
return Err(bad(WEED, "select the art to weed"));
}
let d = &s.doc()?.doc;
let parent = outside_clips(d, s.doc()?.target_parent()?);
// Placed files' art uses their resources (symbols) under names of their own.
let placed = d.with_placed_art();
let region = geometry::Reader::new(&placed).read_ids(&roots).map_err(|e| bad(WEED, e))?;
let region = region.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?;
let outline = region.outline().map_err(|e| bad(WEED, e))?;
let art = outline.iter().fold(None, |r: Option<Rect>, &(a, b)| Some(r.map_or(Rect::from_points(a, b), |r| r.union_pt(a).union_pt(b))));
let frame = art.ok_or_else(|| bad(WEED, "the selection has no outlines to weed around"))?.inflate(margin, margin);
if !(frame.width().is_finite() && frame.height().is_finite()) {
return Err(bad(WEED, "the selected art is too large to measure"));
}
let each = |on: bool, length: f64| if on { lines_across(length, count, spacing) } else { Ok(0) };
let counts =
geometry::Counts { horizontal: each(direction != "vertical", frame.height())?, vertical: each(direction != "horizontal", frame.width())? };
let pieces = geometry::lines(&region, &outline, frame, counts, gap, MAX_PIECES).map_err(|e| bad(WEED, e))?;
if pieces.is_empty() && !with_box {
return Err(EngineError::Other("Weed Box and Lines: no weeding line fits outside the art, and the weed box is off".into()));
}
let ap = Appearance::basic(Paint::None, stroke, weight);
let (group, weed_box, lines) = s.edit("Weed Box and Lines", |d, sel| {
let mut children = vec![];
let mut weed_box = None;
if with_box {
let mut b = Node::path(d.alloc_id(), shapes::rectangle(frame), ap.clone());
b.name = Some("Weed Box".into());
weed_box = Some(b.id);
children.push(Arc::new(b));
}
for (a, b) in &pieces {
children.push(Arc::new(Node::path(d.alloc_id(), shapes::line(*a, *b), ap.clone())));
}
let mut g = Node::group(d.alloc_id(), children);
g.name = Some("Weeding".into());
let id = g.id;
d.insert(parent, usize::MAX, g)?;
sel.set([id]);
Ok((id, weed_box, pieces.len()))
})?;
Ok(json!({ "id": group.0, "box": weed_box.map(|b| b.0), "lines": lines }))
}
@@ -0,0 +1,769 @@
//! The geometry of Weed Box and Lines: the selected art as the outlines a cutter cuts ([`Region`]),
//! and the weeding lines across a box that stop at those outlines or at a gap from them
//! ([`lines`]).
//!
//! A region is measured along one straight line at a time. A closed outline encloses its area by
//! its fill rule, an open one is a line with no area, a group is the union of its members and a
//! clip group is what its members draw inside its clipping path. Along a weeding line the region
//! gives the stretches inside its area ([`Region::spans`]), and its outline pieces
//! ([`Region::outline`]) give the stretches within the gap of an outline.
use std::cell::Cell;
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{BezPath, FillRule, PathEl, Point, Rect};
use super::super::super::super::pathops::node_path;
/// How closely curves are followed, in points.
const TOLERANCE: f64 = 0.02;
/// The most points the outlines of one selection are measured by, once curves are followed in
/// straight segments (each subpath's points, its first one included).
pub(super) const MAX_POINTS: usize = 200_000;
/// The most tests of a segment against another one measuring a clip group's outlines takes.
const MAX_PAIRS: usize = 40_000_000;
/// The deepest groups, symbol instances and live objects are opened inside one another: as deep
/// as any object is drawn.
pub(super) const MAX_DEPTH: usize = vectorcraft_doc::depth::MAX_DRAWN_DEPTH;
/// The most pairs of an outline segment and a weeding line it comes near that one run measures.
const MAX_NEAR: usize = 10_000_000;
/// Pieces of weeding line shorter than this, in points, are left out.
const MIN_PIECE: f64 = 0.01;
/// A straight segment.
pub(super) type Segment = (Point, Point);
/// One subpath followed in straight segments.
#[derive(Clone, Debug)]
pub(super) struct Poly {
points: Vec<Point>,
closed: bool,
/// The box around `points`.
bounds: Rect,
}
impl Poly {
/// The segments, with the closing one of a closed subpath.
fn segments(&self) -> impl Iterator<Item = Segment> + '_ {
let closing = self.closed.then(|| (self.points.last().copied(), self.points.first().copied()));
self.points.windows(2).map(|w| (w[0], w[1])).chain(closing.and_then(|(a, b)| Some((a?, b?))))
}
}
/// The selected art as the outlines a cutter cuts.
#[derive(Clone, Debug)]
pub(super) enum Region {
/// A path, compound path or type: its subpaths with the rule its closed ones fill by.
Shape { polys: Vec<Poly>, rule: FillRule },
/// Everything its members draw.
Union(Vec<Region>),
/// What `content` draws inside `clip`.
Clip { clip: Box<Region>, content: Box<Region> },
}
/// Reads the selected objects into a [`Region`], keeping count of the outline points.
pub(super) struct Reader<'a> {
doc: &'a Document,
points: usize,
}
impl<'a> Reader<'a> {
pub(super) fn new(doc: &'a Document) -> Self {
Self { doc, points: 0 }
}
/// The region of `nodes` together, `None` when they hold no outlines.
pub(super) fn read(&mut self, nodes: &[&Node]) -> Result<Option<Region>, String> {
let mut parts = vec![];
for n in nodes {
parts.extend(self.node(n, 0)?);
}
Ok(union(parts))
}
fn node(&mut self, n: &Node, depth: usize) -> Result<Option<Region>, String> {
if depth > MAX_DEPTH {
return Err(format!("the selected art is nested more than {MAX_DEPTH} levels deep"));
}
if !n.visible {
return Ok(None);
}
match &n.kind {
NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => Ok(None),
NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_) => self.shape(n),
NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } => {
let members = n.editing_children();
if *clip {
let Some((first, rest)) = members.split_first() else { return Ok(None) };
let Some(clip) = self.clip_region(first)? else { return Ok(None) };
let mut parts = vec![];
for c in rest {
parts.extend(self.node(c, depth + 1)?);
}
Ok(union(parts).map(|content| Region::Clip { clip: Box::new(clip), content: Box::new(content) }))
} else {
let mut parts = vec![];
for c in members {
parts.extend(self.node(c, depth + 1)?);
}
Ok(union(parts))
}
}
NodeKind::Image(im) => {
let (w, h) = (f64::from(im.width), f64::from(im.height));
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
self.polygon(&corners)
}
// An instance of a symbol the document doesn't have draws nothing.
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
Some(art) => self.node(&art, depth + 1),
None => Ok(None),
},
NodeKind::PlacedDocument(p) => {
// The art of the file it shows; a file that can't be read shows its preview in its
// box, which may be rotated.
if vectorcraft_doc::placed_document::read_cached(p).is_none() {
return self.polygon(&p.corners());
}
let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n);
if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) {
self.polygon(&p.corners())
} else {
self.node(&art, depth + 1)
}
}
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
// The art a live object draws, as the exporters write it; an object that stays
// as it is is measured by its box.
let art = vectorcraft_render::effects::expand_live_deep(Some(self.doc), n);
if std::mem::discriminant(&art.kind) == std::mem::discriminant(&n.kind) { self.frame(n) } else { self.node(&art, depth + 1) }
}
}
}
/// The region a clipping path `first` clips to, whatever its own visibility: the region the
/// renderer clips to (a path, a compound path, type by its glyphs, a group's visible members,
/// an image's frame). `None` when it clips to nothing, and the clipped art is hidden.
fn clip_region(&mut self, first: &Node) -> Result<Option<Region>, String> {
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(first) else { return Ok(None) };
let mut polys = self.polys(outline)?;
// A region is filled: an open subpath clips as if closed.
polys.iter_mut().for_each(|p| p.closed = true);
Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule }))
}
/// The region of the objects `ids` together, each within the clipping paths of the clip groups
/// and layers around it (an object selected inside a clip group shows only within its clipping
/// path, and not at all inside a hidden group or layer; a clipping path is measured as its clip
/// group), `None` when they show no outlines.
pub(super) fn read_ids(&mut self, ids: &[NodeId]) -> Result<Option<Region>, String> {
let doc = self.doc;
let clips = |n: &Node| matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
// Every object's place in the tree, found in one walk.
let places = doc.index_paths(ids.iter().copied());
let mut paths = vec![];
for id in ids {
let Some(mut path) = places.get(id).cloned() else { continue };
// A clipping path selected on its own stands for the art it shows: its clip group.
while let (Some(n), Some(up)) = (doc.node_at(&path), path.split_last().map(|(_, up)| up).and_then(|up| doc.node_at(up))) {
if !(clips(up) && up.editing_children().first().is_some_and(|f| f.id == n.id)) {
break;
}
path.pop();
}
paths.push(path);
}
// An object selected twice, or inside another selected object, is measured once, with it.
paths.sort();
paths.dedup();
let mut kept: Vec<Vec<usize>> = vec![];
for path in paths {
if !kept.last().is_some_and(|k| path.starts_with(k)) {
kept.push(path);
}
}
let mut parts = vec![];
'ids: for path in &kept {
let Some(n) = doc.node_at(path) else { continue };
// Art in a hidden group or layer isn't shown, and isn't measured.
if (1..path.len()).any(|depth| path.get(..depth).and_then(|p| doc.node_at(p)).is_some_and(|c| !c.visible)) {
continue;
}
let Some(mut region) = self.read(&[n])? else { continue };
// The containers around the object, innermost first.
let mut child = n.id;
for depth in (1..path.len()).rev() {
let Some(container) = path.get(..depth).and_then(|p| doc.node_at(p)) else { break };
if clips(container)
&& let Some(first) = container.editing_children().first().filter(|f| f.id != child)
{
let Some(clip) = self.clip_region(first)? else { continue 'ids };
region = Region::Clip { clip: Box::new(clip), content: Box::new(region) };
}
child = container.id;
}
parts.push(region);
}
Ok(union(parts))
}
/// A path, compound path or type as its outlines.
fn shape(&mut self, n: &Node) -> Result<Option<Region>, String> {
// Each anchor is at least one point, so a path past the budget errs before it is copied.
if anchors(n) > MAX_POINTS.saturating_sub(self.points) {
return Err(too_many());
}
let Some((path, rule)) = node_path(n) else { return Ok(None) };
let polys = self.polys(path.to_bezpath())?;
Ok((!polys.is_empty()).then_some(Region::Shape { polys, rule }))
}
/// The box of an object whose outlines can't be read.
fn frame(&mut self, n: &Node) -> Result<Option<Region>, String> {
match n.geometric_bounds_with(&self.doc.symbol_boxes()) {
Some(r) => self.polygon(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]),
None => Ok(None),
}
}
/// A closed polygon through `points`.
fn polygon(&mut self, points: &[Point]) -> Result<Option<Region>, String> {
let poly = poly(points.to_vec(), true);
self.count(poly.iter().map(|p| p.points.len()).sum())?;
Ok(poly.map(|p| Region::Shape { polys: vec![p], rule: FillRule::NonZero }))
}
fn count(&mut self, n: usize) -> Result<(), String> {
self.points = self.points.saturating_add(n);
if self.points > MAX_POINTS { Err(too_many()) } else { Ok(()) }
}
/// The subpaths of `path` followed in straight segments.
fn polys(&mut self, path: BezPath) -> Result<Vec<Poly>, String> {
let (mut out, mut current, points) = (vec![], vec![], Cell::new(0usize));
let left = MAX_POINTS.saturating_sub(self.points);
// Past the budget no further curve is followed (one curve gives at most
// `MAX_FLATTEN_PER_CURVE` points), and the read fails below.
let elements = path.into_iter().take_while(|_| points.get() <= left);
vectorcraft_geom::flatten(elements, TOLERANCE, |el| {
points.set(points.get() + 1);
if points.get() > left {
return;
}
match el {
PathEl::MoveTo(p) => {
out.extend(poly(std::mem::take(&mut current), false));
current.push(p);
}
PathEl::LineTo(p) => current.push(p),
PathEl::ClosePath => out.extend(poly(std::mem::take(&mut current), true)),
PathEl::QuadTo(..) | PathEl::CurveTo(..) => {}
}
});
if points.get() > left {
return Err(too_many());
}
out.extend(poly(current, false));
self.count(out.iter().map(|p: &Poly| p.points.len()).sum())?;
Ok(out)
}
}
fn too_many() -> String {
format!("the selected art has too many outline points to measure (more than {MAX_POINTS})")
}
/// The anchors of a path or compound path node, read without copying its path; 0 for type.
fn anchors(n: &Node) -> usize {
match &n.kind {
NodeKind::Path { path, .. } => path.anchor_count(),
NodeKind::Compound { children, .. } => children.iter().fold(0, |sum, c| sum.saturating_add(anchors(c))),
_ => 0,
}
}
/// A subpath through `points`, `None` for fewer than two points or one that isn't finite.
fn poly(points: Vec<Point>, closed: bool) -> Option<Poly> {
if points.len() < 2 || points.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return None;
}
let first = *points.first()?;
let bounds = points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p));
Some(Poly { points, closed, bounds })
}
/// One region of `parts`, `None` when there are none.
fn union(mut parts: Vec<Region>) -> Option<Region> {
match parts.len() {
0 => None,
1 => parts.pop(),
_ => Some(Region::Union(parts)),
}
}
/// `p` as (along, across) a weeding line: horizontal lines run along x, vertical ones along y.
fn uv(p: Point, vertical: bool) -> (f64, f64) {
if vertical { (p.y, p.x) } else { (p.x, p.y) }
}
/// Sorts `spans` and joins those that overlap or touch.
fn merged(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out: Vec<(f64, f64)> = Vec::with_capacity(spans.len());
for (a, b) in spans {
match out.last_mut() {
Some(last) if a <= last.1 => last.1 = last.1.max(b),
_ => out.push((a, b)),
}
}
out
}
/// Where sorted, joined spans `a` and `b` overlap.
fn intersected(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> {
let (mut i, mut j, mut out) = (0, 0, vec![]);
while let (Some(&(a0, a1)), Some(&(b0, b1))) = (a.get(i), b.get(j)) {
let (lo, hi) = (a0.max(b0), a1.min(b1));
if lo <= hi {
out.push((lo, hi));
}
if a1 < b1 {
i += 1;
} else {
j += 1;
}
}
out
}
/// Where segment a→b crosses the line `across` = `c`, along it, and which way (1 when `across`
/// grows from a to b), `None` when it doesn't. Each crossing counts once: an end exactly on the
/// line counts as past it.
fn crosses(a: Point, b: Point, vertical: bool, c: f64) -> Option<(f64, i32)> {
let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical));
((v0 <= c && v1 > c) || (v1 <= c && v0 > c)).then(|| (u0 + (c - v0) * (u1 - u0) / (v1 - v0), if v1 > v0 { 1 } else { -1 }))
}
/// The stretches inside an area filled by `rule`, from where its outlines cross a line, sorted
/// along it.
fn filled(crossings: impl IntoIterator<Item = (f64, i32)>, rule: FillRule) -> Vec<(f64, f64)> {
let (mut winding, mut start, mut out) = (0, 0.0, vec![]);
let inside = |w: i32| match rule {
FillRule::NonZero => w != 0,
FillRule::EvenOdd => w % 2 != 0,
};
for (u, dir) in crossings {
let was = inside(winding);
winding += dir;
match (was, inside(winding)) {
(false, true) => start = u,
(true, false) => out.push((start, u)),
_ => {}
}
}
merged(out)
}
/// Where the closed outlines of a region's shapes cross a set of weeding lines: for each line, the
/// crossings as (shape, place along the line, direction), sorted by shape and then by place. Shapes
/// are numbered in the order [`Region::shapes`] lists them.
pub(super) type Crossings = Vec<Vec<(usize, f64, i32)>>;
/// Where the shapes of each part of a region are numbered among its [`Crossings`].
#[derive(Debug)]
pub(super) enum Layout {
Shape,
/// The number of each part's first shape, from the union's first, and the parts' layouts.
Union {
starts: Vec<usize>,
parts: Vec<Layout>,
},
/// The clipping path's shapes come first.
Clip {
clip_shapes: usize,
clip: Box<Layout>,
content: Box<Layout>,
},
}
impl Layout {
/// The layout of `region` and how many shapes it has.
pub(super) fn of(region: &Region) -> (Layout, usize) {
match region {
Region::Shape { .. } => (Layout::Shape, 1),
Region::Union(parts) => {
let (mut starts, mut layouts, mut n) = (vec![], vec![], 0);
for r in parts {
let (l, k) = Layout::of(r);
starts.push(n);
layouts.push(l);
n += k;
}
(Layout::Union { starts, parts: layouts }, n)
}
Region::Clip { clip, content } => {
let ((lc, a), (lt, b)) = (Layout::of(clip), Layout::of(content));
(Layout::Clip { clip_shapes: a, clip: Box::new(lc), content: Box::new(lt) }, a + b)
}
}
}
}
/// The [`Crossings`] of `region` with the lines `across` = v0 + (k + 1)·step, k < `count`. Errs
/// past [`MAX_NEAR`] crossings in all.
pub(super) fn crossings(region: &Region, vertical: bool, v0: f64, step: f64, count: usize) -> Result<Crossings, String> {
let mut shapes = vec![];
region.shapes(&mut shapes);
let at = |k: usize| v0 + step * (k as f64 + 1.0);
// The lines a segment may cross: those from just below its lower end to its higher end.
let candidates = |(a, b): Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
if step <= 0.0 || va == vb {
return 0..0;
}
let first = (((va.min(vb) - v0) / step).floor() - 1.0).clamp(0.0, count as f64);
let end = ((va.max(vb) - v0) / step).ceil().clamp(0.0, count as f64);
(first as usize)..(end as usize)
};
let closed = |polys: &[Poly]| polys.iter().filter(|p| p.closed).flat_map(Poly::segments).collect::<Vec<_>>();
let total = shapes.iter().flat_map(|(polys, _)| closed(polys)).fold(0usize, |n, s| n.saturating_add(candidates(s).len()));
if total > MAX_NEAR {
return Err("the weeding lines cross the art's outlines too many times to measure; use fewer lines".into());
}
let mut out: Crossings = vec![vec![]; count];
for (i, (polys, _)) in shapes.iter().enumerate() {
for (a, b) in closed(polys) {
for k in candidates((a, b)) {
if let (Some((u, dir)), Some(line)) = (crosses(a, b, vertical, at(k)), out.get_mut(k)) {
line.push((i, u, dir));
}
}
}
}
for line in &mut out {
line.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
}
Ok(out)
}
impl Region {
/// The stretches of the line `across` = `c` (horizontal: y = c, along x; vertical: x = c,
/// along y) inside the region's area, sorted and joined.
pub(super) fn spans(&self, vertical: bool, c: f64) -> Vec<(f64, f64)> {
match self {
Region::Shape { polys, rule } => {
let mut crossings: Vec<(f64, i32)> = vec![];
for p in polys.iter().filter(|p| p.closed) {
let (lo, hi) = if vertical { (p.bounds.x0, p.bounds.x1) } else { (p.bounds.y0, p.bounds.y1) };
if c >= lo && c <= hi {
crossings.extend(p.segments().filter_map(|(a, b)| crosses(a, b, vertical, c)));
}
}
crossings.sort_by(|a, b| a.0.total_cmp(&b.0));
filled(crossings, *rule)
}
Region::Union(parts) => merged(parts.iter().flat_map(|r| r.spans(vertical, c)).collect()),
Region::Clip { clip, content } => intersected(&clip.spans(vertical, c), &content.spans(vertical, c)),
}
}
/// The region's shapes with their fill rules, in a fixed order.
fn shapes<'a>(&'a self, out: &mut Vec<(&'a [Poly], FillRule)>) {
match self {
Region::Shape { polys, rule } => out.push((polys, *rule)),
Region::Union(parts) => parts.iter().for_each(|r| r.shapes(out)),
Region::Clip { clip, content } => {
clip.shapes(out);
content.shapes(out);
}
}
}
/// [`Region::spans`] on a weeding line, from `line`, the line's [`Crossings`] with the
/// region's shapes, numbered from `base` (`layout` is the region's [`Layout`]). Only the parts
/// the line crosses are visited: a part it doesn't cross has no stretch inside its area.
pub(super) fn spans_on(&self, layout: &Layout, line: &[(usize, f64, i32)], base: usize) -> Vec<(f64, f64)> {
if line.is_empty() {
return vec![];
}
match (self, layout) {
(Region::Shape { rule, .. }, Layout::Shape) => filled(line.iter().map(|&(_, u, dir)| (u, dir)), *rule),
(Region::Union(parts), Layout::Union { starts, parts: layouts }) => {
let (mut out, mut rest) = (vec![], line);
while let Some(&(id, ..)) = rest.first() {
// The part whose shapes the next crossing is on, and its crossings.
let j = starts.partition_point(|&s| base + s <= id).saturating_sub(1);
let (Some(r), Some(l), Some(&start)) = (parts.get(j), layouts.get(j), starts.get(j)) else { break };
let end = starts.get(j + 1).map_or(usize::MAX, |&s| base + s);
let n = rest.partition_point(|c| c.0 < end);
if n == 0 {
break;
}
let (mine, after) = rest.split_at(n);
out.extend(r.spans_on(l, mine, base + start));
rest = after;
}
merged(out)
}
(Region::Clip { clip, content }, Layout::Clip { clip_shapes, clip: lc, content: lt }) => {
let (a, b) = line.split_at(line.partition_point(|c| c.0 < base + clip_shapes));
if a.is_empty() || b.is_empty() {
return vec![];
}
intersected(&clip.spans_on(lc, a, base), &content.spans_on(lt, b, base + clip_shapes))
}
_ => vec![],
}
}
/// Is `p` inside the region's area or on one of `segments`, the outlines it shows?
fn contains(&self, p: Point, segments: &[Segment]) -> bool {
const EPS: f64 = 1e-7;
self.spans(false, p.y).iter().any(|&(a, b)| p.x >= a - EPS && p.x <= b + EPS) || segments.iter().any(|&(a, b)| distance(p, a, b) <= EPS)
}
/// The pieces of outline the region shows: every outline of a shape and of a group's members,
/// and in a clip group the members' outlines inside the clipping path and the clipping path's
/// outline where the members' area or outlines are. Errs past [`MAX_PAIRS`], counted over
/// every clip group in the region together.
pub(super) fn outline(&self) -> Result<Vec<Segment>, String> {
self.outline_counted(&mut 0)
}
/// [`Region::outline`], adding the measure's work to `work`.
fn outline_counted(&self, work: &mut usize) -> Result<Vec<Segment>, String> {
match self {
Region::Shape { polys, .. } => Ok(polys.iter().flat_map(Poly::segments).collect()),
Region::Union(parts) => {
let mut out = vec![];
for r in parts {
out.extend(r.outline_counted(work)?);
}
Ok(out)
}
Region::Clip { clip, content } => {
// Each side's area is bounded by the outlines it shows, so the pieces are cut and
// tested against those, never against art a nested clip hides.
let (clip_shown, content_shown) = (clip.outline_counted(work)?, content.outline_counted(work)?);
let mut out = within(&content_shown, clip, &clip_shown, work)?;
out.extend(within(&clip_shown, content, &content_shown, work)?);
Ok(out)
}
}
}
/// The points of the region's closed outlines, those a nested clip hides included: what one
/// [`Region::spans`] looks at, at most.
fn closed_points(&self) -> usize {
match self {
Region::Shape { polys, .. } => polys.iter().filter(|p| p.closed).map(|p| p.points.len()).sum(),
Region::Union(parts) => parts.iter().map(Region::closed_points).sum(),
Region::Clip { clip, content } => clip.closed_points().saturating_add(content.closed_points()),
}
}
}
fn too_complex_clip() -> String {
"a clip group in the selection has too many outline segments to measure".into()
}
/// The pieces of `segments` inside `region` (or on its outlines), cut where they cross
/// `region_segments`, the outlines the region shows. Each segment, and each piece of one tested
/// for being inside, adds the region's closed outline points (hidden ones included) and its
/// shown segment count to `work`, and the measure errs past [`MAX_PAIRS`].
fn within(segments: &[Segment], region: &Region, region_segments: &[Segment], work: &mut usize) -> Result<Vec<Segment>, String> {
let mut out = vec![];
let cost = region.closed_points().saturating_add(region_segments.len()).max(1);
let charge = |work: &mut usize| {
*work = work.saturating_add(cost);
if *work > MAX_PAIRS { Err(too_complex_clip()) } else { Ok(()) }
};
for &(a, b) in segments {
charge(work)?;
let mut cuts = vec![0.0, 1.0];
let seg_box = Rect::from_points(a, b);
for &(c, d) in region_segments {
if touches(seg_box, Rect::from_points(c, d)) {
cuts.extend(crossing(a, b, c, d));
}
}
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|x, y| (*x - *y).abs() < 1e-12);
let at = |t: f64| a + (b - a) * t;
for w in cuts.windows(2) {
let (t0, t1) = (w[0], w[1]);
if t1 - t0 < 1e-12 {
continue;
}
charge(work)?;
if region.contains(at((t0 + t1) / 2.0), region_segments) {
out.push((at(t0), at(t1)));
}
}
}
Ok(out)
}
/// Do boxes `a` and `b` overlap or touch?
fn touches(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// Where along a→b (0 to 1) segment c→d crosses or touches it: one place, or the ends of the
/// shared stretch when the two lie on one line.
fn crossing(a: Point, b: Point, c: Point, d: Point) -> Vec<f64> {
let (r, s) = (b - a, d - c);
let denom = r.cross(s);
let qp = c - a;
let len2 = r.hypot2();
if len2 == 0.0 {
return vec![];
}
if denom.abs() <= 1e-12 * len2.sqrt() * s.hypot().max(1e-300) {
// Parallel: the ends of c→d on a→b when the two lie on one line.
if qp.cross(r).abs() > 1e-9 * len2.sqrt() {
return vec![];
}
return [c, d].iter().map(|p| (*p - a).dot(r) / len2).filter(|t| (0.0..=1.0).contains(t)).collect();
}
let t = qp.cross(s) / denom;
let u = qp.cross(r) / denom;
if (0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u) { vec![t] } else { vec![] }
}
/// The distance from `p` to segment a→b.
fn distance(p: Point, a: Point, b: Point) -> f64 {
let ab = b - a;
let len2 = ab.hypot2();
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
(p - (a + ab * t)).hypot()
}
/// The stretch of the line `across` = `c` within `gap` of segment a→b, `None` when the line
/// passes farther away. With no gap it is where the segment meets the line.
fn near(a: Point, b: Point, vertical: bool, c: f64, gap: f64) -> Option<(f64, f64)> {
let ((u0, v0), (u1, v1)) = (uv(a, vertical), uv(b, vertical));
if gap <= 0.0 {
if v0 == v1 {
return (v0 == c).then_some((u0.min(u1), u0.max(u1)));
}
if c < v0.min(v1) || c > v0.max(v1) {
return None;
}
let u = u0 + (c - v0) * (u1 - u0) / (v1 - v0);
return Some((u, u));
}
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
let mut take = |x: f64, y: f64| {
lo = lo.min(x);
hi = hi.max(y);
};
// The round ends.
for (u, v) in [(u0, v0), (u1, v1)] {
let dv = (c - v).abs();
if dv <= gap {
let h = (gap * gap - dv * dv).max(0.0).sqrt();
take(u - h, u + h);
}
}
// The band along the segment: points whose foot falls on it, within the gap of it.
let (du, dv) = (u1 - u0, v1 - v0);
let len = du.hypot(dv);
if len > 0.0 {
// Each condition is linear in the position x along the line: k·x + m ≥ 0.
let mut range = (f64::NEG_INFINITY, f64::INFINITY);
let mut keep = |k: f64, m: f64| {
if k == 0.0 {
if m < 0.0 {
range = (1.0, 0.0);
}
} else if k > 0.0 {
range.0 = range.0.max(-m / k);
} else {
range.1 = range.1.min(-m / k);
}
};
// The foot at or after a: (x - u0)·du + (c - v0)·dv ≥ 0.
keep(du, -u0 * du + (c - v0) * dv);
// The foot at or before b.
keep(-du, u0 * du - (c - v0) * dv + len * len);
// Within the gap on either side: |(x - u0)·dv - (c - v0)·du| ≤ gap·len.
let cross0 = -u0 * dv - (c - v0) * du;
keep(-dv, -cross0 + gap * len);
keep(dv, cross0 + gap * len);
if range.0 <= range.1 {
take(range.0, range.1);
}
}
(lo <= hi).then_some((lo, hi))
}
/// How many weeding lines run each way.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Counts {
pub horizontal: usize,
pub vertical: usize,
}
/// The weeding lines across `frame`: `n.horizontal` horizontal and `n.vertical` vertical lines that
/// divide it evenly, each from one side of the frame to the other, left out where it is inside the
/// region's area or within `gap` of one of its outlines (`outline`). Pieces are in order along each
/// line, the horizontal lines first, top to bottom. Errs past [`MAX_NEAR`] pairs of an outline
/// segment and a line it comes within `gap` of, past [`MAX_NEAR`] crossings of the region's
/// outlines with the lines one way, or past `max_pieces` pieces.
pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts, gap: f64, max_pieces: usize) -> Result<Vec<Segment>, String> {
let mut out = vec![];
let (layout, _) = Layout::of(region);
for (vertical, count) in [(false, n.horizontal), (true, n.vertical)] {
let ((u0, v0), (u1, v1)) = (uv(Point::new(frame.x0, frame.y0), vertical), uv(Point::new(frame.x1, frame.y1), vertical));
let step = (v1 - v0) / (count as f64 + 1.0);
// A frame with no height (for horizontal lines) or no width has no waste to divide.
if step <= 0.0 {
continue;
}
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
// v0 + k·step.
let reach = |&(a, b): &Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
let first = ((lo - v0) / step).ceil().max(1.0);
let last = ((hi - v0) / step).floor().min(count as f64);
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
};
// The outlines near each line, found once for all of them, by index into `outline`.
let pairs = outline.iter().fold(0usize, |sum, s| sum.saturating_add(reach(s).len()));
if pairs > MAX_NEAR {
return Err("the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap".into());
}
let mut near_line: Vec<Vec<usize>> = vec![vec![]; count];
for (j, s) in outline.iter().enumerate() {
for k in reach(s) {
if let Some(list) = near_line.get_mut(k) {
list.push(j);
}
}
}
let crossed = crossings(region, vertical, v0, step, count)?;
for (i, segments) in near_line.iter().enumerate() {
let c = v0 + step * (i as f64 + 1.0);
let mut blocked = region.spans_on(&layout, crossed.get(i).map(Vec::as_slice).unwrap_or_default(), 0);
blocked.extend(segments.iter().filter_map(|&j| outline.get(j)).filter_map(|&(a, b)| near(a, b, vertical, c, gap)));
let mut from = u0;
let point = |u: f64| if vertical { Point::new(c, u) } else { Point::new(u, c) };
for (a, b) in merged(blocked) {
if a - from >= MIN_PIECE && a <= u1 {
out.push((point(from), point(a.min(u1))));
}
from = from.max(b);
}
if u1 - from >= MIN_PIECE {
out.push((point(from), point(u1)));
}
if out.len() > max_pieces {
return Err(format!("the weeding lines would be more than {max_pieces} pieces"));
}
}
}
Ok(out)
}
@@ -0,0 +1,915 @@
//! Tests for `addon.cutting.weed`: a weed box around the selected art and weeding lines across it
//! that stop at the art's outlines.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes};
use super::super::super::super::pathops::text_outline;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
}
fn line(s: &mut Session, pts: &[(f64, f64)]) -> NodeId {
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap())
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
/// Runs Weed Box and Lines with `p` and gives the group it made.
fn weed(s: &mut Session, p: Value) -> (Value, Node) {
let r = s.execute("addon.cutting.weed", &p).unwrap();
let g = node(s, id_of(&r));
(r, g)
}
/// The weed box's rectangle in group `g`, if it has one.
fn weed_box(g: &Node) -> Option<Rect> {
g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).map(|c| c.geometric_bounds().unwrap())
}
/// The weeding lines in group `g` as their two ends, rounded to 1/1000 pt.
fn lines(g: &Node) -> Vec<((f64, f64), (f64, f64))> {
let r = |v: f64| (v * 1000.0).round() / 1000.0;
g.children()
.unwrap()
.iter()
.filter(|c| c.name.is_none())
.map(|c| match &c.kind {
NodeKind::Path { path, .. } => {
let a: Vec<Point> = path.anchors().map(|(_, _, a)| a.p).collect();
assert_eq!(a.len(), 2, "a weeding line is one straight segment");
((r(a[0].x), r(a[0].y)), (r(a[1].x), r(a[1].y)))
}
other => panic!("not a path: {other:?}"),
})
.collect()
}
#[test]
fn a_weed_box_and_lines_go_around_a_rectangle() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let undo = s.doc().unwrap().history.undo.len();
let (r, g) = weed(&mut s, json!({"margin": 10}));
assert_eq!(g.name.as_deref(), Some("Weeding"));
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0)));
// One line each way through the middle, left out over the art.
assert_eq!(
lines(&g),
[((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (160.0, 120.0)), ((125.0, 90.0), (125.0, 100.0)), ((125.0, 140.0), (125.0, 150.0))]
);
assert_eq!(r["lines"], json!(4));
assert_eq!(r["box"], json!(weed_box_id(&g)));
// Stroked in Registration with no fill, selected, as one undo step that takes it all away.
for c in g.children().unwrap() {
assert_eq!(c.appearance.fill_paint(), Paint::None, "no fill");
assert!(c.appearance.stroke_paint().is_registration());
}
assert_eq!(s.doc().unwrap().selection.objects, [g.id]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(g.id).is_none());
}
fn weed_box_id(g: &Node) -> u64 {
g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Weed Box")).unwrap().id.0
}
#[test]
fn lines_stop_at_the_outline_and_cross_the_hole_of_a_compound_path() {
let mut s = session();
let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0);
select(&mut s, &[outer, inner]);
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
// Both subpaths wind the same way, so the fill rule alone decides whether the inner one is a
// hole.
let same_way = |rule: FillRule| {
move |d: &mut vectorcraft_doc::Document, _: &mut vectorcraft_doc::Selection| -> Result<()> {
let Some(NodeKind::Compound { children, rule: r }) = d.node_mut(c).map(|n| &mut n.kind) else { panic!("not a compound path") };
*r = rule;
let area = |n: &Node| match &n.kind {
NodeKind::Path { path, .. } => path.subpaths[0].signed_area(),
_ => panic!("not a path"),
};
let outer = area(&children[0]).signum();
for child in children.iter_mut() {
if area(child).signum() != outer
&& let NodeKind::Path { path, .. } = &mut std::sync::Arc::make_mut(child).kind
{
path.reverse();
}
}
Ok(())
}
};
s.edit("even-odd", same_way(FillRule::EvenOdd)).unwrap();
select(&mut s, &[c]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The waste in the hole is cut too; the ring itself is not.
assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((130.0, 150.0), (170.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]);
// With the non-zero rule the inner subpath fills, and no line crosses it.
s.edit("non-zero", same_way(FillRule::NonZero)).unwrap();
select(&mut s, &[c]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
assert_eq!(lines(&g), [((90.0, 150.0), (100.0, 150.0)), ((200.0, 150.0), (210.0, 150.0))]);
}
#[test]
fn a_gap_keeps_the_lines_away_from_the_outline() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let (_, g) = weed(&mut s, json!({"margin": 20, "gap": 5, "direction": "horizontal"}));
assert_eq!(weed_box(&g), Some(Rect::new(80.0, 80.0, 170.0, 160.0)));
assert_eq!(lines(&g), [((80.0, 120.0), (95.0, 120.0)), ((155.0, 120.0), (170.0, 120.0))]);
// The gap is a distance from the outline: a line passing 5 pt beside a corner, with a gap of
// 6, stops √11 pt short of the corner's height.
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let b = rect(&mut s, 200.0, 60.0, 10.0, 120.0);
select(&mut s, &[a, b]);
let (_, g) = weed(&mut s, json!({"margin": 0, "gap": 6, "direction": "vertical"}));
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 60.0, 210.0, 180.0)));
assert_eq!(lines(&g), [((155.0, 60.0), (155.0, 96.683)), ((155.0, 143.317), (155.0, 180.0))]);
}
#[test]
fn a_box_with_no_height_gets_no_lines_across_it() {
// A horizontal line with no margin: the box is as flat as the line, and no weeding line runs
// along it.
let mut s = session();
let l = line(&mut s, &[(100.0, 150.0), (200.0, 150.0)]);
let n = s.doc().unwrap().doc.node_count();
assert!(s.execute("addon.cutting.weed", &json!({"margin": 0, "direction": "horizontal", "box": false})).is_err());
assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing to add");
select(&mut s, &[l]);
let (_, g) = weed(&mut s, json!({"margin": 0, "direction": "horizontal"}));
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 150.0, 200.0, 150.0)));
assert_eq!(lines(&g), []);
}
#[test]
fn an_open_path_stops_a_line_where_it_crosses() {
let mut s = session();
line(&mut s, &[(100.0, 100.0), (100.0, 200.0)]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal", "gap": 2}));
assert_eq!(lines(&g), [((90.0, 150.0), (98.0, 150.0)), ((102.0, 150.0), (110.0, 150.0))]);
}
#[test]
fn type_is_measured_by_its_glyph_outlines() {
let mut s = session();
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "OHO", "size": 72})).unwrap());
let glyphs = match &node(&s, t).kind {
NodeKind::Text(t) => text_outline(t),
_ => panic!("not type"),
};
let ink = glyphs.bounds().unwrap();
let (_, g) = weed(&mut s, json!({"margin": 10, "count": 3, "direction": "horizontal"}));
let b = weed_box(&g).unwrap();
for (got, want) in [(b.x0, ink.x0 - 10.0), (b.y0, ink.y0 - 10.0), (b.x1, ink.x1 + 10.0), (b.y1, ink.y1 + 10.0)] {
assert!((got - want).abs() < 0.05, "the box is 10 pt around the glyphs: {b:?} vs {ink:?}");
}
// No piece of line runs over a glyph: each piece's middle is outside the ink.
let shape = glyphs.to_bezpath();
let pieces = lines(&g);
assert!(pieces.len() > 3, "the letters break the lines: {pieces:?}");
for ((x0, y0), (x1, y1)) in pieces {
let mid = Point::new((x0 + x1) / 2.0, (y0 + y1) / 2.0);
assert_eq!(shape.winding(mid), 0, "{mid:?} is outside the glyphs");
}
}
#[test]
fn a_clip_group_is_measured_by_what_shows() {
let mut s = session();
let big = rect(&mut s, 0.0, 0.0, 400.0, 300.0);
let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
select(&mut s, &[big, clip]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let (_, g) = weed(&mut s, json!({"margin": 10}));
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 160.0, 150.0)));
assert_eq!(lines(&g).len(), 4);
// Art that shows only partly: the clip path's edge where the art is, and the art's edge
// inside the clip.
let mut s = session();
let art = rect(&mut s, 120.0, 0.0, 100.0, 300.0);
let clip = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
select(&mut s, &[art, clip]);
s.execute("object.clippingMask.make", &json!({})).unwrap();
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
assert_eq!(weed_box(&g), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
assert_eq!(lines(&g), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]);
}
#[test]
fn a_group_as_the_clipping_path_clips_by_its_members() {
// Make Clipping Mask takes a path, a compound path or type; an opened file can clip by a
// group, as this one does.
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("clip group", |d, sel| {
let mut r = |x: f64, w: f64, y: f64, h: f64| {
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + w, y + h)), Appearance::default()))
};
let (a, b, art) = (r(100.0, 50.0, 100.0, 40.0), r(250.0, 50.0, 100.0, 40.0), r(0.0, 400.0, 0.0, 300.0));
let clip = Arc::new(Node::group(d.alloc_id(), vec![a, b]));
let mut g = Node::group(d.alloc_id(), vec![clip, art]);
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
let id = g.id;
d.insert(parent, usize::MAX, g)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(&mut s, &[id]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The art shows through both rectangles, and the line is cut between them too.
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 310.0, 150.0)));
assert_eq!(lines(&g), [((90.0, 120.0), (100.0, 120.0)), ((150.0, 120.0), (250.0, 120.0)), ((300.0, 120.0), (310.0, 120.0))]);
}
#[test]
fn lines_near_too_many_outline_segments_are_refused() {
let mut s = session();
// A zigzag of 12,000 segments; with a gap as tall as the box, each of 1,000 lines comes near
// every segment.
let mut zigzag = BezPath::new();
zigzag.move_to((100.0, 100.0));
for i in 1..=12_000 {
zigzag.line_to((100.0 + f64::from(i) * 0.01, if i % 2 == 0 { 100.0 } else { 101.0 }));
}
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("zigzag", |d, sel| {
let n = Node::path(d.alloc_id(), PathData::from_bezpath(&zigzag), Appearance::default());
let id = n.id;
d.insert(parent, usize::MAX, n)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(&mut s, &[id]);
let n = s.doc().unwrap().doc.node_count();
let e = s.execute("addon.cutting.weed", &json!({"count": 1000, "gap": 50, "direction": "horizontal"})).unwrap_err();
assert!(e.to_string().contains("too many outline segments"), "{e}");
assert_eq!(s.doc().unwrap().doc.node_count(), n);
// Fewer lines measure.
s.execute("addon.cutting.weed", &json!({"count": 10, "gap": 50, "direction": "horizontal"})).unwrap();
}
/// Adds a clip group, clipping path `clip` over `art` (both unpainted), and selects it.
fn clip_group(s: &mut Session, clip: PathData, art: PathData) -> NodeId {
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("clip group", |d, sel| {
let clip = Arc::new(Node::path(d.alloc_id(), clip, Appearance::default()));
let art = Arc::new(Node::path(d.alloc_id(), art, Appearance::default()));
let mut g = Node::group(d.alloc_id(), vec![clip, art]);
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
let id = g.id;
d.insert(parent, usize::MAX, g)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(s, &[id]);
id
}
#[test]
fn an_open_clipping_path_clips_as_if_closed() {
let mut s = session();
let mut v = BezPath::new();
v.move_to((100.0, 100.0));
v.line_to((150.0, 200.0));
v.line_to((200.0, 100.0));
clip_group(&mut s, PathData::from_bezpath(&v), shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 300.0)));
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The art shows inside the triangle the V closes; the line stops at its sides.
assert_eq!(weed_box(&g), Some(Rect::new(90.0, 90.0, 210.0, 210.0)));
assert_eq!(lines(&g), [((90.0, 150.0), (125.0, 150.0)), ((175.0, 150.0), (210.0, 150.0))]);
}
#[test]
fn art_a_nested_clip_hides_adds_no_outline() {
// A clip group, clipping path A, holding a clip group whose clipping path B shows a small
// rectangle and hides a line that runs along A's bottom edge.
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("nested clips", |d, sel| {
let mut path = |p: PathData| Arc::new(Node::path(d.alloc_id(), p, Appearance::default()));
let mut l = BezPath::new();
l.move_to((0.0, 200.0));
l.line_to((400.0, 200.0));
let (b, shown, hidden) = (
path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0))),
path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0))),
path(PathData::from_bezpath(&l)),
);
let a = path(shapes::rectangle(Rect::new(50.0, 50.0, 300.0, 200.0)));
let clipped = |mut g: Node| {
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
g
};
let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, hidden])));
let outer = clipped(Node::group(d.alloc_id(), vec![a, inner]));
let id = outer.id;
d.insert(parent, usize::MAX, outer)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(&mut s, &[id]);
let (_, g) = weed(&mut s, json!({"margin": 10, "count": 0}));
assert_eq!(weed_box(&g), Some(Rect::new(100.0, 100.0, 150.0, 140.0)), "only the shown rectangle is measured");
}
#[test]
fn art_a_nested_clip_hides_counts_toward_the_clip_limit() {
// A clip group, clipping path A of 20,000 segments, holding a clip group whose small clipping
// path B shows a rectangle and hides a closed zigzag C of 20,000 points across every row of A.
// The inner group shows four outline pieces, but testing each piece of A for being inside it
// looks at all of C.
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("nested clips", |d, sel| {
let mut path = |p: BezPath| Arc::new(Node::path(d.alloc_id(), PathData::from_bezpath(&p), Appearance::default()));
let mut a = BezPath::new();
a.move_to((0.0, 0.0));
for i in 1..=20_000 {
a.line_to((f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 0.5 }));
}
a.line_to((400.0, 300.0));
a.line_to((0.0, 300.0));
a.close_path();
let mut c = BezPath::new();
c.move_to((300.0, 0.0));
for i in 1..=20_000 {
c.line_to((300.0 + f64::from(i) * 0.002, if i % 2 == 0 { 0.0 } else { 300.0 }));
}
c.close_path();
let b = path(shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)).to_bezpath());
let shown = path(shapes::rectangle(Rect::new(110.0, 110.0, 140.0, 130.0)).to_bezpath());
let (a, c) = (path(a), path(c));
let clipped = |mut g: Node| {
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
g
};
let inner = Arc::new(clipped(Node::group(d.alloc_id(), vec![b, shown, c])));
let outer = clipped(Node::group(d.alloc_id(), vec![a, inner]));
let id = outer.id;
d.insert(parent, usize::MAX, outer)?;
sel.set([id]);
Ok(id)
})
.unwrap();
select(&mut s, &[id]);
let n = s.doc().unwrap().doc.node_count();
let e = s.execute("addon.cutting.weed", &json!({"margin": 10, "count": 0})).unwrap_err();
assert!(e.to_string().contains("too many outline segments"), "{e}");
assert_eq!(s.doc().unwrap().doc.node_count(), n);
}
#[test]
fn art_selected_inside_a_clip_group_is_measured_by_what_shows() {
// The rectangle runs far outside the clipping path; selected on its own, it still shows only
// inside it.
let mut s = session();
let clip = shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0));
let g = clip_group(&mut s, clip, shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)));
let art = node(&s, g).children().unwrap()[1].id;
select(&mut s, &[art]);
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
assert_eq!(lines(&w), [((110.0, 120.0), (120.0, 120.0)), ((150.0, 120.0), (160.0, 120.0))]);
// The clipping path selected on its own is measured by the art it shows.
let clip_path = node(&s, g).children().unwrap()[0].id;
select(&mut s, &[clip_path]);
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
// With the art selected too, or the group, the group is measured once.
let d = &s.doc().unwrap().doc;
let outline = |ids: &[NodeId]| super::geometry::Reader::new(d).read_ids(ids).unwrap().unwrap().outline().unwrap().len();
assert_eq!(outline(&[clip_path, art]), outline(&[g]));
assert_eq!(outline(&[g, art, g]), outline(&[g]));
}
#[test]
fn art_in_a_hidden_group_is_left_out() {
let mut s = session();
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let b = rect(&mut s, 200.0, 100.0, 50.0, 40.0);
select(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.edit("hide", |d, _| {
if let Some(n) = d.node_mut(g) {
n.visible = false;
}
Ok(())
})
.unwrap();
select(&mut s, &[a]);
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "nothing selected shows");
select(&mut s, &[a, shown]);
let (_, w) = weed(&mut s, json!({"margin": 10}));
assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
}
#[test]
fn art_in_a_hidden_group_is_not_measured() {
// Selected art in a hidden group with more outline points than the limit doesn't count toward
// it.
let mut s = session();
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
let mut p = BezPath::new();
p.move_to((100.0, 100.0));
for i in 1..=super::geometry::MAX_POINTS as u32 {
p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
}
let dense = insert(&mut s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()));
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.edit("hide", |d, _| {
if let Some(n) = d.node_mut(g) {
n.visible = false;
}
Ok(())
})
.unwrap();
select(&mut s, &[dense, shown]);
let (_, w) = weed(&mut s, json!({"margin": 10}));
assert_eq!(weed_box(&w), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
}
#[test]
fn clip_outlines_crossing_too_often_are_refused() {
// A clipping path whose 700 edges each run across the art, and open art whose 700 segments
// each run down across the clipping path: every pair crosses, and each of the 490,000 pieces
// of art between crossings would be tested against all 700 edges.
let zigzag = |across: bool| {
let mut p = BezPath::new();
for i in 0..=700 {
let (along, side) = (100.0 + f64::from(i) * 0.25, if i % 2 == 0 { 100.0 } else { 300.0 });
let pt = if across { (side, along) } else { (along, side) };
if i == 0 { p.move_to(pt) } else { p.line_to(pt) }
}
p
};
let mut clip = zigzag(true);
clip.close_path();
let mut s = session();
clip_group(&mut s, PathData::from_bezpath(&clip), PathData::from_bezpath(&zigzag(false)));
let n = s.doc().unwrap().doc.node_count();
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
assert!(e.to_string().contains("too many outline segments"), "{e}");
assert_eq!(s.doc().unwrap().doc.node_count(), n);
}
/// Each weeding line's stretches inside the art, found from the crossings indexed once for all the
/// lines, match those found by measuring the whole art along that line.
#[test]
fn indexed_crossings_find_the_same_stretches() {
let mut s = session();
let mut ids = vec![];
let outer = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let inner = rect(&mut s, 130.0, 130.0, 40.0, 40.0);
select(&mut s, &[outer, inner]);
ids.push(id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()));
let big = rect(&mut s, 220.0, 50.0, 200.0, 200.0);
let window = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 80, "width": 90, "height": 120})).unwrap());
select(&mut s, &[big, window]);
ids.push(id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()));
ids.push(id_of(&s.execute("text.create", &json!({"x": 100, "y": 320, "text": "WEED 8", "size": 60})).unwrap()));
ids.push(line(&mut s, &[(90.0, 40.0), (450.0, 380.0)]));
let a = rect(&mut s, 300.0, 300.0, 30.0, 30.0);
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 320, "y": 310, "width": 60, "height": 40})).unwrap());
select(&mut s, &[a, b]);
ids.push(id_of(&s.execute("object.group", &json!({})).unwrap()));
let d = &s.doc().unwrap().doc;
let nodes: Vec<&Node> = ids.iter().filter_map(|id| d.node(*id)).collect();
let region = super::geometry::Reader::new(d).read(&nodes).unwrap().unwrap();
let (layout, _) = super::geometry::Layout::of(&region);
let count = 97;
for vertical in [false, true] {
let (v0, v1) = (30.0, 400.0);
let step = (v1 - v0) / (count as f64 + 1.0);
let crossed = super::geometry::crossings(&region, vertical, v0, step, count).unwrap();
assert_eq!(crossed.len(), count);
let mut hit = 0;
for (k, line) in crossed.iter().enumerate() {
let c = v0 + step * (k as f64 + 1.0);
let want = region.spans(vertical, c);
hit += usize::from(!want.is_empty());
assert_eq!(region.spans_on(&layout, line, 0), want, "line {k}, vertical {vertical}");
}
assert!(hit > count / 2, "most lines cross the art ({hit})");
}
}
#[test]
fn art_nested_too_deep_is_refused() {
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
// but the art symbol instances and live objects draw nests further.
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
let nested = |levels: usize| {
let mut n = Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default());
for i in 0..levels {
n = Node::group(NodeId(i as u64 + 2), vec![Arc::new(n)]);
}
n
};
let read = |n: &Node| super::geometry::Reader::new(&doc).read(&[n]);
assert!(read(&nested(super::geometry::MAX_DEPTH)).unwrap().is_some());
let e = read(&nested(super::geometry::MAX_DEPTH + 1)).unwrap_err();
assert!(e.contains("nested more than"), "{e}");
}
#[test]
fn spacing_divides_the_box_into_strips_no_wider() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 10.0, 40.0);
// The box is 60 pt tall: three strips of 20 pt.
let (_, g) = weed(&mut s, json!({"margin": 10, "spacing": 25, "direction": "horizontal", "box": false}));
assert_eq!(weed_box(&g), None);
let ys: Vec<f64> = lines(&g).iter().map(|l| l.0.1).collect();
assert_eq!(ys, [110.0, 110.0, 130.0, 130.0]);
let mut s = session();
rect(&mut s, 100.0, 100.0, 10.0, 40.0);
assert!(s.execute("addon.cutting.weed", &json!({"spacing": 0.01})).is_err(), "too many lines");
}
#[test]
fn the_lines_take_a_swatch() {
let mut s = session();
s.execute("swatch.new", &json!({"name": "Cut", "color": "cmyk 0 100 0 0", "spot": true})).unwrap();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let (_, g) = weed(&mut s, json!({"swatch": "Cut", "weight": 1}));
for c in g.children().unwrap() {
match c.appearance.stroke_paint() {
Paint::Solid { swatch, .. } => assert_eq!(swatch.as_deref(), Some("Cut")),
other => panic!("stroke {other:?}"),
}
assert_eq!(c.appearance.stroke_width(), 1.0);
}
}
/// Adds the object `make` makes with a new id to the current layer, selects it and gives its id.
fn insert(s: &mut Session, make: impl FnOnce(NodeId) -> Node) -> NodeId {
let parent = s.doc().unwrap().target_parent().unwrap();
let id = s
.edit("insert", |d, _| {
let n = make(d.alloc_id());
let id = n.id;
d.insert(parent, usize::MAX, n)?;
Ok(id)
})
.unwrap();
select(s, &[id]);
id
}
/// A 100 pt square turned 45° about (300, 300): a diamond 141.42 pt across.
fn diamond_xf() -> Affine {
Affine::translate((300.0, 300.0)) * Affine::rotate(std::f64::consts::FRAC_PI_4) * Affine::translate((-50.0, -50.0))
}
/// The weeding lines of `g` at height `y` (to 1/1000 pt).
fn at(g: &Node, y: f64) -> Vec<(f64, f64)> {
lines(g).into_iter().filter(|((_, y0), (_, y1))| *y0 == y && *y1 == y).map(|((x0, _), (x1, _))| (x0, x1)).collect()
}
/// The diamond's weeding with three horizontal lines and a margin of 10: the box, and where the
/// first line's left piece ends.
fn diamond_weeding(s: &mut Session) -> (Rect, f64) {
let (_, g) = weed(s, json!({"margin": 10, "count": 3, "direction": "horizontal"}));
let b = weed_box(&g).unwrap();
let y = ((b.y0 + b.height() / 4.0) * 1000.0).round() / 1000.0;
let first = at(&g, y);
assert_eq!(first.len(), 2, "{first:?}");
(b, first[0].1)
}
#[test]
fn an_image_is_measured_by_its_frame_as_turned() {
let mut s = session();
let im = vectorcraft_doc::ImageObject {
key: "image".into(),
width: 100,
height: 100,
xf: diamond_xf(),
link: None,
placement: Default::default(),
pixels: None,
};
insert(&mut s, |id| Node::new(id, NodeKind::Image(Box::new(im))));
let (b, end) = diamond_weeding(&mut s);
let half = 50.0 * std::f64::consts::SQRT_2;
assert!((b.x0 - (290.0 - half)).abs() < 1e-3 && (b.y1 - (310.0 + half)).abs() < 1e-3, "{b:?}");
// A quarter of the box down, the line meets the diamond's upper left edge, not its bounds.
let y = b.y0 + b.height() / 4.0;
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
}
#[test]
fn a_placed_file_is_measured_by_the_art_it_shows() {
let dir = crate::tests_links::Folder::new("weed-placed");
// A file with a 60 × 40 artboard and a 20 pt wide rectangle at each side (hidden when
// `hidden`), placed centered on (200, 150) and selected.
let place = |s: &mut Session, name: &str, hidden: bool| {
let src = dir.file(name);
let mut d = vectorcraft_doc::Document::new(60.0, 40.0);
let layer = d.layers[0].id;
for x in [0.0, 40.0] {
let id = d.alloc_id();
let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
let mut n = Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 40.0)), look);
n.visible = !hidden;
d.insert(Some(layer), 0, n).unwrap();
}
crate::tests_links::write(&src, &vectorcraft_format::save_file(&d));
let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
select(s, &[NodeId(r["ids"][0].as_u64().unwrap())]);
};
let mut s = session();
place(&mut s, "pair.vectorcraft", false);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The rectangles lie at 170..190 and 210..230; the line runs between them too.
assert_eq!(at(&g, 150.0), [(160.0, 170.0), (190.0, 210.0), (230.0, 240.0)]);
// A file read but shown in a box with no size shows nothing, and its box isn't measured.
let id = NodeId(s.execute("file.place", &json!({"path": dir.file("pair.vectorcraft"), "at": [400, 150]})).unwrap()["ids"][0].as_u64().unwrap());
s.edit("no size", |d, _| {
if let Some(NodeKind::PlacedDocument(p)) = d.node_mut(id).map(|n| &mut n.kind) {
(p.width, p.height) = (0.0, 0.0);
}
Ok(())
})
.unwrap();
select(&mut s, &[id]);
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
assert!(e.to_string().contains("has no outlines"), "{e}");
// A file read with nothing showing has no outlines, and its box isn't measured instead.
let mut s = session();
place(&mut s, "hidden.vectorcraft", true);
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
assert!(e.to_string().contains("has no outlines"), "{e}");
// A file whose art is an instance of a symbol of its own: the instance's art is measured.
let src = dir.file("symbol.vectorcraft");
let mut d = vectorcraft_doc::Document::new(60.0, 40.0);
let look = Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0);
let art = Node::path(NodeId(900), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 40.0)), look);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(art) });
let (layer, id) = (d.layers[0].id, d.alloc_id());
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY })).unwrap();
crate::tests_links::write(&src, &vectorcraft_format::save_file(&d));
let mut s = session();
let r = s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
select(&mut s, &[NodeId(r["ids"][0].as_u64().unwrap())]);
let (_, g) = weed(&mut s, json!({"margin": 10}));
let b = weed_box(&g).unwrap();
assert!(b.x0 >= 160.0 - 1e-6 && b.x1 <= 240.0 + 1e-6 && b.width() < 41.0, "the bar, not the whole box: {b:?}");
}
#[test]
fn a_placed_file_that_cant_be_read_is_measured_by_its_box_as_turned() {
let mut s = session();
let p = vectorcraft_doc::PlacedDocument {
link: vectorcraft_doc::LinkInfo::new("/no/such/file.pdf"),
key: "missing".into(),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: diamond_xf(),
placement: Default::default(),
};
insert(&mut s, |id| Node::new(id, NodeKind::PlacedDocument(Box::new(p))));
let (b, end) = diamond_weeding(&mut s);
let half = 50.0 * std::f64::consts::SQRT_2;
let y = b.y0 + b.height() / 4.0;
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
}
#[test]
fn a_symbol_instance_is_measured_by_its_art() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0);
let b = rect(&mut s, 140.0, 100.0, 20.0, 40.0);
select(&mut s, &[a, b]);
let inst = id_of(&s.execute("symbol.new", &json!({"name": "Pair"})).unwrap());
select(&mut s, &[inst]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The line runs between the two rectangles too.
assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 140.0), (160.0, 170.0)]);
// An instance of a symbol the document doesn't have draws nothing, and has no outlines.
s.edit("lose the symbol", |d, _| {
if let Some(NodeKind::SymbolInstance { symbol, .. }) = d.node_mut(inst).map(|n| &mut n.kind) {
*symbol = "Missing".into();
}
Ok(())
})
.unwrap();
select(&mut s, &[inst]);
let n = s.doc().unwrap().doc.node_count();
let e = s.execute("addon.cutting.weed", &json!({})).unwrap_err();
assert!(e.to_string().contains("has no outlines"), "{e}");
assert_eq!(s.doc().unwrap().doc.node_count(), n);
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
select(&mut s, &[inst, shown]);
let (_, g) = weed(&mut s, json!({"margin": 10}));
assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
}
#[test]
fn a_blend_is_measured_by_the_art_it_draws() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 20.0, 40.0);
let b = rect(&mut s, 200.0, 100.0, 20.0, 40.0);
let blend = id_of(&s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 1})).unwrap());
select(&mut s, &[blend]);
let (_, g) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The step halfway between the two rectangles stops the line too.
assert_eq!(at(&g, 120.0), [(90.0, 100.0), (120.0, 150.0), (170.0, 200.0), (220.0, 230.0)]);
}
#[test]
fn the_group_goes_on_top_of_the_current_layer_and_hidden_layers_are_left_out() {
let mut s = session();
let first = s.doc().unwrap().doc.layers[0].id;
let hidden = rect(&mut s, 100.0, 100.0, 50.0, 40.0);
let art = id_of(&s.execute("layer.new", &json!({"name": "Art"})).unwrap());
let shown = rect(&mut s, 300.0, 300.0, 20.0, 20.0);
let below = rect(&mut s, 400.0, 400.0, 20.0, 20.0);
s.edit("hide", |d, _| {
if let Some(n) = d.node_mut(first) {
n.visible = false;
}
Ok(())
})
.unwrap();
select(&mut s, &[hidden]);
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "art in a hidden layer doesn't show");
select(&mut s, &[hidden, shown]);
let (_, g) = weed(&mut s, json!({"margin": 10}));
assert_eq!(weed_box(&g), Some(Rect::new(290.0, 290.0, 330.0, 330.0)));
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(g.id), Some(art));
assert_eq!(d.node(art).unwrap().children().unwrap().last().map(|c| c.id), Some(g.id), "on top");
// A hidden object selected on its own shows nothing.
s.edit("hide", |d, _| {
if let Some(n) = d.node_mut(below) {
n.visible = false;
}
Ok(())
})
.unwrap();
select(&mut s, &[below]);
assert!(s.execute("addon.cutting.weed", &json!({})).is_err(), "a hidden object doesn't show");
}
#[test]
fn the_group_goes_outside_a_clip_group_edited_in_isolation() {
let mut s = session();
let layer = s.doc().unwrap().doc.layers[0].id;
let g = clip_group(&mut s, shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)));
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let art = node(&s, g).children().unwrap()[1].id;
select(&mut s, &[art]);
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
// The clipping path would hide the lines and the box around the art inside it.
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(w.id), Some(layer));
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
// A plain group edited in isolation inside a clip group: the group goes outside the clip group.
let mut s = session();
let parent = s.doc().unwrap().target_parent().unwrap();
let (inner, art) = s
.edit("clip group around a group", |d, _| {
let clip = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 140.0)), Appearance::default()));
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(120.0, 0.0, 220.0, 300.0)), Appearance::default());
let art_id = art.id;
let inner = Node::group(d.alloc_id(), vec![Arc::new(art)]);
let inner_id = inner.id;
let mut g = Node::group(d.alloc_id(), vec![clip, Arc::new(inner)]);
if let NodeKind::Group { clip, .. } = &mut g.kind {
*clip = true;
}
d.insert(parent, usize::MAX, g)?;
Ok((inner_id, art_id))
})
.unwrap();
s.execute("object.isolate", &json!({"id": inner.0})).unwrap();
select(&mut s, &[art]);
let (_, w) = weed(&mut s, json!({"margin": 10, "direction": "horizontal"}));
assert_eq!(s.doc().unwrap().doc.parent_of(w.id), parent);
assert_eq!(weed_box(&w), Some(Rect::new(110.0, 90.0, 160.0, 150.0)));
}
/// Adds one path of `count` open vertical subpaths 2 pt apart, from (100, 100) down to y = 200.
fn bars(s: &mut Session, count: u32) -> NodeId {
let mut p = BezPath::new();
for i in 0..count {
let x = 100.0 + f64::from(i) * 2.0;
p.move_to((x, 100.0));
p.line_to((x, 200.0));
}
insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()))
}
#[test]
fn more_than_the_most_pieces_of_line_is_refused() {
// 1,000 lines each cut into 100 pieces by 101 bars: as many as one run adds.
let mut s = session();
bars(&mut s, 101);
let r = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap();
assert_eq!(r["lines"], json!(super::MAX_PIECES));
// One bar more makes 1,000 pieces more.
let mut s = session();
bars(&mut s, 102);
let n = s.doc().unwrap().doc.node_count();
let e = s.execute("addon.cutting.weed", &json!({"margin": 0, "count": 1000, "direction": "horizontal"})).unwrap_err();
assert!(e.to_string().contains("more than 100000 pieces"), "{e}");
assert_eq!(s.doc().unwrap().doc.node_count(), n);
}
#[test]
fn art_with_more_than_the_most_outline_points_is_refused() {
// An open zigzag of `points` points: one subpath, measured by its points.
let zigzag = |s: &mut Session, points: u32| {
let mut p = BezPath::new();
p.move_to((100.0, 100.0));
for i in 1..points {
p.line_to((100.0 + f64::from(i) * 0.001, if i % 2 == 0 { 100.0 } else { 101.0 }));
}
insert(s, |id| Node::path(id, PathData::from_bezpath(&p), Appearance::default()));
};
let mut s = session();
zigzag(&mut s, super::geometry::MAX_POINTS as u32);
s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap();
let mut s = session();
zigzag(&mut s, super::geometry::MAX_POINTS as u32 + 1);
let e = s.execute("addon.cutting.weed", &json!({"count": 0})).unwrap_err();
assert!(e.to_string().contains("too many outline points"), "{e}");
}
#[test]
fn bad_params_and_an_empty_selection_are_refused() {
let mut s = session();
rect(&mut s, 100.0, 100.0, 50.0, 40.0);
for p in [
json!({"margin": -1}),
json!({"gap": "x"}),
json!({"count": 1.5}),
json!({"count": 1001}),
json!({"count": 2, "spacing": 10}),
json!({"spacing": 0}),
json!({"direction": "diagonal"}),
json!({"box": "yes"}),
json!({"weight": 0}),
json!({"swatch": "no such swatch"}),
json!({"swatch": 3}),
json!({"box": false, "count": 0}),
] {
let n = s.doc().unwrap().doc.node_count();
assert!(s.execute("addon.cutting.weed", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().doc.node_count(), n, "nothing added for {p}");
}
// The same art with good params is weeded; with nothing selected it is refused.
s.execute("addon.cutting.weed", &json!({"count": 2, "gap": "1 mm"})).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
assert!(s.execute("addon.cutting.weed", &json!({})).is_err());
}
+9 -2
View File
@@ -20,6 +20,7 @@ use vectorcraft_geom::Affine;
use super::super::fileio::{MAX_RASTER_ALLOC, ppi};
use super::super::menucmds::has_image;
use super::super::paint::{PROCESS_ON_TRANSPARENCY, gray_colorized_with_process};
use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param};
/// Remove Background's command.
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Background…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, and a result with no pixel left are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
has_image,
remove_background
)]
@@ -182,8 +183,14 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
// Every image is checked before any is decoded.
let mut images = vec![];
for id in ids {
let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let Some(n) = st.doc.node(id) else { continue };
let NodeKind::Image(im) = &n.kind else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take.
if gray_colorized_with_process(&st.doc, n).is_some() {
return Err(bad(C, PROCESS_ON_TRANSPARENCY));
}
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(C, "the linked image shows its preview: embed or relink it first"));
+50 -1
View File
@@ -1,8 +1,9 @@
use std::io::Cursor;
use std::sync::Arc;
use image::{DynamicImage, ImageBuffer, Luma, Rgb};
use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb};
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
@@ -333,6 +334,54 @@ fn sixteen_bit_and_gray_images_keep_their_depth_and_channels() {
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
}
/// A process color can't colorize a grayscale image with transparency, so a gray image colorized
/// with one keeps its pixels. Black, white and spot colors can, so those images are cleared.
#[test]
fn a_gray_image_colorized_with_a_process_color_is_refused() {
let gray = || {
png(DynamicImage::ImageLuma8(ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }]))))
};
let (mut s, id) = open(&gray());
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image");
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}");
assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "the document and its undo steps are unchanged");
// Another image that already has an alpha channel and a process colorize color, as an opened
// file can hold, neither lets this one through nor stops a run on an image that can be cleared.
let held = ImageBlob::png(png(DynamicImage::ImageLumaA8(ImageBuffer::from_pixel(2, 2, LumaA([128u8, 100])))));
let other = place_linked(&mut s, "held", held, (2, 2));
s.edit("Embed and colorize", |d, _| {
let n = d.node_mut(other).unwrap();
n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
if let NodeKind::Image(im) = &mut n.kind {
im.link = None;
}
Ok(())
})
.unwrap();
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute(C, &json!({"ids": [id.0]})).unwrap_err();
assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}");
assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "with another image refused already, nothing changes");
s.execute("paint.setFill", &json!({"color": "#000000", "ids": [id.0]})).unwrap();
assert_eq!(s.execute(C, &json!({"ids": [id.0]})).unwrap()["changed"], 1, "an image colorized with black is cleared beside the other");
let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") };
assert_eq!(out.get_pixel(0, 0).0[1], 0, "the background is cleared");
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the image stays colorized");
for fill in [json!({"color": "#000000"}), json!({"color": "#ffffff"}), json!({"swatch": "Ink"})] {
let (mut s, id) = open(&gray());
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 100, "k": 0}, "spot": true})).unwrap();
s.execute("paint.setFill", &fill).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} colorizes the image");
s.execute(C, &json!({})).unwrap();
let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") };
assert_eq!(out.get_pixel(0, 0).0[1], 0, "{fill}: the background is cleared");
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} still colorizes the image");
}
}
/// The ICC profile the colors are in stays with them.
#[test]
fn the_color_profile_is_kept() {
+2 -1
View File
@@ -139,7 +139,8 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
let mut run = 0;
for (i, at) in chars.into_iter().enumerate() {
let random = if shape == "random" { unit(&mut rng) } else { 0.0 };
let value = from + (to - from) * amount(shape, i, n, random);
// Rounding can carry a value a hair past the range's ends.
let value = (from + (to - from) * amount(shape, i, n, random)).clamp(lo, hi);
let mut change = CharChange::parse(&json!({ key: value }), C, &setup)?;
change.localize(&t, C)?;
while ends.get(run).is_some_and(|&e| e <= at) {
+453
View File
@@ -0,0 +1,453 @@
//! Custom arrowheads (Stroke panel menu › Edit Arrowheads…). The arrowheads file is a native
//! document kept next to the preferences ([`Session::attach_arrowheads_file`]). Each of its symbols
//! is one arrowhead, listed by the symbol's name after the built-in heads in the Stroke panel's
//! arrowhead menus. A head points right (+x): the symbol's registration point is its tip, and the
//! art's height (its extent across the line) is drawn as wide as the built-in heads, four times
//! the head's weight. A head covers what its art paints: the visible fills, and the visible
//! strokes outlined, of the paths, compound paths and groups in it, and its gradient meshes, with
//! their geometry effects applied and clip groups clipped. A head is one solid shape in the stroke's paint: art at 0 %
//! opacity is left out, and other opacities, blend modes and opacity masks do not change the
//! shape. Saving the file reloads the heads. A stroke that uses a custom head carries a copy of its art
//! ([`vectorcraft_doc::CustomArrowhead`]), so its document draws it anywhere.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Node, NodeId, NodeKind, Symbol, SymbolRegistration};
use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath};
use vectorcraft_pathops::BoolOp;
use super::{CommandSpec, Result, Session, always, bad, cmd};
/// The arrowheads file's name, in the folder of the preferences.
pub const FILE_NAME: &str = "Arrowheads.vectorcraft";
/// The largest arrowheads file read, and the most its document or its images may unpack to when
/// compressed.
pub const MAX_FILE_BYTES: u64 = 64 << 20;
/// The most heads read from the file; symbols past it are skipped.
pub const MAX_HEADS: usize = 256;
/// The most anchors a symbol's art, and the shapes it paints, may have; a symbol past it is skipped.
pub const MAX_ART_ANCHORS: usize = 16 * CustomArrowhead::MAX_ANCHORS;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "stroke.arrowheads.list",
"Arrowheads",
[],
None,
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
always,
list
),
cmd!(
"stroke.arrowheads.edit",
"Edit Arrowheads",
[],
None,
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}",
has_file,
edit
),
cmd!(
"stroke.arrowheads.reload",
"Reload Arrowheads",
[],
None,
"{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
has_file,
reload
),
]
}
/// The custom arrowheads read from the arrowheads file.
#[derive(Default)]
pub struct Arrowheads {
path: Option<String>,
heads: Vec<Arc<CustomArrowhead>>,
skipped: Vec<(String, String)>,
error: Option<String>,
}
impl Arrowheads {
/// The arrowheads file's path; `None` without one (the web, runs without preferences).
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// The heads, in the order of the file's symbols.
pub fn heads(&self) -> &[Arc<CustomArrowhead>] {
&self.heads
}
/// Head `name`.
pub fn get(&self, name: &str) -> Option<Arc<CustomArrowhead>> {
self.heads.iter().find(|h| h.name == name).cloned()
}
fn set(&mut self, read: Read) {
(self.heads, self.skipped) = (read.heads.into_iter().map(Arc::new).collect(), read.skipped);
self.error = None;
}
}
/// The heads a document holds, and the symbols that are not heads with the reason.
#[derive(Debug, Default)]
pub struct Read {
pub heads: Vec<CustomArrowhead>,
pub skipped: Vec<(String, String)>,
}
/// The heads of document `doc`: one per symbol, up to [`MAX_HEADS`] (see the module docs).
pub fn heads_of(doc: &Document) -> Read {
let mut d = doc.clone();
let brushes = vectorcraft_brush::library(&d);
let mut out = Read::default();
for (i, sym) in doc.symbols.iter().enumerate() {
if i >= MAX_HEADS {
out.skipped.push((sym.name.clone(), format!("only the first {MAX_HEADS} symbols are read")));
continue;
}
if out.heads.iter().any(|h| h.name == sym.name) {
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
continue;
}
match head(&mut d, &brushes, sym) {
Ok(h) => out.heads.push(h),
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
}
}
out
}
/// Symbol `sym` of `d` as a head.
fn head(d: &mut Document, brushes: &[vectorcraft_brush::Brush], sym: &Symbol) -> std::result::Result<CustomArrowhead, &'static str> {
const TOO_DETAILED: &str = "its art is too long or too detailed for a head";
const UNITED: &str = "its shapes could not be combined into one";
if art_anchors(&sym.art) > MAX_ART_ANCHORS {
return Err(TOO_DETAILED);
}
let art = baked_art(d, sym);
let mut shapes = Shapes::default();
painted(d, brushes, &art, &mut shapes);
if shapes.too_detailed {
return Err(TOO_DETAILED);
}
if shapes.failed {
return Err(UNITED);
}
let area = shapes.united().ok_or(UNITED)?;
let b = area.bounds().filter(|b| b.height() > 1e-9 && b.is_finite()).ok_or("its art paints nothing")?;
let tip = b.center() + d.symbol_registration(&sym.name).offset_from_center(b.width(), b.height());
// Head units: x back from the tip, y across to the right of +x, 4 units to the art's height.
let k = 4.0 / b.height();
let local = Affine::new([-k, 0.0, 0.0, k, k * tip.x, -k * tip.y]);
let h = CustomArrowhead::new(sym.name.clone(), area.transformed(local));
if h.path.subpaths.is_empty() {
return Err(TOO_DETAILED);
}
Ok(h)
}
/// The anchors of the paths in `n` and of the pieces of its gradient meshes ([`mesh_anchors`]), its
/// members' included.
fn art_anchors(n: &Node) -> usize {
let own = match &n.kind {
NodeKind::Mesh(m) => mesh_anchors(m),
_ => n.path_data().map_or(0, PathData::anchor_count),
};
n.children().map_or(own, |c| c.iter().fold(own, |sum, c| sum.saturating_add(art_anchors(c))))
}
/// The art of symbol `sym` of `d` with every geometry effect in it applied (its objects', fills',
/// strokes' and groups'), as the canvas draws it: the art baked as for export, on a copy of `d`.
fn baked_art(d: &Document, sym: &Symbol) -> Node {
// A plain new layer, so the file's own layers' effects stay out of the art.
let mut tmp = d.clone();
tmp.layers = Document::new(1.0, 1.0).layers;
let Some(children) = tmp.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) else { return (*sym.art).clone() };
*children = vec![sym.art.clone()];
let baked = vectorcraft_render::effects::bake_document(&tmp);
baked.as_ref().and_then(|b| b.layers.first()?.children()?.first().map(|c| (**c).clone())).unwrap_or_else(|| (*sym.art).clone())
}
/// The shapes a symbol's art paints, up to [`MAX_ART_ANCHORS`] anchors in all.
#[derive(Default)]
struct Shapes {
list: Vec<(PathData, FillRule)>,
anchors: usize,
/// More anchors were asked for than fit; the shapes past the limit were not made.
too_detailed: bool,
/// A clip group's art could not be combined or clipped, so a shape it paints is missing.
failed: bool,
}
impl Shapes {
/// Whether `anchors` more fit; when they do not, the shapes are too detailed.
fn room(&mut self, anchors: usize) -> bool {
self.too_detailed |= self.anchors.saturating_add(anchors) > MAX_ART_ANCHORS;
!self.too_detailed
}
fn push(&mut self, shape: (PathData, FillRule)) {
if self.room(shape.0.anchor_count()) {
self.anchors += shape.0.anchor_count();
self.list.push(shape);
}
}
/// The shapes united, or `None` when one of them could not be (the union would miss it).
fn united(&self) -> Option<PathData> {
let refs: Vec<(&PathData, FillRule)> = self.list.iter().map(|(p, r)| (p, *r)).collect();
vectorcraft_pathops::try_unite_all(&refs).ok()
}
/// The shapes of `inside` clipped to `outline` (filled under `rule`), added as one.
fn push_clipped(&mut self, inside: Shapes, outline: &PathData, rule: FillRule) {
if inside.too_detailed || !self.room(inside.anchors) {
self.too_detailed = true;
return;
}
self.failed |= inside.failed;
let clip = |art: PathData| {
vectorcraft_pathops::try_boolean(&art, FillRule::NonZero, outline, rule, BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION).ok()
};
let Some(clipped) = inside.united().and_then(clip) else {
self.failed = true;
return;
};
if !clipped.subpaths.is_empty() {
self.push((clipped, FillRule::NonZero));
}
}
}
/// The shapes the shown paths and compound paths in `n` (baked art) paint: their filled areas and
/// their strokes' outlines, its groups' members included (baking has already made a group's own
/// fills and strokes art among its members), and the areas its gradient meshes cover. A clip
/// group's clipped art is clipped to
/// its clipping path, whose own fill and stroke paint unclipped, as on the canvas; a group used as
/// the clipping path paints nothing ([`clip_paint`]). Hidden or fully
/// transparent art is left out.
fn painted(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Path { guide: true, .. } => {}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
fills(n, out);
// The outline holds a copy of the path for each fill too, which adds nothing new.
if let Some(o) = super::pathops::outline_strokes(d, brushes, n) {
fills_in(&o, out);
}
}
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| painted(d, brushes, part, out));
// Nothing to clip by hides the clipped art, as on the canvas.
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| painted(d, brushes, c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| painted(d, brushes, c, out)),
NodeKind::Mesh(_) => mesh_area(n, out),
_ => {}
}
}
/// What clipping path `clip` paints ([`Node::clip_paint`]): its fills and its strokes, each as a
/// copy of it keeping only those. A group or another object that does not paint as a clipping
/// path gives neither.
fn clip_paint(clip: &Node) -> Vec<Node> {
let paint = clip.clip_paint();
[paint.fill, paint.stroke].into_iter().flatten().collect()
}
/// The areas the shown paths and gradient meshes in `n` (an outlined stroke) fill, clipped by its
/// clip groups, whose clipping paths' own fills paint unclipped. A stroke with a gradient along or
/// across it is outlined as gradient meshes clipped to the stroke's outline.
fn fills_in(n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Mesh(_) => mesh_area(n, out),
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| fills_in(part, out));
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| fills_in(c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
_ => match n.children() {
Some(children) => children.iter().for_each(|c| fills_in(c, out)),
None => fills(n, out),
},
}
}
/// The anchors [`mesh_area`] makes at most of mesh `m`: its outline's, one a patch along each side,
/// when no point of it is fully transparent, else four by four quads of four anchors a patch.
fn mesh_anchors(m: &vectorcraft_doc::GradientMesh) -> usize {
let (rows, cols) = (m.rows as usize, m.cols as usize);
if opaque(m) { rows.saturating_add(cols).saturating_mul(2) } else { rows.saturating_mul(cols).saturating_mul(64) }
}
fn opaque(m: &vectorcraft_doc::GradientMesh) -> bool {
m.points.iter().all(|p| p.opacity > 0.0)
}
/// The area gradient mesh `n` paints: its outline when no point of it is fully transparent, else
/// the pieces of it that are not fully transparent (four by four quads a patch). A mesh whose
/// pieces do not fit in `out` makes the shapes too detailed.
fn mesh_area(n: &Node, out: &mut Shapes) {
let NodeKind::Mesh(m) = &n.kind else { return };
if !out.room(mesh_anchors(m)) {
return;
}
if opaque(m) {
let outline = m.outline();
if !outline.subpaths.is_empty() {
out.push((outline, FillRule::NonZero));
}
return;
}
for q in m.quads(4) {
if q.opacity > 0.0 || q.corners.iter().any(|(_, o)| *o > 0.0) {
out.push((PathData::single(SubPath::polyline(&q.pts, true)), FillRule::NonZero));
}
}
}
/// The area path `n` fills, when a shown fill paints it.
fn fills(n: &Node, out: &mut Shapes) {
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none());
if n.appearance.items.iter().any(paints)
&& let Some(shape) = super::pathops::node_path(n)
{
out.push(shape);
}
}
/// The document a missing arrowheads file starts as: one example head, a solid triangle.
pub fn starter() -> Document {
let mut doc = Document::new(612.0, 792.0);
doc.title = "Arrowheads".into();
let name = "Example Arrowhead";
let tri = SubPath::polyline(&[Point::new(-10.0, -8.0), Point::new(10.0, 0.0), Point::new(-10.0, 8.0)], true);
let art = Node::path(NodeId(0), PathData::single(tri), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0));
let art = doc.reid(&art);
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
// The tip is the right edge's middle.
doc.set_symbol_registration(name, SymbolRegistration(5));
let id = doc.alloc_id();
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((306.0, 396.0)) });
let layer = doc.layers.first().map(|l| l.id);
let _ = doc.insert(layer, 0, instance);
doc
}
impl Session {
/// Keep the custom arrowheads in the file at `path` and read the heads it holds (none while it
/// is missing; an unreadable file is reported by `stroke.arrowheads.list`).
pub fn attach_arrowheads_file(&mut self, path: String) {
self.arrowheads.path = Some(path);
self.reload_arrowheads();
}
/// Read the arrowheads file again.
fn reload_arrowheads(&mut self) {
let Some(path) = self.arrowheads.path.clone() else { return };
match read(&path) {
Ok(Some(doc)) => self.arrowheads.set(heads_of(&doc)),
Ok(None) => self.arrowheads.set(Read::default()),
Err(e) => {
self.arrowheads.set(Read::default());
self.arrowheads.error = Some(e);
}
}
}
/// A document was saved to `path`: when that is the arrowheads file, its heads are read back
/// from what was written.
pub(crate) fn arrowheads_saved(&mut self, path: &str) {
if self.arrowheads.path.as_deref().is_some_and(|a| same_file(a, path)) {
self.reload_arrowheads();
}
}
}
fn same_file(a: &str, b: &str) -> bool {
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
}
/// The document in the arrowheads file at `path`; `None` when there is no file.
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
let size = match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("{path}: {e}")),
Ok(m) if !m.is_file() => return Err(format!("{path}: not a file")),
Ok(m) => m.len(),
};
if size > MAX_FILE_BYTES {
return Err(format!("{path}: larger than {} MB", MAX_FILE_BYTES >> 20));
}
let bytes = crate::file_access::unconfined(|| super::fileio::read_file(path)).map_err(|e| e.to_string())?;
// A compressed file's document, and its images, may unpack to no more than an uncompressed
// file may hold.
let parse = || vectorcraft_format::load_file_capped(&bytes, MAX_FILE_BYTES).map(|f| f.doc).map_err(|e| format!("{path}: {e}"));
crate::guard::catch_panic(parse).map_err(|_| format!("{path}: could not be read"))?.map(Some)
}
fn has_file(s: &Session) -> std::result::Result<(), String> {
if s.arrowheads.path.is_some() { Ok(()) } else { Err("no arrowheads file here".into()) }
}
fn skipped(s: &Session) -> Vec<Value> {
s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect();
Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error}))
}
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.reload";
s.reload_arrowheads();
if let Some(e) = &s.arrowheads.error {
return Err(bad(C, e.clone()));
}
Ok(json!({"count": s.arrowheads.heads.len(), "skipped": skipped(s)}))
}
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.edit";
let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?;
if let Some(dir) = std::path::Path::new(&path).parent() {
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
}
// Made only when no file is there, also when another run makes one at the same moment.
let bytes = vectorcraft_format::save_file(&starter());
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
Ok(()) => true,
Err(_) if std::path::Path::new(&path).exists() => false,
Err(e) => return Err(bad(C, e.to_string())),
};
if created {
s.reload_arrowheads();
}
// Already open: that document comes to the front.
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
match open {
Some(i) => {
s.set_active(i);
}
None => {
crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?;
}
}
Ok(json!({"path": path, "created": created}))
}
+73
View File
@@ -170,6 +170,7 @@ pub struct BuiltinBrushLibrary {
/// The built-in brush libraries, in menu order: original brushes generated in code.
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
@@ -268,6 +269,78 @@ fn art_ribbons() -> BrushLibrary {
built("Art Ribbons", doc, brushes)
}
/// A band between the edges y = `top(x)` and y = `bottom(x)` for x in `from`..`to`, in `n` steps.
fn between(from: f64, to: f64, n: usize, top: impl Fn(f64) -> f64, bottom: impl Fn(f64) -> f64) -> PathData {
let xs: Vec<f64> = (0..=n).map(|i| from + (to - from) * i as f64 / n as f64).collect();
let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, top(x))).collect();
pts.extend(xs.iter().rev().map(|&x| Point::new(x, bottom(x))));
PathData::single(SubPath::polyline(&pts, true))
}
/// Path `p` filled with gray `hex` at `opacity`: one layer of a wash.
fn wash(p: PathData, hex: &str, opacity: f32) -> Node {
let mut n = filled(p, Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK)));
n.opacity = opacity;
n
}
/// How much of a wash's width is left at x: rounded ends, full width from 8 pt in.
fn wash_ends(x: f64) -> f64 {
let ends = ((x / 8.0).min(1.0) * ((100.0 - x) / 8.0).min(1.0)).max(0.0);
0.4 + 0.6 * ends.sqrt()
}
/// Ink and Wash: Tapered Ink, broad near its start and thinning to a fine tip; Brush Pen, a
/// rounded nib whose size follows the pen pressure; and two washes of translucent grays, Soft Wash
/// with faint edges and Pooling Wash with a darker rim and two light breaks. Black and grays take
/// the stroke color as tints of it.
fn ink_and_wash() -> BrushLibrary {
let tapered = {
let half = |x: f64| 3.0 * (x / 22.0).min(1.0).powf(0.6) * ((100.0 - x) / 78.0).min(1.0).powf(1.4);
black(between(0.0, 100.0, 48, |x| -0.85 * half(x), |x| 1.15 * half(x)))
};
let pen = Brush {
name: "Brush Pen".into(),
kind: BrushKind::Calligraphic(Calligraphic {
angle: 40.0,
roundness: 75.0,
size: 5.0,
variation: [0.0, 0.0, 2.5],
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
}),
};
let soft = {
let top = |x: f64| -(4.5 + 0.5 * (x * 0.21).sin() + 0.3 * (x * 0.57 + 1.3).sin()) * wash_ends(x);
let bottom = |x: f64| (4.5 + 0.45 * (x * 0.26 + 2.1).sin() + 0.3 * (x * 0.69 + 0.4).sin()) * wash_ends(x);
group(vec![
wash(between(0.0, 100.0, 40, top, bottom), "#404040", 0.4),
wash(between(2.0, 98.0, 32, |x| top(x) - 0.7 - 0.3 * (x * 0.43).sin().abs(), |x| top(x) + 0.5), "#404040", 0.2),
wash(between(3.0, 97.0, 32, |x| bottom(x) - 0.5, |x| bottom(x) + 0.6 + 0.35 * (x * 0.37 + 1.0).sin().abs()), "#404040", 0.18),
wash(shapes::ellipse(Rect::new(21.0, -2.4, 39.0, 0.8)), "#e6e6e6", 0.22),
wash(shapes::ellipse(Rect::new(61.0, -0.3, 75.0, 2.3)), "#e6e6e6", 0.18),
])
};
let pooling = {
let top = |x: f64| -(4.0 + 0.4 * (x * 0.18 + 0.7).sin() + 0.2 * (x * 0.53).sin()) * wash_ends(x);
let bottom = |x: f64| (4.0 + 0.35 * (x * 0.23 + 1.9).sin() + 0.25 * (x * 0.61 + 0.2).sin()) * wash_ends(x);
let rim = |x: f64, k: f64, phase: f64| 0.35 + k * (0.5 + 0.5 * (x * 0.29 + phase).sin());
group(vec![
wash(between(0.0, 100.0, 40, top, bottom), "#4d4d4d", 0.35),
wash(between(1.0, 99.0, 40, top, |x| top(x) + rim(x, 0.45, 0.0)), "#262626", 0.55),
wash(between(1.0, 99.0, 40, |x| bottom(x) - rim(x, 0.5, 1.1), bottom), "#262626", 0.55),
wash(polygon(&[(34.0, -2.6), (39.0, -2.8), (36.0, 2.7), (31.0, 2.5)]), "#e6e6e6", 0.2),
wash(polygon(&[(70.0, -2.4), (74.0, -2.5), (72.0, 2.6), (68.0, 2.4)]), "#e6e6e6", 0.18),
])
};
let brushes = vec![
art("Tapered Ink", tapered, Colorization::Tints),
pen,
art("Soft Wash", soft, Colorization::Tints),
art("Pooling Wash", pooling, Colorization::Tints),
];
built("Ink and Wash", Document::new(100.0, 100.0), brushes)
}
fn nib(name: &str, angle: f64, roundness: f64, size: f64) -> Brush {
Brush { name: name.into(), kind: BrushKind::Calligraphic(Calligraphic { angle, roundness, size, ..Default::default() }) }
}
+1 -1
View File
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
has_doc,
brush_options
),
+1 -1
View File
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), 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)}",
"{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, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
+1 -1
View File
@@ -491,7 +491,7 @@ fn import_text(s: &mut Session, p: &Value) -> Result<Value> {
if text.trim().is_empty() {
return Err(bad(C, "the text is empty"));
}
let style = super::super::create::new_type_style(s, &Value::Null);
let style = super::super::create::new_type_style(s, &Value::Null, C)?;
let system_layout = s.doc()?.doc.setup.system_layout;
let layout = |t: &mut TextObject| {
t.system_layout = system_layout;
+48 -11
View File
@@ -210,8 +210,12 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
let remembered = s.store_profile(&info.name, &bytes);
// A new file of a working space: the active settings still hold the old one.
let working = cms::active_settings();
if working.rgb == info.name || working.cmyk == info.name {
let is_working = working.rgb == info.name || working.cmyk == info.name;
if is_working {
cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?;
}
// A new file of a working space, or of the CMYK profile View → Proof Setup targets: redraw.
if is_working || proof_targets(&info.name) {
touch_all(s);
}
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
@@ -233,10 +237,17 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("no profile named `{name}`")));
}
s.unstore_profile(&info.name);
touch_all(s);
if proof_targets(&info.name) {
touch_all(s);
}
Ok(json!({"removed": info.name}))
}
/// Whether View → Proof Setup targets the CMYK profile `name`.
fn proof_targets(name: &str) -> bool {
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name)
}
#[cfg(target_arch = "wasm32")]
fn load_profile(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("color.loadProfile", "loading profiles from disk isn't available in the browser"))
@@ -274,14 +285,17 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
Ok(())
})?;
let mut st = cms::active_settings();
let before = st.clone();
if let Some(r) = &rgb {
st.rgb = r.clone();
}
if let Some(c) = &cmyk {
st.cmyk = c.clone();
}
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
touch_all(s);
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
touch_all(s);
}
}
Ok(json!({"rgb": rgb, "cmyk": cmyk}))
}
@@ -760,17 +774,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = on_param(p, "proof", C)? {
v.proof_colors = on;
}
proof::set_view(v.clone());
touch_all(s);
store_view(s, v.clone());
Ok(view_json(&v))
}
/// Make `v` the proof view and redraw every document. When `v` equals the current view, the view
/// and the revisions stay as they are; Separations Preview's visible plates are compared as a set.
fn store_view(s: &mut Session, v: proof::ProofView) {
let shown = |v: &proof::ProofView| proof::ProofView {
separations: v.separations.as_ref().map(|vis| {
let mut vis = vis.clone();
vis.sort();
vis.dedup();
vis
}),
..v.clone()
};
if shown(&v) != shown(&proof::view()) {
proof::set_view(v);
touch_all(s);
}
}
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
let on = on_param(p, "on", cmd)?;
let mut v = proof::view();
f(&mut v, on);
proof::set_view(v.clone());
touch_all(s);
store_view(s, v.clone());
Ok(view_json(&v))
}
@@ -802,7 +832,15 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
match p.get("plates") {
None | Some(Value::Null) => {}
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
let mut vis: Vec<String> = Vec::new();
for n in a.iter().filter_map(Value::as_str) {
let n = check(n)?;
// A plate named twice is shown once.
if !vis.contains(&n) {
vis.push(n);
}
}
v.separations = Some(vis);
}
Some(_) => {
let key = "plates";
@@ -821,8 +859,7 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
vis.push(n);
}
}
proof::set_view(v);
touch_all(s);
store_view(s, v);
Ok(plates_json(s))
}
+6 -6
View File
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -739,7 +739,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(a, &["width", "height"], "text.create")?;
}
let text = str_param(p, "text").unwrap_or("");
let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p));
let mut t = TextObject::point(Point::new(x, y), text, new_type_style(s, p, "text.create")?);
// Turned about the point (the first baseline's start, an area's top-left corner): type set
// along a Constrain Angle.
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "text.create")? } else { 0.0 };
@@ -848,11 +848,11 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject)
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults,
/// filled with the current fill unless that is None or white (black then), in the document's
/// language.
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error.
pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result<CharStyle> {
let mut style = CharStyle::default();
if let Some(sz) = p.get("size").and_then(Value::as_f64) {
style.size = sz.clamp(0.1, 1296.0);
style.size = super::typecmd::given_type_size(sz, cmd)?;
}
if let Some(f) = str_param(p, "font") {
style.font_family = f.to_string();
@@ -873,5 +873,5 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten();
let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language));
style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string);
style
Ok(style)
}
+33 -13
View File
@@ -7,8 +7,8 @@ use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_svg::{CssOptions, CssSheet, css_rules};
use super::fileio::{default_name, encode_with_warnings, isolated, write_file};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets};
use super::fileio::{Note, default_name, encode_with_notes, isolated, note_texts, write_file};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, named_ids, targets};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -21,13 +21,13 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
selection
),
cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document", has_doc, generate),
cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document; ids and id are not used, and a malformed one is an error", has_doc, generate),
cmd!(
"css.export",
"Export CSS",
[],
None,
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
"{path?: string, scope?: selection|all (default selection when left out; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} a path or scope given as anything but a string, null included, is an error, and so is a malformed ids or id with scope all, which does not use them; write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
has_doc,
export
),
@@ -77,16 +77,34 @@ fn selection(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result(&sheet(s, p, ids, "css.selection")?))
}
/// Checks the form of the `ids` or `id` that `p` gives a command that exports every object and does
/// not use them: a malformed one is an error, as it is for the selection.
fn unused_ids(p: &Value) -> Result<()> {
named_ids(p).map(|_| ())
}
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
unused_ids(p)?;
let ids = everything(s)?;
Ok(result(&sheet(s, p, ids, "css.generate")?))
}
/// The string `p` gives for `key`, or `None` when `p` leaves it out. Any value given that is not a
/// string, null included, is an error: "`{key}` must be a string".
fn given_text<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str>> {
p.get(key).map(|v| v.as_str().ok_or_else(|| bad(cmd, format!("`{key}` must be a string")))).transpose()
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "css.export";
let ids = match str_param(p, "scope").unwrap_or("selection") {
let scope = given_text(p, "scope", C)?;
let path = given_text(p, "path", C)?;
let ids = match scope.unwrap_or("selection") {
"selection" => targets(s, p)?,
"all" => everything(s)?,
"all" => {
unused_ids(p)?;
everything(s)?
}
other => return Err(bad(C, format!("scope must be selection or all (got {other})"))),
};
let sheet = sheet(s, p, ids, C)?;
@@ -100,22 +118,24 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
}
let css = format!("{}\n", sheet.text());
let doc = &s.doc()?.doc;
// Encode the pictures of rasterized art, and add each of their warnings once.
// Encode the pictures of rasterized art, and add each of their warnings once. What CSS can't
// describe is a loss.
let mut images = Vec::new();
let mut warnings = sheet.warnings.clone();
let mut notes: Vec<Note> = sheet.warnings.iter().cloned().map(Note::loss).collect();
for r in &sheet.rules {
let Some(name) = &r.image else { continue };
let (d, _) = isolated(doc, &[r.id], name).ok_or_else(|| bad(C, format!("{} paints nothing to rasterize", r.selector)))?;
let (png, notes) = encode_with_warnings(&d, "png", &json!({}))?;
let (png, given) = encode_with_notes(&d, "png", &json!({}))?;
images.push((name, png));
for w in notes {
if !warnings.contains(&w) {
warnings.push(w);
for n in given {
if !notes.iter().any(|x| x.text == n.text) {
notes.push(n);
}
}
}
let warnings = note_texts(&notes);
let n = sheet.rules.len();
match str_param(p, "path") {
match path {
Some(path) => {
write_file(path, css.as_bytes())?;
let folder = std::path::Path::new(path).parent();
+1 -1
View File
@@ -568,7 +568,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
st.start_arrow = head;
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
st.arrow_align = vectorcraft_doc::appearance::ArrowAlign::Tip;
+460 -79
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
has_doc,
info
),
@@ -40,7 +40,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
("objects", "Objects"),
("graphicStyles", "Graphic Styles"),
("brushes", "Brushes"),
("spotColors", "Spot Colors"),
("spotColors", "Spot Color Objects"),
("patterns", "Pattern Objects"),
("gradients", "Gradient Objects"),
("symbols", "Symbols"),
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
];
/// The object counts of `document.info` and their labels.
const OBJECT_LABELS: [(&str, &str); 18] = [
const OBJECT_LABELS: [(&str, &str); 19] = [
("paths", "Paths"),
("compoundPaths", "Compound Paths"),
("groups", "Groups"),
@@ -63,6 +63,7 @@ const OBJECT_LABELS: [(&str, &str); 18] = [
("symbolInstances", "Symbol Instances"),
("gradients", "Gradient Objects"),
("patterns", "Pattern Objects"),
("spots", "Spot Color Objects"),
("meshes", "Gradient Meshes"),
("blends", "Blends"),
("envelopes", "Envelopes"),
@@ -130,15 +131,18 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
/// rows of its objects filled or stroked with a pattern and with a gradient.
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
fonts: &BTreeSet<super::fonts::UsedFont>,
images: &[ImageRow],
brushes: &[(String, String)],
repeats: &[(String, String)],
spot_objects: &[(String, String)],
pattern_objects: &[(String, String)],
gradient_objects: &[(String, String)],
category: Option<&str>,
@@ -182,8 +186,8 @@ fn sections(
rows
}
"graphicStyles" => names("graphicStyleNames"),
"brushes" => names("brushNames"),
"spotColors" => names("spotColors"),
"brushes" => brushes.to_vec(),
"spotColors" => spot_objects.to_vec(),
"patterns" => pattern_objects.to_vec(),
"gradients" => gradient_objects.to_vec(),
"symbols" => names("symbols"),
@@ -273,15 +277,50 @@ fn gradient_label(p: &Paint) -> Option<String> {
}
}
/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
/// renderer lays it out.
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
/// The names of `d`'s spot color swatches: the swatches whose prints go to a plate of their own
/// ([`vectorcraft_doc::inks::inks`]). A name held by several swatches is the first one's, as
/// [`Document::swatch`] finds it, and the Registration swatch prints on every plate, so it is not
/// one.
fn spot_swatches(d: &Document) -> HashSet<&str> {
let mut first: BTreeMap<&str, bool> = BTreeMap::new();
for s in d.swatches_iter() {
first.entry(s.name.as_str()).or_insert(s.spot && s.paint.color().is_some());
}
first.into_iter().filter(|&(name, spot)| spot && name != vectorcraft_color::swatch::REGISTRATION).map(|(name, _)| name).collect()
}
/// The spot colors paint `p` prints (`spots`: [`spot_swatches`]): the spot swatch a solid color is
/// linked to, or those a gradient's stops are linked to, each once, in the order of the stops. A
/// link at a tint of 0 prints no ink, a gradient whose stops are all at an opacity of 0 draws
/// nothing, and a color that only looks like a spot color is not linked to one.
fn spot_labels(spots: &HashSet<&str>, p: &Paint) -> Vec<String> {
let mut out: Vec<String> = vec![];
let mut add = |swatch: &Option<String>, tint: f32| {
if let Some(name) = swatch
&& tint > 0.0
&& spots.contains(name.as_str())
&& !out.contains(name)
{
out.push(name.clone());
}
};
match p {
Paint::Solid { swatch, tint, .. } => add(swatch, *tint),
Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity > 0.0) => g.gradient.stops.iter().for_each(|s| add(&s.swatch, s.tint)),
_ => {}
}
out
}
/// The type object `n` holds and the runs its layout draws, when it uses a spot color, a pattern or
/// a gradient (`spots`: [`spot_swatches`]): the runs with a glyph outline (list markers and ruby
/// included) or an underline or strikethrough bar. Spaces and line breaks draw no outline. A type
/// object's characters carry their own fill and stroke, and the type object's own fills and strokes
/// paint on its characters, so only those runs paint. The type is laid out with its inline
/// graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
let NodeKind::Text(t) = &n.kind else { return None };
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)) || !spot_labels(spots, p).is_empty();
let own = n.appearance.items.iter().any(|i| match i {
vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
@@ -289,51 +328,103 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
return None;
}
Some((t, drawn_runs(d, t)))
}
/// The runs of type `t` that its layout draws: those with a glyph outline (list markers and ruby
/// included) or an underline or strikethrough bar, laid out as the renderer lays it out.
fn drawn_runs(d: &Document, t: &vectorcraft_doc::TextObject) -> BTreeSet<usize> {
let db = vectorcraft_text::FontDb::global();
let resolved = d.inline_resolved(t);
let lay = vectorcraft_text::layout(db, &resolved);
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
Some((t, painted))
painted
}
/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
/// path's member (`members`: the compound path's own fills and strokes paint 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.
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
/// gradient.
type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
/// hidden fill or stroke, a fill or stroke at an opacity of 0 and a stroke with no width paint
/// nothing, and neither does any fill or
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
/// compound path's own fills and strokes paint 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_paints(
d: &Document,
n: &Node,
members: &HashSet<*const Node>,
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
label: fn(&Paint) -> Option<String>,
label: &PaintNames<'_>,
) -> Vec<String> {
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|| members.contains(&std::ptr::from_ref(n))
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|| !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
|| n.appearance.items.iter().all(|i| label(i.paint()).is_empty())
{
return vec![];
}
// The patterns or gradients an image's shaped fills and strokes paint (their effects can
// transform the paint, so they are matched by label).
// The names an image's shaped fills and strokes paint (their effects can transform the paint,
// so they are matched by name).
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_))
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
let mut out: Vec<String> = vec![];
for item in &n.appearance.items {
let Some(name) = label(item.paint()) else { continue };
let paints = item.visible()
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
&& shaped.as_ref().is_none_or(|s| s.contains(&name));
if paints && !out.contains(&name) {
out.push(name);
if !item.visible() || item.opacity() <= 0.0 || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
continue;
}
for name in label(item.paint()) {
if shaped.as_ref().is_none_or(|s| s.contains(&name)) && !out.contains(&name) {
out.push(name);
}
}
}
out
}
/// [`pattern_label`] or [`gradient_label`] as the names [`own_paints`] takes.
fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<String> {
move |p| label(p).into_iter().collect()
}
/// The brushes `n`'s own strokes draw with, in the order of its appearance. A hidden stroke, a
/// stroke at an opacity of 0, a stroke with no paint and a stroke with no width draw nothing, and neither does any stroke of a
/// guide (drawn in the guide color) or of a compound path's member (`members`: the compound path's
/// own strokes draw it). An image's strokes draw only where an effect gives them a shape, and only
/// paths, compound paths, type and images draw strokes of their own.
fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Vec<String> {
if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) {
return vec![];
}
let brush = |item: &vectorcraft_doc::AppearanceItem| match item {
vectorcraft_doc::AppearanceItem::Stroke(st) if item.visible() && st.opacity > 0.0 && !st.paint.is_none() && st.width > 0.0 => {
st.brush.clone().filter(|b| !b.is_empty())
}
_ => None,
};
if matches!(n.kind, NodeKind::Image(_)) {
return vectorcraft_render::effects::image_paint(Some(d), n).iter().filter_map(|(_, _, item)| brush(item)).collect();
}
let used: Vec<String> = n.appearance.items.iter().filter_map(brush).collect();
if used.is_empty() {
return used;
}
// A path or compound path with no segment gives its strokes nothing to follow, and neither does
// type whose layout draws nothing (spaces and line breaks without an underline or strikethrough).
let segments = |pd: &vectorcraft_geom::PathData| pd.subpaths.iter().any(|sp| sp.segment_count() > 0);
let follows = match &n.kind {
NodeKind::Path { .. } => n.path_data().is_some_and(segments),
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).any(segments),
NodeKind::Text(t) => !drawn_runs(d, t).is_empty(),
// A brush on any other kind of object (a layer, a group, a ruler guide) is not listed.
_ => false,
};
if follows { used } else { vec![] }
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.info";
let category = str_param(p, "category");
@@ -370,10 +461,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
};
let mut patterns = BTreeSet::new();
let mut symbols = BTreeSet::new();
// `spot_objects`, `spot_rows` and `spot` hold the `spotObjects` entries, the rows of the objects filled or stroked with a spot
// color, in walk order, and the spot colors they use. `spot_swatches` names the document's spot colors once, for every paint.
let spot_swatches = spot_swatches(d);
let mut spot_objects: Vec<Value> = vec![];
let mut spot_rows: Vec<(String, String)> = vec![];
let mut spot = BTreeSet::new();
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
// in walk order.
let library = vectorcraft_brush::library(d);
let mut brushes: Vec<String> = vec![];
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
let mut repeats: Vec<Value> = vec![];
let mut repeat_rows: Vec<(String, String)> = vec![];
@@ -446,17 +545,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
}
for item in &n.appearance.items {
if let Paint::Solid { swatch: Some(name), .. } = item.paint()
&& d.swatch(name).is_some_and(|s| s.spot)
{
spot.insert(name.clone());
}
}
// The patterns and the gradients this object's fills and strokes paint, each once.
let painted_runs = painted_runs(d, n);
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
// The spot colors, the patterns and the gradients this object's fills and strokes paint, each once.
let painted_runs = painted_runs(d, &spot_swatches, n);
let mut used_spots = own_paints(d, n, &members, painted_runs.as_ref(), &spot_label);
let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), &pattern);
let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), &gradient);
// The characters' own paints: an inline graphic draws no outline and does not take its
// run's paint (a list marker set in its run does), and a stroke with no width paints
// nothing.
@@ -464,19 +557,38 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
for paint in std::iter::once(&run.style.fill).chain(stroke) {
for (used, label) in
[(&mut used_patterns, pattern_label as fn(&Paint) -> Option<String>), (&mut used_gradients, gradient_label)]
{
if let Some(name) = label(paint)
&& !used.contains(&name)
{
used.push(name);
let labels: [(&mut Vec<String>, &PaintNames<'_>); 3] =
[(&mut used_spots, &spot_label), (&mut used_patterns, &pattern), (&mut used_gradients, &gradient)];
for (used, label) in labels {
for name in label(paint) {
if !used.contains(&name) {
used.push(name);
}
}
}
}
}
}
// Objects counts the objects that Pattern Objects and Gradient Objects list.
// A grayscale or 1-bit image colorized with a spot color prints it, while its pixels take
// the color, as the renderer draws it.
if let NodeKind::Image(im) = &n.kind
&& let Some(colorize) = n.extras().colorize.as_deref()
&& d.image_blob(im).is_some_and(|b| b.takes_colorize())
{
for name in spot_label(colorize) {
if !used_spots.contains(&name) {
used_spots.insert(0, name);
}
}
}
// Objects counts the objects that Spot Color Objects, Pattern Objects and Gradient Objects list.
if !used_spots.is_empty() {
let name = n.display_name();
spot.extend(used_spots.iter().cloned());
spot_rows.push((name.clone(), used_spots.join(", ")));
spot_objects.push(json!({ "id": n.id.0, "name": name, "spotColors": used_spots }));
*counts.entry("spots").or_default() += 1;
}
if !used_patterns.is_empty() {
let name = n.display_name();
patterns.extend(used_patterns.iter().cloned());
@@ -503,14 +615,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
{
styles.push(&g.name);
}
if selection_only {
for item in &n.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(st) = item
&& let Some(b) = &st.brush
&& !brushes.contains(b)
{
brushes.push(b.clone());
}
for b in applied_brushes(d, n, &members) {
if !brushes.contains(&b) {
brushes.push(b);
}
}
if let NodeKind::Repeat(spec) = &n.kind {
@@ -521,6 +628,17 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
.iter()
.map(|name| {
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} brush", k.label())))
})
.collect();
let mut out = json!({
"document": document_summary(d),
"objects": counts,
@@ -529,10 +647,14 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"images": images,
"symbols": symbols,
"spotColors": spot,
"spotColorNames": spot,
"spotObjects": spot_objects,
"swatches": d.swatches_iter().count(),
"graphicStyles": d.graphic_styles.len(),
"graphicStyleNames": styles,
"brushNames": brushes,
"brushes": brush_entries,
"panelBrushNames": library.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
"repeatObjects": repeats,
"characterStyles": d.char_styles.len(),
"paragraphStyles": d.para_styles.len(),
@@ -544,7 +666,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -657,38 +779,129 @@ mod tests {
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
}
/// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists
/// the brushes the selected objects' strokes use, each once.
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
/// Selection Only it lists the brushes the selected objects' strokes use.
#[test]
fn info_lists_the_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let panel: Vec<Value> =
s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect();
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushNames"], json!(panel));
let brushes = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap();
// No art uses a brush: the category is empty.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!((i["brushNames"].clone(), i["brushes"].clone(), i["panelBrushNames"].clone()), (json!([]), json!([]), json!(panel)));
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes")));
let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect();
assert_eq!(i["sections"][0]["rows"], json!(rows));
assert_eq!(i["sections"][0]["rows"], json!([]));
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Dots"})).unwrap();
s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap();
let names =
|s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone();
// The whole document: the two brushes the art uses, each once, with their types; "3 pt. Round" (a Calligraphic
// brush in the panel) is left out.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"]));
assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}]));
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art brush"], ["Dots", "Scatter brush"]]));
assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel));
let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nCharcoal: Art brush\nDots: Scatter brush\n") && !text.contains("3 pt. Round"), "{text}");
assert!(!text.contains("OBJECTS"), "{text}");
// Selection Only: the brushes the selected objects' strokes use.
let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"}));
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"]));
assert_eq!(selected(&mut s)["brushNames"], json!(["Charcoal", "Dots"]));
s.execute("select.set", &json!({"ids": [b]})).unwrap();
assert_eq!(names(&mut s), json!(["Arrow"]));
let i = selected(&mut s);
assert_eq!(
(i["brushes"].clone(), i["sections"][0]["rows"].clone()),
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter brush"]]))
);
let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nDots: Scatter brush\n") && !text.contains("Charcoal"), "{text}");
// A stroke without a brush lists none.
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
assert_eq!(names(&mut s), json!([]));
let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}");
assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}");
assert_eq!(selected(&mut s)["brushNames"], json!([]));
}
/// Document Info › Brushes leaves out brushes on strokes that draw nothing (hidden, at an
/// opacity of 0, with no width or paint, a guide's, a compound path member's, a path's with no segment, type's that
/// draws no characters, a group's own), lists a brush the Brushes panel does
/// not hold with no type, and gives a name two panel brushes share the type the renderer uses.
#[test]
fn info_brushes_skip_undrawn_strokes_and_name_missing_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let square = |s: &mut Session, x: f64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
};
let (hidden, thin, guide, missing) = (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
let (empty, faint) = (square(&mut s, 80.0), square(&mut s, 200.0));
s.execute("brush.apply", &json!({"ids": [hidden, thin, guide, missing, empty, faint], "name": "Charcoal"})).unwrap();
let (p, q) = (square(&mut s, 100.0), square(&mut s, 120.0));
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
// A compound path's member: the compound path's own stroke draws it.
let NodeKind::Compound { children, .. } = &mut d.node_mut(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
let member = &mut std::sync::Arc::make_mut(&mut children[0]).appearance;
member.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
member.stroke_mut().unwrap().brush = Some("Dots".into());
d.node_mut(NodeId(hidden)).unwrap().appearance.stroke_mut().unwrap().visible = false;
d.node_mut(NodeId(thin)).unwrap().appearance.stroke_mut().unwrap().width = 0.0;
// A stroke at an opacity of 0 draws nothing.
d.node_mut(NodeId(faint)).unwrap().appearance.stroke_mut().unwrap().opacity = 0.0;
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
*g = true;
}
// A path with no segment: its stroke follows nothing.
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(empty)).unwrap().kind {
*path = vectorcraft_geom::PathData::default();
}
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Gone".into());
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushes"], json!([{"name": "Gone", "type": null}]));
assert_eq!(i["sections"][0]["rows"], json!([["Gone", "missing from the Brushes panel"]]));
// A stroke with no paint draws nothing.
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None;
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([]));
// Two panel brushes with one name: the type is the one the renderer draws with, the last one's.
let twin = square(&mut s, 140.0);
s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut lib = vectorcraft_brush::library(d);
let kinds: Vec<vectorcraft_brush::BrushKind> =
["Charcoal", "Dots"].iter().map(|n| lib.iter().find(|b| b.name == *n).unwrap().kind.clone()).collect();
lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind }));
vectorcraft_brush::store(d, &lib);
d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into());
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}]));
// Type: a brushed stroke on drawn characters is listed, one on spaces alone is not.
let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap();
let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
for (id, name) in [(blank, "Dots"), (word, "Arrow")] {
let ap = &mut d.node_mut(NodeId(id)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some(name.into());
}
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
// A group's own stroke: the group draws its members.
let (m1, m2) = (square(&mut s, 160.0), square(&mut s, 180.0));
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let ap = &mut d.node_mut(NodeId(group)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some("Leaves".into());
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
}
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
@@ -799,6 +1012,11 @@ mod tests {
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
// Nor does a pattern fill at an opacity of 0.
let clear = square(&mut s, 220.0);
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [clear], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [clear], "index": 0, "opacity": 0})).unwrap();
// A type object with no characters paints nothing either.
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
@@ -859,7 +1077,7 @@ mod tests {
assert_eq!(i["patternNames"], json!(["Dots"]));
// Objects counts the objects that Pattern Objects lists.
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
s.execute("select.set", &json!({"ids": [d, e, clear, empty, blank, guide, compound, image.0]})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
@@ -997,6 +1215,169 @@ mod tests {
assert!(!text.contains("Spare"), "{text}");
}
/// Document Info › Spot Color Objects lists each object filled or stroked with a spot color once,
/// with the spot colors it uses, as a solid color or in a gradient's stops, one in a group and a
/// type object whose characters use one included. A spot swatch no art uses adds no row; a
/// process color that looks the same, Registration and a tint of 0 are not spot colors; paint
/// that draws nothing is left out by the rules Pattern Objects follows; and Objects counts the
/// listed objects. With Selection Only it lists the objects in the selection, each once, and the
/// report writes the same rows.
#[test]
fn info_lists_the_spot_color_objects() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
// An empty document lists none.
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
assert_eq!((i["spotObjects"].clone(), i["spotColorNames"].clone(), i["spotColors"].clone()), (json!([]), json!([]), json!([])));
assert!(i["objects"]["spots"].is_null() && i["sections"][0]["rows"] == json!([]), "{i}");
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("\nSPOT COLOR OBJECTS\nNone\n"), "{text}");
let ink = |c: f64| json!({"model": "cmyk", "c": c, "m": 0.5, "y": 0.0, "k": 0.0});
s.execute("swatch.new", &json!({"name": "Ink", "color": ink(1.0), "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Gold", "color": ink(0.2), "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Spare", "color": ink(0.4), "spot": true})).unwrap();
// A global process color of the same color as Ink.
s.execute("swatch.new", &json!({"name": "Look", "color": ink(1.0), "global": true})).unwrap();
let square =
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let ramp = |a: &str, b: &str| json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000", "swatch": a}, {"offset": 1, "color": "#fff", "swatch": b}]});
let (a, b, c, f, g, h) =
(square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0), square(&mut s, 80.0), square(&mut s, 100.0));
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Gold", "tint": 40})).unwrap();
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
s.execute("paint.setFill", &json!({"ids": [b], "swatch": "Look"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Ink", "tint": 50})).unwrap();
s.execute("paint.setFill", &json!({"ids": [c], "swatch": "Ink", "tint": 0})).unwrap();
s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("Gold", "Look")})).unwrap();
s.execute("paint.setFill", &json!({"ids": [g], "gradient": ramp("Look", "Look")})).unwrap();
s.execute("paint.setFill", &json!({"ids": [h], "swatch": "[Registration]"})).unwrap();
for id in [&c, &g, &h] {
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
}
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
// A type object whose characters are filled with a spot color.
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [t], "none": true})).unwrap();
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
// A hidden spot fill and a spot stroke with no width paint nothing, so neither object is listed.
let (d, e) = (square(&mut s, 120.0), square(&mut s, 140.0));
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ink"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Ink"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
// Type with no characters, or of only spaces and a line break, paints nothing, and neither
// does a guide made from a path with a spot color.
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ink"})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ink"})).unwrap();
let guide = square(&mut s, 300.0);
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ink"})).unwrap();
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
// Nor does a compound path's member's own spot fill, or an image's spot fill without an
// effect that gives it a shape.
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
let pic = square(&mut s, 360.0);
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
let image = s.doc().unwrap().selection.objects[0];
s.edit("own paint", |d, _| {
d.node_mut(member).unwrap().appearance = paint.clone();
d.node_mut(image).unwrap().appearance = paint;
Ok(())
})
.unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
assert_eq!(
i["spotObjects"],
json!([
{"id": a, "name": "Both", "spotColors": ["Ink", "Gold"]},
{"id": b, "name": "<Rectangle>", "spotColors": ["Ink"]},
{"id": f, "name": "<Rectangle>", "spotColors": ["Gold"]},
{"id": t, "name": "Type", "spotColors": ["Ink"]},
])
);
assert_eq!((i["spotColorNames"].clone(), i["spotColors"].clone()), (json!(["Gold", "Ink"]), json!(["Gold", "Ink"])));
// Objects counts the objects that Spot Color Objects lists.
assert_eq!(i["objects"]["spots"].as_u64(), Some(4), "{}", i["objects"]);
let objects = s.execute("document.info", &json!({"category": "objects"})).unwrap()["sections"][0]["rows"].clone();
assert!(objects.as_array().unwrap().contains(&json!(["Spot Color Objects", "4"])), "{objects}");
s.execute("select.set", &json!({"ids": [c, g, h, d, e, empty, blank, guide, compound, image.0]})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert!(i["objects"]["spots"].is_null() && i["spotObjects"] == json!([]) && i["spotColors"] == json!([]), "{i}");
let i = s.execute("document.info", &json!({"category": "spotColors"})).unwrap();
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("spotColors"), Some("Spot Color Objects")));
assert_eq!(i["sections"][0]["rows"], json!([["Both", "Ink, Gold"], ["<Rectangle>", "Ink"], ["<Rectangle>", "Gold"], ["Type", "Ink"]]));
// A selection that holds the group and the object inside it lists that object once.
for ids in [json!([group, b]), json!([b, group])] {
s.execute("select.set", &json!({"ids": ids})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Ink"]]), "{ids}");
assert_eq!((i["objects"]["spots"].as_u64(), i["spotColorNames"].clone()), (Some(1), json!(["Ink"])), "{ids}");
}
s.execute("select.set", &json!({"ids": [t]})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "spotColors"})).unwrap();
assert_eq!((i["sections"][0]["rows"].clone(), i["spotColors"].clone()), (json!([["Type", "Ink"]]), json!(["Ink"])));
let text = s.execute("document.info", &json!({"category": "spotColors", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("\nSPOT COLOR OBJECTS\nBoth: Ink, Gold\n<Rectangle>: Ink\n<Rectangle>: Gold\nType: Ink\n"), "{text}");
assert!(!text.contains("Spare") && !text.contains("Look"), "{text}");
}
/// Spot Color Objects lists a grayscale image colorized with a spot color, and leaves out a
/// gradient whose stops are all at an opacity of 0, which draws nothing.
#[test]
fn spot_color_objects_take_colorized_images_and_skip_clear_gradients() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let mut bytes = Vec::new();
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(2, 1, vec![0, 255]).unwrap())
.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png)
.unwrap();
let image = s
.edit("Place", |d, sel| {
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(bytes));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "gray".into(),
width: 2,
height: 1,
xf: Default::default(),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().extras().colorize.is_some());
let clear = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 10, "height": 10})).unwrap()["id"].clone();
let stops =
json!([{"offset": 0, "color": "#000", "swatch": "Ink", "opacity": 0}, {"offset": 1, "color": "#fff", "swatch": "Ink", "opacity": 0}]);
s.execute("paint.setFill", &json!({"ids": [clear], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
let i = s.execute("document.info", &json!({})).unwrap();
let name = s.doc().unwrap().doc.node(image).unwrap().display_name();
assert_eq!(i["spotObjects"], json!([{"id": image.0, "name": name, "spotColors": ["Ink"]}]), "{i}");
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
+7 -3
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_move
),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
cmd!(
@@ -50,7 +50,11 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_compare
),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so are a data set's image value and a linked JavaScript file in svg_scripts outside them (a URL is kept); a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
let st = s.doc()?;
let d = super::links::with_hidden_paths_named(&st.doc, super::links::LinkBase::of(st));
Ok(serde_json::to_value(&*d).unwrap_or(Value::Null))
}),
cmd!(
"document.setUnits",
"Units",
+145 -29
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand…",
["Object"],
None,
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
has_selection,
expand
),
@@ -194,10 +194,12 @@ impl Expandable {
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
_ => shape && !c.appearance.stroke_paint().is_none(),
};
e.gradient |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
};
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
e.fill |= match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
@@ -222,6 +224,43 @@ fn gradient_fill(i: &AppearanceItem) -> Option<(&FillLayer, &GradientPaint)> {
}
}
/// Whether path `l` has a gradient fill that Fill expands ([`expand_fills`]): one that repeats or
/// reflects stays a gradient when its box needs more runs than are written ([`padded_on`]). For a
/// path that live-effect plug-ins paint, whether a piece of the art they paint has one
/// ([`expand_pieces`]).
fn gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().any(|i| gradient_fill(i).is_some()) {
return false;
}
if !vectorcraft_render::effects::has_painted_effects(l) {
return piece_gradient_expands(d, l);
}
let Some(art) = vectorcraft_render::effects::reshape(Some(d), l, None) else { return false };
let mut any = false;
art.walk(&mut |c| {
any = any
|| (matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
&& !c.is_ruler_guide()
&& c.appearance.items.iter().any(|i| gradient_fill(i).is_some())
&& piece_gradient_expands(d, c));
});
any
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
return l.appearance.items.iter().any(|i| gradient_fill(i).is_some());
}
let reshaped = reshaped(d, l);
let l = reshaped.as_ref().unwrap_or(l);
let Some((path, _)) = node_path(l) else { return false };
let Some(bounds) = path.bounds() else { return false };
l.appearance.items.iter().filter(|i| gradient_fill(i).is_some()).any(|item| {
fill_shape(d, l, item, &path, bounds).is_some_and(|(_, _, b, moved)| gradient_fill(&moved).is_some_and(|(_, g)| padded_on(g, b).is_some()))
})
}
/// The definition and placement of a visible pattern fill whose pattern `d` defines.
fn pattern_fill<'a, 'd>(d: &'d Document, i: &'a AppearanceItem) -> Option<(&'a FillLayer, &'d PatternDef, Affine)> {
match i {
@@ -476,11 +515,15 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
} else {
// A gradient that repeats or reflects expands as its stops repeated over the box (and
// stays a gradient when the box needs more runs than are written).
let (g, runs) = padded_on(g, bounds)?;
let g = &*g;
let frame = Frame::new(g, bounds);
match to {
GradientTo::Mesh => vec![Node::new(d.alloc_id(), NodeKind::Mesh(frame.mesh(&g.gradient)))],
GradientTo::Objects(n) => frame
.pieces(&g.gradient, n as usize)
.pieces(&g.gradient, n as usize, runs)
.into_iter()
.map(|(shape, (color, opacity))| {
let fill = FillLayer { opacity, overprint: f.overprint, ..FillLayer::new(Paint::solid(color)) };
@@ -543,12 +586,14 @@ fn expand_piece_leaves(
}
/// 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
/// path (a plain path then), and every geometry effect of its own removed, with each raster effect
/// following the Transform effects after it
/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)). `None` when it has no
/// 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};
use vectorcraft_render::effects::{GeomContext, apply_geometry_carrying, has_geometry, without_geometry};
if !has_geometry(&l.appearance.effects) {
return None;
}
@@ -559,7 +604,7 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option<Node> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
m.appearance.effects.retain(|e| !is_geometry(&e.id));
m.appearance.effects = without_geometry(&m.appearance.effects);
Some(m)
}
@@ -601,9 +646,10 @@ fn with_path(l: &Node, path: PathData) -> Node {
}
/// The effects of fill `f` that stay on its expanded art: all but its geometry effects, which
/// shape the outline it paints ([`fill_shape`]).
/// shape the outline it paints ([`fill_shape`]), with each raster effect following the Transform
/// effects after it ([`without_geometry`](vectorcraft_render::effects::without_geometry)).
fn fill_effects(f: &FillLayer) -> Vec<vectorcraft_doc::Effect> {
f.effects.iter().filter(|e| !vectorcraft_render::effects::is_geometry(&e.id)).cloned().collect()
vectorcraft_render::effects::without_geometry(&f.effects)
}
/// Replace every pattern fill of the selected paths by the tiles it paints (see [`expand_patterns`]).
@@ -1234,8 +1280,70 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
(super::paint::stored_color(store_in, c), a)
});
}
let (geom, spread) = (g.resolve(bounds), g.gradient.spreader());
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
}
/// For stops repeated by [`padded_on`]: where along the vector (0 to 1) their first run starts and
/// how many runs lie evenly from there to 1.
type Runs = Option<(f64, usize)>;
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
/// there to 1. `None` when the box needs more runs than are written
/// ([`vectorcraft_color::Padded::capped`]): the gradient stays.
fn padded_on(g: &GradientPaint, bounds: Rect) -> Option<(std::borrow::Cow<'_, GradientPaint>, Runs)> {
use std::borrow::Cow;
if !g.gradient.is_spread() {
return Some((Cow::Borrowed(g), None));
}
let geom = g.resolve(bounds);
Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32))
match g.gradient.padded_over(&geom, bounds) {
Some(p) if p.capped => None,
Some(p) => {
let runs = Some((p.first, p.runs));
Some((Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs))
}
None => {
let runs = Some((0.0, g.gradient.repeat_count() as usize));
Some((Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs))
}
}
}
/// The edges (gradient parameters, from `lo` to `hi`) of about `n` bands [`Frame::pieces`] cuts:
/// evenly spaced, or for stops repeated in `runs` ([`padded_on`]: where the first run starts and
/// how many runs lie evenly from there to 1) the same whole number of bands in each run between
/// `lo` and `hi` (at least one, about `n` in all), so every run starts on an edge and no band
/// holds two runs' colors.
fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64> {
let n = n.max(1);
let even = || {
let step = (hi - lo) / n as f64;
(0..=n).map(|k| lo + k as f64 * step).collect()
};
let Some((first, count)) = runs.filter(|&(first, count)| count > 0 && (0.0..1.0).contains(&first)) else { return even() };
let run = (1.0 - first) / count as f64;
let (from, to) = (lo.max(first), hi.min(1.0));
let shown = (to - from) / run;
if !(shown > 0.0 && shown.is_finite()) {
return even();
}
let step = run / (n as f64 / shown).round().max(1.0);
// Both whole numbers of steps from `first`, at most `n` plus the runs shown, plus one.
let (k0, k1) = (((from - first) / step).ceil(), ((to - first) / step).floor());
let mut edges = vec![lo];
for k in (k0 as usize)..(k1 as usize).saturating_add(1) {
let t = first + k as f64 * step;
if t > edges.last().copied().unwrap_or(lo) + 1e-12 && t < hi - 1e-12 {
edges.push(t);
}
}
edges.push(hi);
edges
}
/// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every
@@ -1404,10 +1512,17 @@ impl Frame {
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
/// center from each band's start to the seam, for a diamond one, nested squares (largest
/// first). Each paints over the ones below except its band, so no seam shows between bands.
/// With translucent stops each shape is just its band, so nothing doubles up.
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
/// With translucent stops each shape is just its band, so nothing doubles up. Stops repeated
/// in `runs` ([`padded_on`]) get the same whole number of bands in each run ([`band_edges`]).
fn pieces(&self, g: &Gradient, n: usize, runs: Option<(f64, usize)>) -> Vec<(PathData, (Color, f32))> {
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
let color = |e: &[f64], k: usize| {
let (a, b) = (e.get(k).copied().unwrap_or(0.0), e.get(k + 1).copied().unwrap_or(1.0));
g.sample_keep_model(((a + b) / 2.0) as f32)
};
if let Some((geom, b, _)) = &self.conic {
// Evenly spaced around the turn, as the wedges are.
let n = band_edges(0.0, 1.0, n, runs).len().saturating_sub(1);
return geom
.conic_wedges(*b, n, opaque)
.into_iter()
@@ -1419,51 +1534,52 @@ impl Frame {
return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))];
};
// Nested squares about the center, largest first, as a radial gradient's ellipses.
let step = reach / n as f64;
let edges = band_edges(0.0, *reach, n, runs);
let square = |t: f64| -> SubPath {
let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect();
SubPath::polyline(&pts, true)
};
return (0..n)
return (0..edges.len().saturating_sub(1))
.rev()
.map(|k| {
let mut shape = PathData::single(square((k + 1) as f64 * step));
let mut shape = PathData::single(square(edges.get(k + 1).copied().unwrap_or(*reach)));
if !opaque && k > 0 {
let mut hole = square(k as f64 * step);
let mut hole = square(edges.get(k).copied().unwrap_or(0.0));
hole.reverse();
shape.subpaths.push(hole);
}
(shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32))
(shape, color(&edges, k))
})
.collect();
}
let step = (self.t1 - self.t0) / n as f64;
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
let edges = band_edges(self.t0, self.t1, n, runs);
let bands = edges.len().saturating_sub(1);
let edge = |k: usize| edges.get(k).copied().unwrap_or(self.t1);
if self.radial {
let ellipse = |t: f64| {
let c = self.focal + (self.start - self.focal) * t;
let m = Affine::new([self.along.x * t, self.along.y * t, self.across.x * t, self.across.y * t, c.x, c.y]);
shapes::ellipse(Rect::new(-1.0, -1.0, 1.0, 1.0)).transformed(m)
};
return (0..n)
return (0..bands)
.rev()
.map(|k| {
let mut shape = ellipse((k + 1) as f64 * step);
let mut shape = ellipse(edge(k + 1));
if !opaque && k > 0 {
let mut hole = ellipse(k as f64 * step).subpaths.remove(0);
let mut hole = ellipse(edge(k)).subpaths.remove(0);
hole.reverse();
shape.subpaths.push(hole);
}
(shape, color(k))
(shape, color(&edges, k))
})
.collect();
}
(0..n)
(0..bands)
.map(|k| {
let a = self.t0 + k as f64 * step;
let b = if opaque { self.t1 } else { a + step };
let a = edge(k);
let b = if opaque { self.t1 } else { edge(k + 1) };
let pts = [self.at(a, self.s0), self.at(b, self.s0), self.at(b, self.s1), self.at(a, self.s1)];
(PathData::single(SubPath::polyline(&pts, true)), color(k))
(PathData::single(SubPath::polyline(&pts, true)), color(&edges, k))
})
.collect()
}
+4 -3
View File
@@ -66,12 +66,11 @@ use serde_json::{Value, json};
pub use action_batch::batch_overwrites_one_file;
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{export_crop, isolated};
pub use export::{export_doc, export_source};
pub(crate) use load::check_not_lossy_overwrite;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
@@ -82,6 +81,7 @@ pub use load::{
Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image,
read_for_open, texture_image,
};
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
pub use load::{losses_summary, overwrite_losses};
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
@@ -130,7 +130,8 @@ mod tests_readonly;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::{Placed, copy_new, file_metadata};
pub(crate) use access::{
absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file,
absolute_path, create_dir, document_path, file_created, file_stamp, naming_in_error, read_file, read_file_head, shown_link, shown_path,
write_file, write_new_file,
};
#[cfg(all(test, windows))]
pub(crate) use access::{document_path_on, document_path_with};
+105
View File
@@ -65,6 +65,62 @@ pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::bo
std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name })
}
/// What an error names a file or folder outside the read roots by when [`shown_path`] gives no
/// name for it, or gives one that is not valid text.
pub(crate) const UNNAMED: &str = "a file or folder outside the read roots";
/// An error about `path`, a file or folder the client did not give, as the request being served
/// may see it: where the message names `path` ([`naming_in_message`]), it names it as
/// [`shown_path`] does, or as [`UNNAMED`] when that is empty or holds a replacement character. The
/// roots the message names and the reason stay whole. Unchanged when `path` is [`shown`].
pub(crate) fn naming_in_error(e: EngineError, path: &str) -> EngineError {
if path.is_empty() || shown(path) {
return e;
}
naming_as(e, path, &error_name(path))
}
/// What an error names `path` by when it is outside the read roots: [`shown_path`], or
/// [`UNNAMED`] when that is empty or holds a replacement character.
pub(crate) fn error_name(path: &str) -> String {
let name = shown_path(path);
if name.is_empty() || name.contains('\u{FFFD}') { UNNAMED.to_string() } else { name.into_owned() }
}
/// [`naming_in_error`] with `path` named `name`, whether or not it is [`shown`] (a name worked out
/// earlier, for the request that prepared the work).
pub(crate) fn naming_as(e: EngineError, path: &str, name: &str) -> EngineError {
match e {
EngineError::Other(msg) => EngineError::Other(naming_in_message(&msg, path, name)),
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: naming_in_message(&msg, path, name) },
EngineError::ReadOnlyLocation(msg) => EngineError::ReadOnlyLocation(naming_in_message(&msg, path, name)),
e => e,
}
}
/// `msg` with `path` given as `name` where it begins a path the message is about: at the start of
/// `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or after
/// `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message names
/// stays whole, even one inside `path`.
pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
const BEFORE: [&str; 2] = [": ", "cannot resolve "];
let mut out = String::with_capacity(msg.len());
let mut rest = msg;
loop {
if let Some(after) = rest.strip_prefix(path)
&& after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' '))
{
out.push_str(name);
rest = after;
}
let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break };
out.push_str(&rest[..i + len]);
rest = &rest[i + len..];
}
out.push_str(rest);
out
}
/// `path` checked for writing against the automation roots in force.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn may_write(path: &str) -> Result<()> {
@@ -466,3 +522,52 @@ pub(crate) fn create_dir(path: &str) -> Result<()> {
pub(crate) fn write_new_file(path: &str, _: &[u8]) -> Result<()> {
Err(no_fs(path))
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crate::file_access::{AutomationRoots, confine};
/// An error about a path the client did not give, under roots that don't let it be read: the
/// path is named by its file name (after a `/` or a `\`), or as [`UNNAMED`] when it ends in no
/// name or its name is not valid text, and every root and the reason stay whole. A path inside the
/// read roots, and any path without roots in force, stay whole.
#[test]
fn an_error_names_a_path_outside_the_read_roots_by_its_name() {
let base = std::env::temp_dir().join(format!("vc-access-naming-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (a, b, out) = (base.join("a"), base.join("b"), base.join("kept-out"));
for f in [&a, &b, &out] {
std::fs::create_dir_all(f).unwrap();
}
let text = |p: &std::path::Path| p.to_string_lossy().into_owned();
let roots = AutomationRoots::new(&[a.as_path(), b.as_path()], &[a.as_path(), b.as_path()]).unwrap();
let file = text(&out.join("doc.svg"));
let raw = confine(roots.as_ref(), || crate::file_access::check_write(&file)).unwrap_err();
let shown_root = |p: &std::path::Path| crate::cmd::findfiles::plain(std::fs::canonicalize(p).unwrap()).display().to_string();
let (ra, rb) = (shown_root(&a), shown_root(&b));
let named = |e: EngineError, path: &str| confine(roots.as_ref(), || naming_in_error(e, path)).to_string();
assert_eq!(named(EngineError::Other(raw.clone()), &file), format!("automation path rejected: outside the write roots {ra}, {rb}: doc.svg"));
let io = named(EngineError::Other(format!("{file}: disk full")), &file);
assert_eq!(io, "doc.svg: disk full");
let bad = named(EngineError::BadParams { cmd: "x".into(), msg: format!("{file}: not a file") }, &file);
assert_eq!(bad, "invalid parameters for `x`: doc.svg: not a file");
// A save refused by the file system keeps its type and its code.
let read_only = confine(roots.as_ref(), || naming_in_error(EngineError::ReadOnlyLocation(format!("{file}: Permission denied")), &file));
assert!(matches!(&read_only, EngineError::ReadOnlyLocation(_)));
assert_eq!(read_only.to_string(), format!("{}: doc.svg: Permission denied", crate::READ_ONLY_LOCATION));
// A Windows path written with `\`, a path that ends in no name and a name that isn't text.
let win = r"C:\Users\me\secret\doc.svg";
assert_eq!(named(EngineError::Other(format!("{win}: denied")), win), "doc.svg: denied");
let folder = format!("{}/", text(&out));
assert_eq!(named(EngineError::Other(format!("{folder}: denied")), &folder), format!("{UNNAMED}: denied"));
let lossy = text(&out.join("bad\u{FFFD}.svg"));
assert_eq!(named(EngineError::Other(format!("{lossy}: denied")), &lossy), format!("{UNNAMED}: denied"));
// Readable, or nothing confined: whole.
let inside = text(&a.join("x.svg"));
assert_eq!(named(EngineError::Other(format!("{inside}: denied")), &inside), format!("{inside}: denied"));
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
let _ = std::fs::remove_dir_all(base);
}
}
@@ -1429,6 +1429,42 @@ mod tests {
assert_eq!(written.len(), 2, "{written:?}");
}
/// A Data Sets batch whose Save step has no path saves the document's own file. When that file is
/// outside the client's read and write roots, each row's error keeps the write root and names the
/// file by its file name, with Stop on Error on and off. A source folder the client gives stays
/// whole in the error.
#[test]
fn dataset_batch_step_error_hides_document_path() {
use crate::file_access::{AutomationRoots, confine};
let base = tmp("roots-error");
let (inside, outside) = (base.join("in"), base.join("kept-out"));
for f in [&inside, &outside] {
std::fs::create_dir_all(f).unwrap();
}
let mut s = with_data_sets(&["Alpha", "Beta"]);
let own = outside.join("doc.vectorcraft").to_string_lossy().into_owned();
s.execute("document.save", &json!({"path": own})).unwrap();
let roots = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
let root = crate::cmd::findfiles::plain(std::fs::canonicalize(&inside).unwrap()).display().to_string();
let hidden = outside.to_string_lossy().into_owned();
for (stop, rows) in [(true, 1), (false, 2)] {
let p = json!({"source": "datasets", "stopOnError": stop, "commands": [{"command": "document.save", "params": {}}]});
let r = confine(roots.as_ref(), || s.execute("action.batch", &p)).unwrap();
assert_eq!((r["failed"].as_u64(), r["processed"].as_array().map(Vec::len)), (Some(rows), Some(rows as usize)), "{r}");
for row in r["processed"].as_array().unwrap() {
let e = row["error"].as_str().unwrap_or_default();
let want = format!("batch step 0 (`document.save`) failed: automation path rejected: outside the write root {root}: doc.vectorcraft");
assert_eq!(e, want, "{r}");
}
assert!(!r.to_string().contains(&hidden), "{r}");
}
let p = json!({"source": "folder", "folder": hidden, "commands": [{"command": "object.unlockAll", "params": {}}]});
let e = confine(roots.as_ref(), || s.execute("action.batch", &p)).unwrap_err().to_string();
assert!(e.contains(&hidden), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// The names of the files in `dir`, sorted.
fn file_names(dir: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> =
+2 -2
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .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 o Line truncated
"{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; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .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 o Line truncated
always,
load::open
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export Document",
[],
None,
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; 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), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend 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, Line truncated
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend 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 Line truncated
has_doc,
export::export
),
+1
View File
@@ -241,6 +241,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
for img in out.images {
if !enc.linked.iter().any(|l| l.name == img.name) {
enc.linked.push(vectorcraft_svg::LinkedImage { name: img.name, bytes: Arc::new(img.bytes) });
+102 -9
View File
@@ -74,18 +74,104 @@ pub struct Encoded {
pub linked: Vec<vectorcraft_svg::LinkedImage>,
/// Image maps, each written beside its image under the image's name (raster `imageMap`).
pub maps: Vec<imagemap::Map>,
/// The encoder's warnings (features approximated or left out, options not applied yet).
/// The encoder's warnings: what the file leaves out of the document or writes differently
/// ([`NoteKind::Loss`]).
pub warnings: Vec<String>,
/// The encoder's notes on the options: options not applied yet or applied another way, and
/// what an option turns off ([`NoteKind::Setting`]). A reply gives them after the warnings
/// ([`Self::notes`]).
pub setting_notes: Vec<String>,
/// What joins the file's stem and the artboard name when there is a file per artboard
/// (default `-`; EPS uses `_`, as the reference app names them).
pub joiner: Option<&'static str>,
}
/// What a note an export gives with its file is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NoteKind {
/// Something of the document (its art, type, layers or artboards) that the file leaves out or
/// that reaches it changed: the format, its version or a limit can't hold it, or the export
/// couldn't write it.
Loss,
/// An option the export didn't apply or applied another way while the art reaches the file as
/// it looks, or something left out because an option turns it off.
Setting,
}
/// A note an export gives with its file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Note {
/// What the note is about.
pub kind: NoteKind,
/// The note, in English.
pub text: String,
}
impl Note {
/// A note about what the file loses ([`NoteKind::Loss`]).
pub fn loss(text: impl Into<String>) -> Self {
Self { kind: NoteKind::Loss, text: text.into() }
}
/// A note on the options ([`NoteKind::Setting`]).
pub fn setting(text: impl Into<String>) -> Self {
Self { kind: NoteKind::Setting, text: text.into() }
}
}
/// The texts of `notes` in the order a reply gives them: the losses first, then the notes on the
/// options, each kind in the order given (the status bar names the first).
pub fn note_texts(notes: &[Note]) -> Vec<String> {
let of = |kind| notes.iter().filter(move |n| n.kind == kind).map(|n| n.text.clone());
of(NoteKind::Loss).chain(of(NoteKind::Setting)).collect()
}
/// Add `note` to `notes` unless a note with its text is there already.
pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
if !notes.iter().any(|n| n.text == note.text) {
notes.push(note);
}
}
impl Encoded {
pub(super) fn one(bytes: Vec<u8>) -> Self {
Self { files: vec![(None, bytes)], ..Self::default() }
}
/// The file `bytes` with `notes`, each in the list of its kind, in the order given.
pub(super) fn one_with_notes(bytes: Vec<u8>, notes: Vec<Note>) -> Self {
let mut enc = Self::one(bytes);
for n in notes {
match n.kind {
NoteKind::Loss => enc.warnings.push(n.text),
NoteKind::Setting => enc.setting_notes.push(n.text),
}
}
enc
}
/// Add each of `texts` to [`Self::setting_notes`] unless a note with its text is there already.
pub(super) fn add_setting_notes(&mut self, texts: impl IntoIterator<Item = String>) {
for t in texts {
if !self.warnings.contains(&t) && !self.setting_notes.contains(&t) {
self.setting_notes.push(t);
}
}
}
/// Every note with its kind: the warnings, then the notes on the options that aren't also
/// warnings.
pub fn kinded_notes(&self) -> Vec<Note> {
let settings = self.setting_notes.iter().filter(|t| !self.warnings.contains(t)).map(Note::setting);
self.warnings.iter().map(Note::loss).chain(settings).collect()
}
/// The notes' texts in the order a reply gives them ([`note_texts`]): the warnings, then the
/// notes on the options, each once.
pub fn notes(&self) -> Vec<String> {
note_texts(&self.kinded_notes())
}
/// Every file to write for the destination `path` (a path or a file name): the file itself
/// when there is one, else `{stem}-{artboard name}.{ext}` beside it (see `joiner`; a file of no artboard
/// among several, as Save's master file, is the file itself), then the linked images beside it
@@ -128,13 +214,14 @@ impl Encoded {
out
}
/// The one file and the warnings, when the export wrote nothing else.
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<String>)> {
/// The one file and the notes, when the export wrote nothing else.
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<Note>)> {
if !self.linked.is_empty() || !self.maps.is_empty() {
return Err(bad(C, format!("{} with linked images or an image map writes several files: use document.export", f.label)));
}
let notes = self.kinded_notes();
match <[_; 1]>::try_from(self.files) {
Ok([(_, bytes)]) => Ok((bytes, self.warnings)),
Ok([(_, bytes)]) => Ok((bytes, notes)),
Err(_) => Err(bad(C, format!("{} writes one file per artboard here: use document.export, or name one artboard", f.label))),
}
}
@@ -419,8 +506,14 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
/// Like [`encode`], also returning the encoder's warnings (PDF and SVG: options not applied yet,
/// features approximated or left out; every format that draws type: fonts written in the fallback
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame), what
/// the file loses first ([`note_texts`]).
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
encode_with_notes(doc, format, p).map(|(bytes, notes)| (bytes, note_texts(&notes)))
}
/// Like [`encode_with_warnings`], with each note's kind ([`Encoded::kinded_notes`]).
pub fn encode_with_notes(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
let f = super::writable(C, Some(format), None)?;
let enc = encode_all(doc, f.id, p)?;
// The error for a version 7 .ai of several artboards names the legacy .ai.
@@ -476,7 +569,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
/// one named after the document) with that path's extension when the plug-in lists it, else its
/// first. Its warnings come back with the file.
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
use vectorcraft_plugins::{Error, export};
let doc = &*doc.without_edit_modes();
@@ -539,8 +632,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
"ai" => return super::save::encode_ai(C, f, doc, p),
"pdf" => {
let (bytes, warnings) = super::pdf::encode(C, doc, p)?;
return Ok(Encoded { warnings, ..Encoded::one(bytes) });
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
return Ok(Encoded::one_with_notes(bytes, notes));
}
"png" | "jpg" | "webp" | "gif" | "png8" | "tiff" | "bmp" | "tga" | "psd" => {
let o: RasterOptions = options(f, p)?;
@@ -607,7 +700,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&regions)));
if format == RasterFormat::WebP && o.lossless == Some(false) {
enc.warnings.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
}
return Ok(enc);
}
+1
View File
@@ -382,6 +382,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
}
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&regions)));
Ok(enc)
+2 -2
View File
@@ -42,7 +42,7 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }),
};
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.warnings }));
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.notes() }));
if main.len() > 1 {
out["files"] = main.iter().map(|(name, bytes)| merge(json!({ "name": name }), data(bytes))).collect();
}
@@ -69,7 +69,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
o.insert("_displayDocTitle".into(), json!(display_doc_title));
}
let enc = encode_all(doc, f.id, &q)?;
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings }))
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() }))
}
/// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait`
+1
View File
@@ -116,6 +116,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
}
if enc.files.is_empty() {
return Err(bad(C, "the document has no artboard"));
+4 -1
View File
@@ -136,10 +136,12 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
}
let images = see_through_images(&d, mode);
if !images.is_empty() {
note(&mut enc.warnings, if mode == SeeThrough::Flatten { FLATTENED } else { OMITTED });
if mode == SeeThrough::Flatten {
note(&mut enc.warnings, FLATTENED);
flatten_images(&mut d, &images)?;
} else {
// A note on the options: `transparentImages: omit` leaves them out.
enc.add_setting_notes([OMITTED.to_string()]);
for (_, id) in images {
let _ = d.remove(id); // Inside an image left out before: gone already.
}
@@ -150,6 +152,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
for w in placed.iter().chain(&out.warnings) {
note(&mut enc.warnings, w);
}
enc.add_setting_notes(out.setting_notes);
enc.files.push((Some(b), out.bytes));
}
// Expanding raster effects and flattening images draw the art, and an image the renderer
+56 -4
View File
@@ -398,7 +398,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let editing = vectorcraft_svg::editing(&text).map(|e| (e.intact, move || vectorcraft_format::base64_decode(&e.data)));
// Relative links are found in the SVG's folder (when `name` is a path).
let folder = std::path::Path::new(name).parent().map(|f| f.to_string_lossy()).filter(|f| !f.is_empty()).map(|f| absolute_path(&f));
restore_or_import(editing, || import_svg(&text, folder.as_deref()))?
restore_or_import(editing, || open_svg(&text, folder.as_deref()))?
}
"pdf" | "ai" | "ait" => {
// The file is read and checked once, for the document it carries, its pages, the
@@ -573,6 +573,33 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
/// own): rasters stay linked, SVG files become art, missing ones placeholders (see
/// [`vectorcraft_svg::ImportOptions`]).
pub(crate) fn import_svg(text: &str, folder: Option<&str>) -> Result<(Document, Vec<String>)> {
import_svg_finding(text, folder, &std::collections::HashSet::new()).map(|(doc, warnings, _)| (doc, warnings))
}
/// [`import_svg`] for a document opened from an SVG: with the variable data the file carries (SVG
/// Options › Include Variable Data), read as [`crate::cmd::variablecmds::svg_library`] says. Variable
/// data that can't be read is left out with a warning; the art opens either way.
fn open_svg(text: &str, folder: Option<&str>) -> Result<(Document, Vec<String>)> {
let lib = match crate::cmd::variablecmds::svg_library(text) {
None => return import_svg(text, folder),
Some(Err(e)) => {
let (doc, mut warnings) = import_svg(text, folder)?;
warnings.push(format!("the file's variable data wasn't read: {e}"));
return Ok((doc, warnings));
}
Some(Ok(lib)) => lib,
};
let (mut doc, mut warnings, found) = import_svg_finding(text, folder, &lib.elements())?;
warnings.extend(crate::cmd::variablecmds::give_svg_library(&mut doc, lib, &found));
Ok((doc, warnings))
}
/// [`import_svg`], also returning the object made of each element whose id `ids` lists.
fn import_svg_finding(
text: &str,
folder: Option<&str>,
ids: &std::collections::HashSet<String>,
) -> Result<(Document, Vec<String>, vectorcraft_svg::Found)> {
// The importer reads on a thread of its own (for its stack): what may be read is what may be
// read here.
let scope = crate::file_access::ScopeHandle::capture();
@@ -588,7 +615,7 @@ pub(crate) fn import_svg(text: &str, folder: Option<&str>) -> Result<(Document,
Some((bytes, link))
})
};
vectorcraft_svg::import_with(text, &vectorcraft_svg::ImportOptions { folder, read: Some(&read) }).map_err(err)
vectorcraft_svg::import_finding(text, &vectorcraft_svg::ImportOptions { folder, read: Some(&read) }, ids).map_err(err)
}
/// Open a file's bytes as the new active document (what `document.open` does) →
@@ -1019,13 +1046,38 @@ fn is_loss(note: &str) -> bool {
/// Another name keeps the original file, with all it has.
pub(crate) fn check_not_lossy_overwrite(st: &crate::DocState, target: &str, p: &Value, cmd: &str) -> Result<()> {
let Some(losses) = overwrite_losses(st, target, p) else { return Ok(()) };
Err(lossy_overwrite(target, losses, cmd))
}
/// The refusal to write `target`, the file the document was read from, when reading it left out `losses`.
fn lossy_overwrite(target: &str, losses: &[String], cmd: &str) -> EngineError {
let what = losses_summary(losses);
Err(bad(
bad(
cmd,
format!(
"{target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway"
),
))
)
}
/// The file the document was read from and what reading it left out, when a write to that file
/// needs `acknowledgeLoss` and `p` does not have it ([`overwrite_losses`]).
pub(crate) fn lossy_source(st: &crate::DocState, p: &Value) -> Option<(String, Vec<String>)> {
let source = st.imported_from.as_deref().filter(|_| !st.import_losses.is_empty())?;
(!bool_or(p, "acknowledgeLoss", false)).then(|| (source.to_string(), st.import_losses.clone()))
}
/// None of the files `targets` (every file a save writes, before any is written) is the
/// `source` file that reading left `losses` out of ([`lossy_source`]).
pub(crate) fn check_files_not_lossy_overwrite<'a>(
source: &(String, Vec<String>),
targets: impl IntoIterator<Item = &'a str>,
cmd: &str,
) -> Result<()> {
match targets.into_iter().find(|t| same_file(&source.0, t)) {
Some(target) => Err(lossy_overwrite(target, &source.1, cmd)),
None => Ok(()),
}
}
/// What writing the file `target` for document `st` would lose for good: the notes of what reading
+26 -23
View File
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, S
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
use super::{ArtboardPick, FormatOption, write_or_return};
use super::{ArtboardPick, FormatOption, Note, note_texts, write_or_return};
use crate::EngineError;
const C: &str = "document.exportPdf";
@@ -284,21 +284,22 @@ pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// Encode `doc` as PDF with the options in `p` → (bytes, warnings). Raster effects are rendered
/// Encode `doc` as PDF with the options in `p` → (bytes, notes). Raster effects are rendered
/// to images at the document's raster effects resolution. Preserve Editing embeds `doc` itself
/// when the PDF has every artboard (a PDF of some reopens as just those).
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
encode_at(cmd, doc, p, None)
}
/// [`encode`] modified at `modified` (Unix seconds) when given, instead of the time of writing.
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<String>)> {
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<Note>)> {
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
let (full, mut warnings) = crate::cmd::place::document::full_documents(doc);
let (bytes, drawn_warnings) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
warnings.extend(drawn_warnings);
warnings.extend(overflow_warning(cmd, &full, p)?);
Ok((bytes, warnings))
let (full, placed) = crate::cmd::place::document::full_documents(doc);
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
notes.extend(drawn);
notes.extend(overflow_warning(cmd, &full, p)?.map(Note::loss));
Ok((bytes, notes))
}
/// The warning about the type that the pages of a PDF of `doc` with the options in `p` draw and
@@ -321,7 +322,7 @@ pub(super) fn encode_carrying(
p: &Value,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<String>)> {
) -> Result<(Vec<u8>, Vec<Note>)> {
encode_carrying_at(cmd, doc, p, None, native, private)
}
@@ -334,7 +335,7 @@ fn encode_carrying_at(
modified: Option<i64>,
native: impl FnOnce() -> Result<Vec<u8>>,
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
) -> Result<(Vec<u8>, Vec<String>)> {
) -> Result<(Vec<u8>, Vec<Note>)> {
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
@@ -345,21 +346,22 @@ fn encode_carrying_at(
if opts.settings.thumbnails {
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
}
let mut warnings = vec![];
// The status bar shows the first warning, so this one goes ahead of the flattening note.
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
warnings.push(BLEED_LEFT_OUT.to_string());
notes.push(Note::loss(BLEED_LEFT_OUT));
}
if opts.settings.preserve_editing {
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
opts.native = Some(native()?);
if let Some((data, lost)) = private()? {
opts.private_data = Some(data);
warnings.extend(lost);
notes.extend(lost.into_iter().map(Note::loss));
}
} else {
opts.settings.preserve_editing = false;
warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string());
notes.push(Note::setting(EDITING_NEEDS_EVERY_ARTBOARD));
}
}
let set = &opts.settings;
@@ -370,12 +372,13 @@ fn encode_carrying_at(
vectorcraft_doc::cancel::check()?;
if flattened {
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"));
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
}
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
warnings.extend(r.warnings);
warnings.extend(crate::cmd::fonts::substitution_warning(doc));
Ok((r.bytes, warnings))
notes.extend(r.warnings.into_iter().map(Note::loss));
notes.extend(r.setting_notes.into_iter().map(Note::setting));
notes.extend(crate::cmd::fonts::substitution_warning(doc).map(Note::loss));
Ok((r.bytes, notes))
}
/// The flattener preset of PDF 1.3 files whose `flattenerPreset` is empty.
@@ -479,8 +482,8 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
} else {
q = json!({ "_displayDocTitle": display_doc_title });
}
let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": warnings }))
let (bytes, notes) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(&notes) }))
}
/// `(path, value)` for every leaf of `v` that differs from `default` (`compression.color.ppi`).
@@ -512,7 +515,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
let set = settings_with(Q, p, saved)?;
let diff = changes(&set, &preset_settings(Q, p, saved)?);
let warnings = match s.active() {
Some(st) if bool_or(p, "includeDocument", false) => encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1,
Some(st) if bool_or(p, "includeDocument", false) => note_texts(&encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1),
_ => set.warnings(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
+36 -14
View File
@@ -99,6 +99,10 @@ pub struct SavePlan {
/// `preview`, `precision`) given beside the path, and each key of `options`, that the format
/// doesn't read, naming the file the save writes.
pub notes: Vec<String>,
/// The file the document was read from and what reading it left out, when the save needs
/// `acknowledgeLoss` to write over it and was not given it: every file the save writes is
/// checked against it before the first is written.
pub lossy_source: Option<(String, Vec<String>)>,
}
impl SavePlan {
@@ -303,7 +307,9 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
};
let modified = date_param(p, "modified", cmd)?;
if let Some(path) = &path {
super::check_not_lossy_overwrite(st, path, p, cmd)?;
// Without a path, it is the document's own file: the error names it as the request may see it.
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
super::check_not_lossy_overwrite(st, path, p, cmd).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })?;
}
let written = written_as(cmd, format, &Value::Object(options.clone()));
let top = NATIVE_OPTIONS.iter().filter(|k| p.get(**k).is_some_and(|v| !v.is_null())).map(|k| k.to_string());
@@ -313,7 +319,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
.chain(nested.filter(|k| !reads_option(format, k)).map(|k| format!("options.{k}")))
.map(|k| format!("`{k}` was not used: {} files don't read it", written.label))
.collect();
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes })
let lossy_source = super::lossy_source(st, p);
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source })
}
/// The native save options, which a save also takes beside the path.
@@ -745,12 +752,14 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
carries_editing.set(true);
Ok(Some((data, resolved_warnings)))
};
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, &params, native, private)?;
warnings.extend(placed_warnings);
let (bytes, notes) = super::pdf::encode_carrying(cmd, &pages, &params, native, private)?;
let mut enc = Encoded::one_with_notes(bytes, notes);
enc.warnings.extend(placed_warnings);
// A note on the options: `pdfCompatible: false` writes blank pages.
if !pdf_compatible {
warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
enc.setting_notes.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
}
Ok(Encoded { warnings, ..Encoded::one(bytes) })
Ok(enc)
}
/// Snapshot the active document for `plan` (stamping File Info's dates on the snapshot when the
@@ -838,8 +847,8 @@ impl SaveJob {
}
/// Encode the file → it (and, with `separateArtboards`, a file per artboard after it), with
/// the warnings (what the format loses first, then the encoder's own notes: PDF options not
/// applied yet…, then the plan's notes on its params).
/// the notes (what the format loses first, then the encoder's own notes: PDF options not
/// applied yet…, then the plan's notes on its params, which are notes on the options).
pub fn encode(&self) -> Result<Encoded> {
let mut enc = self.encode_one(&self.doc)?;
for &b in &self.boards {
@@ -847,7 +856,7 @@ impl SaveJob {
enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes)));
}
enc.warnings.splice(0..0, self.format_losses());
enc.warnings.extend(self.plan.notes.iter().cloned());
enc.setting_notes.extend(self.plan.notes.iter().cloned());
Ok(enc)
}
@@ -898,9 +907,8 @@ impl SaveJob {
/// order: when `stop` returns a value, nothing is written and that value is returned.
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let (plan, doc) = (&self.plan, &*self.doc);
let mut enc = self.encode()?;
let warnings = std::mem::take(&mut enc.warnings);
let extra = json!({ "format": plan.format.id, "warnings": warnings });
let enc = self.encode()?;
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
let Some(path) = &plan.path else {
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
out["name"] = json!(plan.name);
@@ -910,6 +918,9 @@ impl SaveJob {
return Ok(out);
};
let files = enc.named(doc, path);
if let Some(source) = &plan.lossy_source {
super::check_files_not_lossy_overwrite(source, files.iter().map(|(p, _)| p.as_str()), plan.mode.command())?;
}
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
return Ok(stopped);
}
@@ -1021,6 +1032,8 @@ impl SaveJob {
}
// The other open documents that place this one show the new version.
let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template"));
// A save of the arrowheads file lists its heads in the arrowhead menus.
let native = self.plan.format.id == "vectorcraft";
if let Some(st) = s.document_mut(uid) {
self.finish(st);
}
@@ -1028,6 +1041,9 @@ impl SaveJob {
crate::cmd::recovery::forget(s, uid);
}
if let Some(path) = written {
if native {
s.arrowheads_saved(&path);
}
crate::cmd::links::refresh_placed(s, uid, &path);
}
}
@@ -1048,7 +1064,12 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value>
let plan = save_plan(s, mode, p)?;
let job = save_job(s, plan)?;
let uid = s.doc()?.uid;
let mut out = job.write_streamed(&mut super::write_save_file_with)?;
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
// Without a path, the files written are the document's own file and those beside it.
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
};
let mut out = job.write_streamed(&mut write)?;
job.complete(s, uid);
leave_out_unreadable_save_paths(&mut out, str_param(p, "path"));
Ok(out)
@@ -1103,7 +1124,8 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> {
fn revert(s: &mut Session, _: &Value) -> Result<Value> {
let index = s.active_index().ok_or(crate::EngineError::NoDocument)?;
let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?;
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
let bytes = read_file(&path).map_err(|e| super::access::naming_in_error(e, &path))?;
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &bytes)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
doc.template = false;
// Back to the saved file: its recovery copy has nothing left to recover.
let uid = s.doc()?.uid;
+58 -54
View File
@@ -17,12 +17,12 @@ use vectorcraft_doc::Document;
use vectorcraft_geom::Rect;
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
use super::encode::single_artboard;
use super::encode::{add_note, single_artboard};
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
use super::naming::{self, NameParts};
use super::{
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_warnings, merge,
unique_file_names_keeping_dots, with_black_output, writable, write_file,
ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge,
note_texts, unique_file_names_keeping_dots, with_black_output, writable, write_file,
};
const C: &str = "document.exportForScreens";
@@ -649,59 +649,34 @@ pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
let p = with_preset(s, p)?;
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
let mut r = export(s, &p).map_err(|e| match hidden {
Some(folder) => leave_out_folder_from_error(e, folder),
Some(folder) => super::access::naming_in_error(e, folder),
None => e,
})?;
remember(s, &p);
// A prepared export is written later, maybe on another thread: it names the folder as this
// request may see it.
if let (Some(folder), Some(Some(export))) = (hidden, s.screens_hand_off.as_mut()) {
export.hidden = Some((folder.to_string(), super::access::error_name(folder)));
}
if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) {
leave_out_unreadable_folder(&mut r, folder);
}
Ok(r)
}
/// An error of an export into `folder`, a folder outside the read roots that the client did not
/// give: `folder` as the path the error is about names it by its own name
/// ([`super::access::shown_path`]), and the rest of the message stays.
fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError {
let name = super::access::shown_path(folder);
match e {
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)),
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) },
e => e,
}
}
/// `msg` with `folder` given as `name` where it begins a path the message is about: at the start
/// of `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or
/// after `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message
/// names stays whole, even one inside `folder`.
fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String {
const BEFORE: [&str; 2] = [": ", "cannot resolve "];
let mut out = String::with_capacity(msg.len());
let mut rest = msg;
loop {
if let Some(after) = rest.strip_prefix(folder)
&& after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' '))
{
out.push_str(name);
rest = after;
}
let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break };
out.push_str(&rest[..i + len]);
rest = &rest[i + len..];
}
out.push_str(rest);
out
}
/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being
/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's
/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`),
/// as the reply of an export to a ZIP names them.
fn leave_out_unreadable_folder(r: &mut Value, folder: &str) {
if super::access::shown(folder) {
return;
if !super::access::shown(folder) {
leave_out_folder(r, folder);
}
}
/// The reply `r` of an export into `folder` with the ZIP's `path` left out and `files` named
/// relative to `folder` ([`leave_out_unreadable_folder`]).
fn leave_out_folder(r: &mut Value, folder: &str) {
let Some(o) = r.as_object_mut() else { return };
o.remove("path");
let inside = format!("{folder}/");
@@ -1046,7 +1021,8 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
/// so do different files that would share a name, with or without the `name` pattern. The reply's
/// `warnings` lists every warning the encoders give for the files, each once.
/// `warnings` lists every warning the encoders give for the files, each once, what the files lose
/// first ([`super::note_texts`]).
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
check_passwords(p)?;
let o = ScreenParams::of(p)?;
@@ -1074,7 +1050,7 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
// Include Artboard Fill off: the encoders leave the background colors out.
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
let rows = rows.into_iter().map(|r| Row { options: merge(with_black_output(s, &r.options), fill.clone()), ..r }).collect();
let export = ScreenExport { cmd: C, o, rows, naming, items };
let export = ScreenExport { cmd: C, o, rows, naming, items, hidden: None };
match &mut s.screens_hand_off {
Some(slot) => {
*slot = Some(export);
@@ -1095,9 +1071,27 @@ pub struct ScreenExport {
rows: Vec<Row>,
naming: Naming,
items: Vec<Item>,
/// The export folder and the name the request that prepared the export may see it by, when the
/// folder came from the `exportPreset` and is outside that request's read roots: the reply and
/// the errors of [`ScreenExport::write`] name it as [`export_for_screens`] does.
hidden: Option<(String, String)>,
}
impl Session {
/// The folder `document.exportForScreens` (`id`) with `params` writes into, the client's
/// `folder` or else the one its `exportPreset` keeps, with the name the request being served may
/// see it by when the reply leaves it out: a preset's folder outside the read roots, named by
/// its own name ([`super::access::shown_path`]). `assets.export` takes no preset, so for it the
/// folder is the client's. → `None` without a folder (the files come back in the reply) or for
/// an unknown preset, which the export itself refuses.
pub fn screen_export_folder(&self, id: &str, params: &Value) -> Option<(String, Option<String>)> {
let given = params.get("folder").is_some();
let p = if given || id == ASSETS { params.clone() } else { with_preset(self, params).ok()? };
let folder = str_param(&p, "folder").filter(|f| !f.is_empty())?.to_string();
let hidden = (!given && !super::access::shown(&folder)).then(|| super::access::shown_path(&folder).into_owned());
Some((folder, hidden))
}
/// Run `assets.export` when `id` names it, else `document.exportForScreens`, with `params` as
/// a command (checked and journaled as any other; Export for Screens remembers its settings)
/// that encodes and writes nothing → the export it prepared, which [`ScreenExport::write`]
@@ -1123,10 +1117,19 @@ impl ScreenExport {
/// return → the reply of `document.exportForScreens`. It reports one progress step per file
/// ([`vectorcraft_doc::cancel::progress`]), and a cancel stops it before it encodes or writes
/// another file.
pub fn write(self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
pub fn write(mut self, writer: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
let cmd = self.cmd;
let hidden = self.hidden.take();
// A refusal names `assets.export` when that command prepared the export, as its reply does.
encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) })
let r = encode_and_write(self, writer).map_err(|e| if cmd == C { e } else { crate::cmd::assets::of_cmd(cmd, e) });
match hidden {
Some((folder, name)) => {
let mut r = r.map_err(|e| super::access::naming_as(e, &folder, &name))?;
leave_out_folder(&mut r, &folder);
Ok(r)
}
None => r,
}
}
}
@@ -1138,18 +1141,16 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
create_dir(dir)?;
}
let mut out = Output::default();
// The encoders' warnings for every file, each once.
let mut warnings: Vec<String> = Vec::new();
// The encoders' notes for every file, each once.
let mut notes: Vec<Note> = Vec::new();
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
// written on a page of their own bounds, which it doesn't grow.
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
for w in notes {
if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) {
warnings.push(w);
}
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
add_note(&mut notes, n);
}
Ok(bytes)
};
@@ -1224,6 +1225,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
if o.zip || folder.is_none() {
vectorcraft_doc::cancel::check()?;
}
// What the files lose first, across every file.
let warnings = note_texts(&notes);
let names: Vec<&str> = out.kept.iter().map(|(n, _)| n.as_str()).collect();
if o.zip {
let zip = super::zip::deflate(&out.kept, super::zip::FIXED_TIME, vectorcraft_doc::cancel::is_cancelled);
@@ -1475,7 +1478,8 @@ pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
#[cfg(test)]
mod tests {
use super::{Output, ScreenSize, leave_out_folder_from_message, safe_file_name};
use super::super::access::naming_in_message;
use super::{Output, ScreenSize, safe_file_name};
/// A hidden export folder is named by its name where a message is about it, and a root that
/// starts with the same text, or a longer path, stays whole.
@@ -1492,7 +1496,7 @@ mod tests {
("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"),
];
for (msg, want) in cases {
assert_eq!(leave_out_folder_from_message(msg, f, "out"), want, "{msg}");
assert_eq!(naming_in_message(msg, f, "out"), want, "{msg}");
}
}
+7
View File
@@ -90,6 +90,12 @@ pub const OPTIONS: &[FormatOption] = &[
default: "false",
description: "embed the fonts type uses as @font-face, subset to the characters used (whole when the font's licence forbids subsetting, left out with a warning when it forbids embedding)",
},
FormatOption {
name: "variableData",
ty: "boolean",
default: "false",
description: "Include Variable Data: write the text variables, the data sets and the type object each text variable is bound to as a variable library (variableSets) that document.open and variable.loadLibrary read back; variables of other kinds, and what is past the limits variable.loadLibrary reads (256 text variables, 1,000 data sets, 8 MiB), are left out with a warning",
},
FormatOption {
name: "svg",
ty: "object",
@@ -198,6 +204,7 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
enc.warnings.push(w);
}
}
enc.add_setting_notes(out.setting_notes);
enc.files.push((artboard, if compressed { vectorcraft_svg::compress_bytes(&bytes) } else { bytes }));
}
// Live type names its fonts; outlines and embedded fonts are the fallback font's.
Loaded 100 of 467 files, more files were not shown because too many files have changed in this diff. Show more