Merge main into fix/text-wrap-offset-refused

This commit is contained in:
dotCooCoo committed 2026-11-14 12:30:12 -08:00
commit c7fa644f2f
339 files changed
+26695 -2336

No files matched your search

+49 -4
View File
@@ -8,23 +8,40 @@
//! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none:
//! heartbeats alone decide there.
#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::collections::{BTreeMap, BTreeSet};
#[cfg(target_arch = "wasm32")]
use std::sync::{Arc, Mutex};
#[cfg(target_arch = "wasm32")]
use js_sys::{Function, Promise, Reflect};
#[cfg(target_arch = "wasm32")]
use vectorcraft_engine::cmd::recovery::Hold;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast as _;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::closure::Closure;
/// How often the snapshot of the locks held is refreshed (ms).
#[cfg(target_arch = "wasm32")]
const REFRESH_MS: i32 = 10_000;
/// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was
/// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under
/// that is safe; an older snapshot counts every area as held.
const FRESH_MS: f64 = 60_000.0;
/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on
/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later
/// than `now`.
fn trusted(asked: f64, now: f64) -> bool {
(0.0..=FRESH_MS).contains(&(now - asked))
}
#[cfg(target_arch = "wasm32")]
thread_local! {
/// What releases each lock this tab holds, by name: it resolves the promise the lock is held
/// by (wasm runs on one thread).
@@ -32,26 +49,31 @@ thread_local! {
}
/// The locks of the page, named `<prefix><area>`.
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct WebLocks {
prefix: &'static str,
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms since
/// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms on
/// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does
/// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// [`REFRESH_MS`] and read from here.
seen: Arc<Mutex<(f64, BTreeSet<String>)>>,
}
/// `navigator.locks`, if the browser has it here.
#[cfg(target_arch = "wasm32")]
fn manager() -> Option<JsValue> {
let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?;
locks.is_object().then_some(locks)
}
/// Method `name` of `obj`.
#[cfg(target_arch = "wasm32")]
fn method(obj: &JsValue, name: &str) -> Option<Function> {
Reflect::get(obj, &name.into()).ok()?.dyn_into().ok()
}
#[cfg(target_arch = "wasm32")]
impl WebLocks {
/// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when
/// the browser has none or won't say which are held (heartbeats alone decide then).
@@ -75,7 +97,7 @@ impl WebLocks {
/// Take a new snapshot of the locks held.
async fn refresh(&self) -> Option<()> {
let m = manager()?;
let asked = js_sys::Date::now();
let asked = vectorcraft_ui_egui::now_ms();
let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?;
let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?;
let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?);
@@ -91,7 +113,7 @@ impl WebLocks {
/// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell.
pub fn held(&self, area: &str) -> bool {
let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area)
!trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area)
}
/// Hold `area`'s lock until the returned hold is dropped (or the page goes).
@@ -110,8 +132,10 @@ impl WebLocks {
}
/// A lock this tab holds (by name), released when dropped.
#[cfg(target_arch = "wasm32")]
struct LockHold(String);
#[cfg(target_arch = "wasm32")]
impl Drop for LockHold {
fn drop(&mut self) {
if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) {
@@ -120,3 +144,24 @@ impl Drop for LockHold {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_is_trusted_for_a_minute() {
assert!(trusted(1_000.0, 1_000.0));
assert!(trusted(1_000.0, 1_000.0 + FRESH_MS));
assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS));
// Before the first snapshot every area counts as held.
assert!(!trusted(f64::NEG_INFINITY, 0.0));
}
#[test]
fn a_snapshot_stamped_later_than_now_is_not_trusted() {
// A clock that went back reads an old snapshot as taken in the future.
assert!(!trusted(5_000_000.0, 1_000.0));
assert!(!trusted(1_001.0, 1_000.0));
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ mod api;
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
mod keys;
#[cfg(target_arch = "wasm32")]
#[cfg(any(target_arch = "wasm32", test))]
mod locks;
#[cfg(any(target_arch = "wasm32", test))]
mod pencil;
+389 -34
View File
@@ -11,13 +11,14 @@
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads SVG,
//! text and PNG. A clipboard that can't be opened is tried again after a wait that grows to a
//! minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app
//! Copy offers SVG (`image/svg+xml`), PNG (`image/png`) and text together, and Paste reads copied
//! files (`text/uri-list`), SVG, text and PNG. A clipboard that can't be opened is tried again
//! after a wait that grows to a minute, not each time Paste asks. On Linux and the BSDs a read waits 2 s at most for the app
//! that copied to send its data (a bitmap 10 s), and until that app answers, later reads fail at
//! once; a paste then waits for that read's answer off the UI thread.
//! - Everywhere: files copied in a file manager paste as the first one that is art (SVG, PDF, EPS,
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text).
//! a metafile or a bitmap), before the clipboard's other formats (the files' paths as text). A
//! file of more than 64 MiB is skipped before it is read.
use std::io::{Cursor, Read};
use std::path::PathBuf;
@@ -144,9 +145,18 @@ fn dib_image(dib: &[u8]) -> Option<image::RgbaImage> {
Some(img)
}
/// The most bytes a paste takes from another app (untrusted data), VectorCraft's own limit: a copied
/// file of more is skipped, and on Wayland a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// The first of `paths` (files copied in a file manager) that pastes as one of `mimes`, read
/// whole. Only its first bytes are read to tell, so other files cost little.
/// whole, at most [`MAX_BYTES`]. Only its first bytes are read to tell, so other files cost little.
fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
copied_file_within(paths, mimes, MAX_BYTES)
}
/// [`copied_file`] with a file of more than `limit` bytes skipped.
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -164,14 +174,108 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
if !std::fs::metadata(&path).ok()?.is_file() {
return None;
}
let mut file = std::fs::File::open(&path).ok()?;
// The file opened may not be the one looked at: its size is checked before any read.
let meta = file.metadata().ok()?;
if !meta.is_file() || meta.len() > limit as u64 {
return None;
}
let mut head = Vec::with_capacity(FILE_HEAD);
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
(&mut file).take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
let data = std::fs::read(&path).ok()?;
let data = read_rest(file, head, limit)?;
(!data.is_empty()).then_some(Flavour { mime, data })
})
}
/// `data` (the first bytes read of `file`) followed by the rest of `file`, or `None` when they come
/// to more than `limit` bytes, as when the file grew after its size was checked. At most one byte
/// past `limit` is read.
fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>> {
let more = (limit + 1).saturating_sub(data.len());
file.take(more as u64).read_to_end(&mut data).ok()?;
(data.len() <= limit).then_some(data)
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
/// The local files a `text/uri-list` names, in order ([`file_uri_path`]). Each line holds one URI
/// and a line that starts with `#` is a comment (RFC 2483, section 5); lines end in CRLF or LF.
/// Lines that are not UTF-8 and URIs that don't name a local file are skipped. A list of more than
/// [`MAX_URIS`] URIs names none.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn uri_list_paths(list: &[u8]) -> Vec<PathBuf> {
let uris: Vec<&[u8]> = list
.split(|&b| b == b'\n')
.map(|line| line.strip_suffix(b"\r").unwrap_or(line))
.filter(|line| !line.is_empty() && !line.starts_with(b"#"))
.take(MAX_URIS + 1)
.collect();
if uris.len() > MAX_URIS {
return vec![];
}
uris.into_iter().filter_map(|uri| file_uri_path(std::str::from_utf8(uri).ok()?)).collect()
}
/// The local files GNOME Files' `x-special/gnome-copied-files` names: a first line of `copy` or
/// `cut`, then one URI a line, read as [`uri_list_paths`] reads them. A paste places the files'
/// art either way and leaves the files where they are. No files when the first line is neither.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn gnome_copied_paths(list: &[u8]) -> Vec<PathBuf> {
let (action, uris) = match list.iter().position(|&b| b == b'\n') {
Some(end) => (list.get(..end).unwrap_or_default(), list.get(end + 1..).unwrap_or_default()),
None => (list, &[][..]),
};
match action.strip_suffix(b"\r").unwrap_or(action) {
b"copy" | b"cut" => uri_list_paths(uris),
_ => vec![],
}
}
/// The absolute path a `file:` URI names on this machine: `file:/path`, `file:///path` or
/// `file://localhost/path` (RFC 8089, section 2; scheme and host in any letter case), its percent
/// escapes decoded once (RFC 3986, section 2.1) and a fragment (`#…`) left out. None for another
/// scheme, another host, a relative path, a query (`?…`), a bad escape, an escaped NUL or a path
/// that is not UTF-8 once decoded.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn file_uri_path(uri: &str) -> Option<PathBuf> {
let uri = uri.trim_matches(|c: char| c.is_ascii_whitespace());
let uri = uri.split_once('#').map_or(uri, |(before, _)| before);
if uri.contains('?') {
return None;
}
let scheme = uri.get(..5).filter(|s| s.eq_ignore_ascii_case("file:"))?;
let rest = uri.get(scheme.len()..)?;
let path = match rest.strip_prefix("//") {
Some(authority_and_path) => {
let slash = authority_and_path.find('/')?;
let host = authority_and_path.get(..slash)?;
if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") {
return None;
}
authority_and_path.get(slash..)?
}
None => rest.starts_with('/').then_some(rest)?,
};
let mut bytes = Vec::with_capacity(path.len());
let mut it = path.bytes();
while let Some(b) = it.next() {
if b == b'%' {
let hex = |d: Option<u8>| char::from(d?).to_digit(16);
let (hi, lo) = (hex(it.next())?, hex(it.next())?);
bytes.push(u8::try_from(hi * 16 + lo).ok()?);
} else {
bytes.push(b);
}
}
if bytes.contains(&0) {
return None;
}
String::from_utf8(bytes).ok().map(PathBuf::from)
}
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
@@ -1094,7 +1198,9 @@ mod portable {
}
}
/// Files copied in a file manager (none where the backend can't read a file list).
/// Files copied in a file manager, read through arboard. The Wayland core protocol reads
/// its file list with the rest of a paste
/// ([`DataClipboard::read`](super::wayland::DataClipboard::read)).
fn file_list(&mut self) -> Vec<PathBuf> {
match self {
Self::Arboard(cb) => cb.read(Request::Files).files(),
@@ -1233,8 +1339,9 @@ mod portable {
}
/// Text and copied files are read here, and work that reads arboard's image comes back. On
/// the Wayland core protocol the first of `mimes` the clipboard offers is read: text here,
/// SVG and PNG by the work that comes back, which waits [`IMAGE_WAIT`] at most.
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
/// waits [`IMAGE_WAIT`] at most.
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let cb = self.cb(Asker::User).ok()?;
#[cfg(target_os = "linux")]
@@ -1335,9 +1442,9 @@ mod portable {
}
/// Text, on macOS vector art or a bitmap (by the pasteboard's types), and on the Wayland
/// core protocol SVG, text or PNG (by the types offered, nothing read). arboard has no
/// cheap way to ask for a bitmap (reading one costs as much as pasting it): the paste keys
/// take it, the menu item waits for text.
/// core protocol copied files, SVG, text or PNG (by the types offered, nothing read).
/// arboard has no cheap way to ask for a bitmap (reading one costs as much as pasting it):
/// the paste keys take it, the menu item waits for text.
fn has(&mut self, mimes: &[&'static str]) -> bool {
#[cfg(target_os = "macos")]
if super::mac::has(mimes) {
@@ -1784,12 +1891,13 @@ mod portable {
/// window's own Wayland connection: what Copy and Paste use where the compositor lacks the
/// data-control protocol arboard needs (GNOME) and there is no X11 to fall back on (the Flatpak on
/// a Wayland session). A Copy offers its SVG as `image/svg+xml`, its PNG as `image/png` and its
/// text under each of [`TEXT_TYPES`]; Paste reads the clipboard's SVG, text and PNG, and the paste
/// check looks at the types offered without reading any data. The protocol gives the clipboard to
/// the window with the keyboard focus only. A worker thread handles the protocol's events and
/// starts a thread for each paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads
/// run on another worker and take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, SVG and
/// PNG as long as a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
/// text under each of [`TEXT_TYPES`]; Paste reads the files a file manager copied
/// ([`FILE_LISTS`]), then the clipboard's SVG, text and PNG, and the paste check looks at the types
/// offered without reading any data. The protocol gives the clipboard to the window with the
/// keyboard focus only. A worker thread handles the protocol's events and starts a thread for each
/// paste of a Copy's data by another app ([`MAX_SENDS`] at once). Reads run on another worker and
/// take [`MAX_BYTES`] at most; text waits [`LOAD_WAIT`] at most, file lists, SVG and PNG as long as
/// a paste's bitmap from arboard. A read that gets no answer in its wait is kept for
/// a paste to wait for off the UI thread, as arboard's are. A read or send whose pipe moves no data
/// for [`IDLE_WAIT`] fails and closes the pipe, which frees its worker or thread.
#[cfg(target_os = "linux")]
@@ -1817,14 +1925,17 @@ mod wayland {
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::{BITMAP, Flavour, PNG, SVG, TEXT};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
/// and Qt apps), `UTF8_STRING` (X11 apps through XWayland) and `text/plain`.
const TEXT_TYPES: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
/// The most bytes a read takes from the app that copied (untrusted data), VectorCraft's own
/// limit: a read of more fails.
const MAX_BYTES: usize = 64 << 20;
/// What reads the files a file list names.
type PathsOf = fn(&[u8]) -> Vec<PathBuf>;
/// The types files copied in a file manager are offered under, each with what reads its files,
/// best first: `text/uri-list` (RFC 2483), and GNOME Files' own list, read only when the first
/// names no file.
const FILE_LISTS: [(&str, PathsOf); 2] = [("text/uri-list", uri_list_paths), ("x-special/gnome-copied-files", gnome_copied_paths)];
/// The most pastes of a Copy's data that are sent at once; a paste beyond them gets nothing.
const MAX_SENDS: usize = 8;
/// The most types of an offer that are kept (untrusted data).
@@ -1905,6 +2016,35 @@ mod wayland {
Some(first)
}
/// Whether a paste of one of `mimes` can take a copied file: one of them is not text.
fn takes_files(mimes: &[&'static str]) -> bool {
mimes.iter().any(|&m| m != TEXT)
}
/// The first type among `offered` that lists copied files ([`FILE_LISTS`]), in any letter case.
fn file_list_type(offered: &[String]) -> Option<&str> {
FILE_LISTS.iter().find_map(|(list, _)| offered.iter().find(|o| o.eq_ignore_ascii_case(list))).map(String::as_str)
}
/// The first file a file manager copied that pastes as one of `mimes` ([`copied_file`]), from
/// the first of [`FILE_LISTS`] among `offered` that names a file, `read` reading each list.
fn copied(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option<Vec<u8>>) -> Option<Flavour> {
if !takes_files(mimes) {
return None;
}
let paths = FILE_LISTS.iter().find_map(|(list, paths_of)| {
let wire = offered.iter().find(|o| o.eq_ignore_ascii_case(list))?;
Some(paths_of(&read(wire)?)).filter(|paths| !paths.is_empty())
})?;
copied_file(paths, mimes)
}
/// What a paste of one of `mimes` takes: the first copied file that is art ([`copied`]), else
/// what [`pick`] takes.
fn pick_pasted(offered: &[String], mimes: &[&'static str], mut read: impl FnMut(&str) -> Option<Vec<u8>>) -> Option<Flavour> {
copied(offered, mimes, &mut read).or_else(|| pick(offered, mimes, read))
}
/// The time `idle` from now; None when that is past the clock's range (no limit).
fn idle_until(idle: Duration) -> Option<Instant> {
Instant::now().checked_add(idle)
@@ -2089,9 +2229,9 @@ mod wayland {
impl Unanswered {
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
/// `limit` after the read was sent: the clipboard read again as [`pick`] reads it, each read
/// waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may have lost the
/// clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
@@ -2103,7 +2243,9 @@ mod wayland {
}
seen.offered.clone()
};
pick(&offered, mimes, |wire| wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok())
pick_pasted(&offered, mimes, |wire| {
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
})
}
}
@@ -2136,12 +2278,36 @@ mod wayland {
}
}
/// What a paste of one of `mimes` reads: the first the clipboard offers. Text is read here,
/// [`LOAD_WAIT`] at most, and pasted unless it is empty; SVG and PNG are asked for here and
/// waited for, `wait` at most, by the work that comes back. When that read fails or is
/// empty, the work reads the rest of `mimes` as [`pick`] does, each read waiting until
/// `wait` after the first was sent, [`LOAD_WAIT`] at least.
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
/// by the work that comes back. When that read fails or is empty, the work reads the rest
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
/// after the first was sent, [`LOAD_WAIT`] at least.
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
if takes_files(mimes) {
let offered = lock(&self.seen).offered.clone();
if let Some(list) = file_list_type(&offered).map(str::to_string) {
let sent = Instant::now();
let answer = self.loads.ask(list.clone()).ok()?;
self.unanswered = None;
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
return Some(ClipboardRead::Later(Box::new(move || {
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
// The list asked for here is read from its answer, every other type anew.
let mut first = Some((list, answer));
pick_pasted(&offered, &mimes, |wire| {
let answer = match first.take_if(|(list, _)| list.as_str() == wire) {
Some((_, answer)) => answer,
None => reads.ask(wire.to_string()).ok()?,
};
wait_for_answer(&answer, left()).ok()?.ok()
})
})));
}
}
mimes.iter().enumerate().find_map(|(i, &mime)| {
let wire = self.wire(mime)?;
if mime == TEXT {
@@ -2163,10 +2329,11 @@ mod wayland {
})
}
/// Whether the clipboard offers one of `mimes`; nothing is read.
/// Whether the clipboard offers one of `mimes`, or files a file manager copied when a paste
/// of `mimes` can take a file; nothing is read.
pub(super) fn has(&self, mimes: &[&'static str]) -> bool {
let seen = lock(&self.seen);
mimes.iter().any(|m| wire_type(m, &seen.offered).is_some())
(takes_files(mimes) && file_list_type(&seen.offered).is_some()) || mimes.iter().any(|m| wire_type(m, &seen.offered).is_some())
}
/// Whether the clipboard holds this connection's last Copy.
@@ -2835,6 +3002,85 @@ mod wayland {
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
/// Reads of a clipboard holding `data` by type, answered at once.
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
let types: Vec<&str> = types.iter().map(String::as_str).collect();
Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&types))))
}
/// The `file:` URI of `path`, its spaces escaped.
fn file_uri(path: &std::path::Path) -> String {
format!("file://{}", path.display().to_string().replace(' ', "%20"))
}
/// What a paste of `mimes` takes from `reads`.
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
match reads.read(mimes, Duration::from_secs(600))? {
ClipboardRead::Now(f) => Some((f.mime, f.data)),
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
}
}
#[test]
fn files_copied_in_a_file_manager_paste_as_their_art() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let d = tempfile::Builder::new().prefix("vectorcraft-wayland-files-").tempdir().unwrap();
let (notes, red) = (d.path().join("notes.txt"), d.path().join("red image.png"));
let mut png = vec![];
image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
std::fs::write(&notes, "not art").unwrap();
std::fs::write(&red, &png).unwrap();
let list = |paths: &[&std::path::Path]| paths.iter().map(|p| file_uri(p) + "\r\n").collect::<String>().into_bytes();
let held = |types: &[(&str, Vec<u8>)]| reads_holding(types.iter().map(|(t, d)| (t.to_string(), d.clone())).collect());
let text = ("text/plain;charset=utf-8", b"the files' paths".to_vec());
// A file list alone enables Paste and pastes the first file that is art.
let mut reads = held(&[("text/uri-list", list(&[&notes, &red]))]);
assert!(reads.has(&PASTE_ORDER) && reads.has(&[BITMAP]));
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
// A paste of text alone takes no file.
assert!(!reads.has(&[TEXT]));
assert_eq!(paste(&mut reads, &[TEXT]), None);
// The files come before the other types offered, as on the other platforms; the type in
// any letter case.
let mut reads = held(&[(SVG, b"<svg/>".to_vec()), text.clone(), ("Text/URI-List", list(&[&red]))]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
assert_eq!(paste(&mut reads, &[TEXT]), Some((TEXT, text.1.clone())));
// With no file that is art, the paste takes the other types.
let mut reads = held(&[("text/uri-list", list(&[&notes, &d.path().join("gone.png")])), text.clone()]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((TEXT, text.1.clone())));
let mut reads = held(&[("text/uri-list", b"https://example.com/art.png\r\n".to_vec())]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), None);
// GNOME Files' own list, alone or when the URI list names no local file.
let gnome = [b"copy\n".to_vec(), file_uri(&red).into_bytes()].concat();
let mut reads = held(&[("x-special/gnome-copied-files", gnome.clone())]);
assert!(reads.has(&PASTE_ORDER));
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
let mut reads = held(&[("text/uri-list", b"file://server/art.png\r\n".to_vec()), ("x-special/gnome-copied-files", gnome)]);
assert_eq!(paste(&mut reads, &PASTE_ORDER), Some((PNG, png.clone())));
// KDE's cut marker is not a file list.
let mut reads = held(&[("application/x-kde-cutselection", b"1".to_vec())]);
assert!(!reads.has(&PASTE_ORDER));
assert_eq!(paste(&mut reads, &PASTE_ORDER), None);
}
#[test]
fn a_file_list_that_cant_be_read_gives_way_to_the_other_types() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let offered = offered(&["text/uri-list", "text/plain"]);
let mut asked = vec![];
let f = pick_pasted(&offered, &PASTE_ORDER, |wire| {
asked.push(wire.to_string());
(wire == "text/plain").then(|| b"words".to_vec())
});
assert_eq!(f.map(|f| (f.mime, f.data)), Some((TEXT, b"words".to_vec())));
assert_eq!(asked, ["text/uri-list", "text/plain"]);
}
}
}
@@ -2952,6 +3198,115 @@ mod tests {
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
}
/// A copied file of more than 64 MiB is skipped before it is read, and the next one pastes.
#[test]
fn an_oversized_copied_file_is_skipped_before_it_is_read() {
let d = dir("oversized");
let (big, small) = (d.path().join("big.png"), d.path().join("small.png"));
std::fs::write(&big, png(2, 2)).unwrap();
// Sparse where the file system allows: no 64 MiB is written.
std::fs::OpenOptions::new().write(true).open(&big).unwrap().set_len(MAX_BYTES as u64 + 1).unwrap();
std::fs::write(&small, png(3, 2)).unwrap();
assert!(copied_file(vec![big.clone()], &PASTE_ORDER).is_none());
let f = copied_file(vec![big, small], &PASTE_ORDER).unwrap();
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
}
/// A copied file of exactly the limit pastes; one byte more and it is skipped.
#[test]
fn a_copied_file_pastes_up_to_the_limit() {
let d = dir("limit");
let art = d.path().join("art.svg");
let svg = "<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
std::fs::write(&art, svg).unwrap();
let read = |limit| copied_file_within(vec![art.clone()], &PASTE_ORDER, limit).map(|f| f.data);
assert_eq!(read(svg.len()), Some(svg.as_bytes().to_vec()));
assert_eq!(read(svg.len() - 1), None);
}
/// A file that grows past the limit after its size was checked is read to one byte past the
/// limit and refused.
#[test]
fn the_rest_of_a_file_is_read_to_the_limit_at_most() {
let read = |len: usize, head: usize| {
let bytes = vec![7u8; len];
let mut file = Cursor::new(bytes);
let mut first = vec![0; head];
file.read_exact(&mut first).unwrap();
(read_rest(&mut file, first, 16).map(|d| d.len()), file.position())
};
assert_eq!(read(16, 4), (Some(16), 16));
assert_eq!(read(0, 0), (Some(0), 0));
assert_eq!(read(17, 4), (None, 17));
assert_eq!(read(1000, 4), (None, 17));
// First bytes already past the limit: nothing more is read.
assert_eq!(read(1000, 20), (None, 20));
}
fn uri_paths(list: &[u8]) -> Vec<String> {
uri_list_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect()
}
#[test]
fn a_uri_list_names_the_local_files_of_its_lines() {
// CRLF or LF, comment lines and blank lines.
assert_eq!(uri_paths(b"# copied\r\nfile:///home/a/one.svg\r\n\r\nfile:///home/a/two.png\n"), ["/home/a/one.svg", "/home/a/two.png"]);
assert_eq!(uri_paths(b"file:///a.svg"), ["/a.svg"]);
// Percent escapes are decoded once; `+` and an escaped `#` are part of the name.
assert_eq!(uri_paths(b"file:///home/a/red%20image.png"), ["/home/a/red image.png"]);
assert_eq!(uri_paths(b"file:///home/a/caf%C3%A9.svg\nfile:///home/a/caf\xC3\xA9.svg"), ["/home/a/café.svg", "/home/a/café.svg"]);
assert_eq!(uri_paths(b"file:///a/%231+2.svg"), ["/a/#1+2.svg"]);
assert_eq!(uri_paths(b"file:///a/100%2525.svg"), ["/a/100%25.svg"]);
// No host, `localhost` in any case, and the short form name this machine; a fragment is
// left out.
assert_eq!(
uri_paths(b"file://localhost/a.svg\nFILE://LocalHost/b.svg\nfile:/c.svg\nfile:///d.svg#page=2"),
["/a.svg", "/b.svg", "/c.svg", "/d.svg"]
);
// Other hosts and schemes, relative paths, queries, bad escapes, an escaped NUL, a name
// that is not UTF-8 once decoded and a line that is not UTF-8 name no file.
for uri in [
&b"file://server/a.svg"[..],
b"https://example.com/a.svg",
b"file:a.svg",
b"file://",
b"file://localhost",
b"file:///a.svg?x=1",
b"file:///a%2",
b"file:///a%zz.svg",
b"file:///a%00b.svg",
b"file:///a%FF.svg",
b"file:///a\xFF.svg",
b"/home/a/one.svg",
b"#file:///a.svg",
] {
assert!(uri_list_paths(uri).is_empty(), "{}", String::from_utf8_lossy(uri));
}
// The files beside a URI that names none are kept.
assert_eq!(uri_paths(b"https://example.com/a.svg\r\nfile:///b.svg\r\n"), ["/b.svg"]);
assert!(uri_list_paths(b"").is_empty());
}
#[test]
fn a_uri_list_longer_than_the_limit_names_no_file() {
assert_eq!(MAX_URIS, 1024);
let list = |n: usize| (0..n).map(|i| format!("# file {i}\r\nfile:///f{i}.svg\r\n")).collect::<String>();
// Comment lines don't count.
assert_eq!(uri_list_paths(list(MAX_URIS).as_bytes()).len(), MAX_URIS);
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
}
#[test]
fn gnome_files_list_names_its_files_after_copy_or_cut() {
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
assert_eq!(paths(b"copy\nfile:///a.svg\nfile:///b%20c.png"), ["/a.svg", "/b c.png"]);
assert_eq!(paths(b"cut\r\nfile:///a.svg\r\n"), ["/a.svg"]);
// Another first line, none, or no files.
for list in [&b"move\nfile:///a.svg"[..], b"file:///a.svg\nfile:///b.svg", b"copy", b"", b"Copy\nfile:///a.svg"] {
assert!(gnome_copied_paths(list).is_empty(), "{}", String::from_utf8_lossy(list));
}
}
/// A DIB of `w`×`h` pixels (top row first when `h` is negative): a `header`-byte header (40,
/// or 124 for a BITMAPV5HEADER with BGRA masks), `extra` (the masks after a 40-byte header, a
/// colour table), then `rows`, each padded to 4 bytes.
+8 -1
View File
@@ -13,6 +13,7 @@
mod calli;
mod colorize;
mod defaults;
pub mod stored_art;
pub mod track;
mod warp;
@@ -799,9 +800,15 @@ fn number_repeated_names(lib: &mut [Brush]) {
}
}
/// Store `lib` as the document's brush library.
/// Store `lib` as the document's brush library. When the art of a brush holds images or placed
/// documents, each object in that art whose id is 0 or repeats another object's is given a new
/// id ([`stored_art::StoredArt::persist_ids`]), so the Links panel lists it by the same id until it
/// changes.
pub fn store(doc: &mut Document, lib: &[Brush]) {
doc.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap_or_default());
if lib.iter().any(|b| b.art().into_iter().any(stored_art::holds_files)) {
stored_art::StoredArt::persist_ids(doc);
}
}
/// Find a brush by name.
+176
View File
@@ -0,0 +1,176 @@
//! The art of the stored brushes (a scatter or art brush's art, a pattern brush's tiles) as stored
//! art of the document ([`Document::mounted_art`]): set on the document while a command looks it up
//! by id or changes it, then written back into the library entries whose art changed. The Links
//! panel finds the images and placed documents in that art this way.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use crate::{Brush, BrushKind, DOC_KEY};
/// The brushes of a document's stored library whose art holds images or placed documents.
#[derive(Default)]
pub struct StoredArt {
entries: Vec<Entry>,
/// How many entries the stored library had when it was read.
read_entries: usize,
}
/// A library entry whose brush's art holds images or placed documents.
struct Entry {
/// Its index in the stored library.
slot: usize,
/// The entry as it was read.
raw: Value,
brush: Brush,
/// The brush's art ([`Brush::art`]), each root with the `owner` the Links panel names for it.
art: Vec<(Arc<Node>, Value)>,
}
/// What names each root of [`Brush::art`] among the brush's art: a pattern brush's tile, in the
/// same order; nothing for the one root of a scatter or art brush.
fn tiles(b: &Brush) -> Vec<Option<&'static str>> {
match &b.kind {
BrushKind::Pattern(p) => std::iter::once(Some("side"))
.chain(
[
(p.outer_corner.is_some(), "outerCorner"),
(p.inner_corner.is_some(), "innerCorner"),
(p.start.is_some(), "start"),
(p.end.is_some(), "end"),
]
.into_iter()
.filter(|(held, _)| *held)
.map(|(_, tile)| Some(tile)),
)
.collect(),
_ => vec![None],
}
}
/// Whether `n` or its subtree, opacity-mask art included, holds an image or a placed document.
pub(crate) fn holds_files(n: &Node) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= matches!(c.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)));
found
}
impl StoredArt {
/// The brushes of `doc`'s stored library whose art holds an image or a placed document (opacity
/// masks included). An entry that does not read as a brush is left out, and so is left as it
/// is. A root's owner is
/// `{kind: "brush", name, index, tile?}`, with the name and index the brush has in the library as
/// the Brushes panel lists it ([`crate::library`], a repeated name numbered).
pub fn read(doc: &Document) -> Self {
let Some(stored) = doc.unknown.get(DOC_KEY) else { return Self::default() };
let Some(list) = stored.as_array() else { return Self::default() };
let listed = crate::parse_library(stored);
let parsed = list.iter().enumerate().filter_map(|(slot, raw)| Brush::from_json(raw.clone()).ok().map(|b| (slot, raw, b)));
let mut entries = vec![];
for (index, (slot, raw, brush)) in parsed.enumerate() {
if !brush.art().into_iter().any(holds_files) {
continue;
}
let name = listed.get(index).map_or(brush.name.as_str(), |b| b.name.as_str());
let art: Vec<(Arc<Node>, Value)> = brush
.art()
.into_iter()
.zip(tiles(&brush))
.map(|(n, tile)| {
let mut owner = json!({ "kind": "brush", "name": name, "index": index });
if let Some(tile) = tile {
owner["tile"] = json!(tile);
}
(Arc::new(n.clone()), owner)
})
.collect();
if !art.is_empty() {
entries.push(Entry { slot, raw: raw.clone(), brush, art });
}
}
Self { entries, read_entries: list.len() }
}
/// Gives the objects of the stored brushes' art that holds images or placed documents ids of
/// their own in `doc`'s library, as [`Self::mount`] gives them, and writes the brushes whose
/// ids changed back. Does nothing while art is set on `doc` ([`Document::mounted_art`]).
pub fn persist_ids(doc: &mut Document) {
if !doc.mounted_art.is_empty() {
return;
}
let art = Self::read(doc);
if !art.is_empty() {
art.mount(doc);
art.write_entries(doc);
}
}
/// No stored brush's art holds an image or a placed document.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Sets the art on `doc` as [`Document::mounted_art`], each object with an id of its own
/// ([`Document::number_mounted_art`]: an id another stored object has, or none, is replaced, and
/// the id counter stands above them all).
pub fn mount(&self, doc: &mut Document) {
doc.mounted_art = self.entries.iter().flat_map(|e| e.art.iter().cloned()).collect();
doc.number_mounted_art();
}
/// Takes [`Document::mounted_art`] off `doc` and writes each brush whose art changed (new ids
/// included) back into its library entry: the entry at its index when that entry is as it was
/// read or reads as the brush as it was apart from its name, else the first entry that reads as
/// the brush as it was, else the first that does apart from its name. An entry found apart from
/// its name keeps that name (the library was written again meanwhile, as placing a document's
/// brushes into it does, numbering a repeated name). The other entries are left as
/// they are. Then the art of brushes added meanwhile gets ids of its own
/// ([`Self::persist_ids`]).
pub fn write_back(self, doc: &mut Document) {
let read_entries = self.read_entries;
self.write_entries(doc);
if doc.unknown.get(DOC_KEY).and_then(Value::as_array).map(Vec::len) != Some(read_entries) {
Self::persist_ids(doc);
}
}
/// [`Self::write_back`] without giving ids to the art of brushes added meanwhile.
fn write_entries(self, doc: &mut Document) {
let mut mounted = std::mem::take(&mut doc.mounted_art).into_iter();
let mut changed = vec![];
for e in self.entries {
let now: Vec<Arc<Node>> = mounted.by_ref().take(e.art.len()).map(|(n, _)| n).collect();
if now.len() != e.art.len() || now.iter().zip(&e.art).all(|(a, (b, _))| Arc::ptr_eq(a, b)) {
continue;
}
let mut brush = e.brush.clone();
for (slot, art) in brush.art_mut().into_iter().zip(now) {
*slot = Arc::unwrap_or_clone(art);
}
changed.push((e.slot, e.raw, e.brush, brush));
}
let Some(list) = doc.unknown.get_mut(DOC_KEY).and_then(Value::as_array_mut) else { return };
for (slot, raw, was, mut brush) in changed {
// The entry's name when it reads as `was` apart from its name.
let name_of = |entry: &Value| {
Brush::from_json(entry.clone()).ok().and_then(|mut b| {
let name = std::mem::replace(&mut b.name, was.name.clone());
(b == was).then_some(name)
})
};
let at = match list.get(slot) {
Some(entry) if *entry == raw || name_of(entry).is_some() => Some(slot),
_ => list.iter().position(|e| name_of(e).as_ref() == Some(&was.name)).or_else(|| list.iter().position(|e| name_of(e).is_some())),
};
let Some(entry) = at.and_then(|i| list.get_mut(i)) else { continue };
if let Some(name) = name_of(entry) {
brush.name = name;
}
if let Ok(v) = serde_json::to_value(&brush) {
*entry = v;
}
}
}
}
+153
View File
@@ -1017,6 +1017,159 @@ fn repeated_brush_names_are_numbered_when_read() {
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len());
}
/// Art of `w`×`h` points holding a linked image: a group of [`rect_art`] and the image, both with id 0.
fn linked_art(w: f64, h: f64) -> Node {
let image = Node::new(
NodeId(0),
NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
key: "k".into(),
width: 4,
height: 4,
xf: Affine::IDENTITY,
link: Some(vectorcraft_doc::LinkInfo::new("/art/a.png")),
placement: Default::default(),
pixels: None,
})),
);
Node::group(NodeId(0), vec![std::sync::Arc::new(rect_art(w, h)), std::sync::Arc::new(image)])
}
/// The art of the stored brushes that holds images mounts on the document as stored art, each tile
/// with the brush, its place in the library and the tile as owner, its objects with ids of their
/// own; writing it back changes only the entries whose art changed, and leaves an entry that does
/// not read as a brush, a brush without art and a brush whose art holds no image as they were stored.
#[test]
fn stored_brush_art_mounts_and_writes_back_only_what_changed() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let layer_object = d.layers[0].id;
let mut side = linked_art(10.0, 4.0);
side.id = layer_object;
let pattern =
Brush { name: "Frame".into(), kind: BrushKind::Pattern(PatternBrush { side, start: Some(linked_art(4.0, 4.0)), ..Default::default() }) };
let scatter = Brush {
name: "Dots".into(),
kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), colorization: Colorization::None, ..Default::default() }),
};
// Written as a file holds it, without the ids `store` gives.
let lib = [calli(0.0, 100.0, 3.0), pattern, scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)];
d.unknown.insert(DOC_KEY.into(), serde_json::to_value(lib).unwrap());
let odd = serde_json::json!({ "name": "Odd", "type": "unknown" });
if let Some(list) = d.unknown.get_mut(DOC_KEY).and_then(serde_json::Value::as_array_mut) {
list.insert(1, odd.clone());
}
let stored = d.unknown[DOC_KEY].clone();
let art = StoredArt::read(&d);
art.mount(&mut d);
let owners: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| o).collect();
assert_eq!(
owners,
[
&serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "side" }),
&serde_json::json!({ "kind": "brush", "name": "Frame", "index": 1, "tile": "start" }),
&serde_json::json!({ "kind": "brush", "name": "Dots", "index": 2 }),
]
);
let ids: Vec<NodeId> = d.mounted_art.iter().map(|(n, _)| n.id).collect();
let mut all = vec![];
d.visit_stored(|n, _| all.push(n.id));
assert!(all.iter().all(|id| id.0 != 0) && !all[1..].contains(&layer_object), "{all:?}");
assert_eq!(all.iter().collect::<std::collections::HashSet<_>>().len(), all.len(), "{all:?}");
// The scatter brush's art changes; the pattern brush's tiles keep the ids mounting gave them.
d.stored_node_mut(ids[2]).unwrap().name = Some("changed".into());
art.write_back(&mut d);
assert!(d.mounted_art.is_empty());
let now = d.unknown[DOC_KEY].as_array().unwrap();
assert_eq!(now.len(), 5);
assert_eq!((&now[0], &now[1], &now[4]), (&stored[0], &odd, &stored[4]), "the entries without images stay as stored");
assert_ne!(now[2], stored[2], "the pattern brush keeps the ids its art was given");
let lib = library(&d);
let Some(BrushKind::Pattern(p)) = lib.iter().find(|b| b.name == "Frame").map(|b| &b.kind) else { panic!("no pattern brush") };
assert_eq!((p.side.id, p.start.as_ref().map(|n| n.id)), (ids[0], Some(ids[1])));
assert_eq!(find(&d, "Dots").unwrap().art()[0].name.as_deref(), Some("changed"));
// Mounting again gives the same ids and changes nothing, so writing back leaves the library as it is.
let again = d.unknown[DOC_KEY].clone();
let art = StoredArt::read(&d);
art.mount(&mut d);
assert_eq!(d.mounted_art.iter().map(|(n, _)| n.id).collect::<Vec<_>>(), ids);
art.write_back(&mut d);
assert_eq!(d.unknown[DOC_KEY], again);
}
/// A brush whose stored name repeats an earlier brush's is named in its art's owner as the Brushes
/// panel lists it, numbered.
#[test]
fn stored_brush_art_owner_names_a_repeated_name_as_listed() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: linked_art(2.0, 2.0), ..Default::default() }) };
store(&mut d, &[scatter.clone(), scatter]);
StoredArt::read(&d).mount(&mut d);
let names: Vec<&serde_json::Value> = d.mounted_art.iter().map(|(_, o)| &o["name"]).collect();
assert_eq!(names, ["Dots", "Dots 2"]);
}
/// Storing a library whose brush art holds an image gives that art ids of its own, so mounting it
/// later gives the same ids whatever the document allocated in between; art without images keeps
/// the ids it was stored with.
#[test]
fn storing_brush_art_with_images_keeps_ids_of_its_own() {
use stored_art::StoredArt;
let mut d = Document::new(100.0, 100.0);
let mut art = linked_art(2.0, 2.0);
art.id = d.layers[0].id;
let scatter = Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art, ..Default::default() }) };
store(&mut d, &[scatter, art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)]);
let lib = library(&d);
let stored = lib[0].art()[0].id;
assert_ne!(stored, d.layers[0].id);
assert_eq!(lib[1].art()[0].id, NodeId(0), "art without images is stored as it was");
d.alloc_id();
StoredArt::read(&d).mount(&mut d);
assert_eq!(d.mounted_art[0].0.id, stored);
}
/// When the library is written again while the art is mounted, numbering a repeated name and
/// adding a brush (as placing a document's brushes into it does), writing back changes the entry
/// at its own place that reads as the brush apart from its new name, keeping that name, even when
/// an earlier brush is the same as the one it was, and gives the added brush's art ids of its own.
#[test]
fn brush_art_written_back_finds_its_renamed_entry_and_numbers_added_art() {
use stored_art::StoredArt;
/// `n` with ids from `next` on, in paint order.
fn numbered(mut n: Node, next: &mut u64) -> Node {
n.id = NodeId(*next);
*next += 1;
for c in n.children_mut().into_iter().flatten() {
*c = std::sync::Arc::new(numbered((**c).clone(), next));
}
n
}
let mut d = Document::new(100.0, 100.0);
let scatter =
|n: &str| Brush { name: n.into(), kind: BrushKind::Scatter(Scatter { art: numbered(linked_art(2.0, 2.0), &mut 50), ..Default::default() }) };
// Two brushes the same apart from the ids mounting gives the second.
d.unknown.insert(DOC_KEY.into(), serde_json::to_value([scatter("Dots"), scatter("Dots")]).unwrap());
let art = StoredArt::read(&d);
art.mount(&mut d);
assert_eq!(d.mounted_art[0].0.id, NodeId(50));
let second = d.mounted_art[1].0.id;
// The library is written again: the repeated name numbered, a brush whose art repeats an id added.
let mut added = scatter("New");
if let BrushKind::Scatter(s) = &mut added.kind {
s.art.id = d.layers[0].id;
}
let lib = [library(&d), vec![added]].concat();
d.unknown.insert(DOC_KEY.into(), serde_json::to_value(&lib).unwrap());
assert_eq!(lib[1].name, "Dots 2");
d.stored_node_mut(second).unwrap().name = Some("changed".into());
art.write_back(&mut d);
let lib = library(&d);
assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["Dots", "Dots 2", "New"]);
assert_eq!((lib[0].art()[0].name.as_deref(), lib[1].art()[0].name.as_deref()), (None, Some("changed")));
assert_ne!(lib[2].art()[0].id, d.layers[0].id, "the added brush's art has ids of its own");
}
#[test]
fn brushes_serde_round_trip() {
let lib = defaults().to_vec();
+20
View File
@@ -1024,6 +1024,26 @@ fn overlaps(a: Rect, b: Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// Whether a plot draws nothing of `n` wherever it is, apart from what every export leaves out
/// (hidden objects, guides and template layers): an object at 0% opacity, a non-printing layer, a
/// placed image, a gradient mesh whose every point is at 0% opacity, or a path or compound path
/// without effects whose fills and strokes paint nothing. An image or a mesh in `doc` with a
/// visible Crop Marks effect, or with a Vector Halftone effect that makes dots, is not one of them.
/// A clipping path still clips when the plot draws nothing of it.
pub fn plots_nothing(doc: &Document, n: &Node) -> bool {
let unpainted = || n.appearance.effects.is_empty() && top_stroke(n).is_none() && top_fill(n).is_none();
let dots = || vectorcraft_effects::addons::halftone::halftone_art(doc, n).is_some_and(|g| g.children().is_some_and(|c| !c.is_empty()));
let adds_art = || vectorcraft_effects::has_crop_marks(n) || dots();
n.opacity <= 0.0
|| match &n.kind {
NodeKind::Layer { printable, .. } => !printable,
NodeKind::Image(_) => !adds_art(),
NodeKind::Mesh(m) => !adds_art() && m.points.iter().all(|p| p.opacity <= 0.0),
NodeKind::Path { .. } | NodeKind::Compound { .. } => unpainted(),
_ => false,
}
}
/// `nodes` (the children of a clipping container when `clipping`) without the layers and
/// sublayers a plot leaves out (hidden, non-printing, template or at 0% opacity) and without
/// guides, in layers and groups at any depth, so that baking can't wrap one in art that is drawn
+84
View File
@@ -177,6 +177,90 @@ fn meshes_in_blends_are_outlines_and_clear_meshes_draw_nothing() {
assert_eq!(t.matches("PD").count(), 3, "{t}");
}
/// `plots_nothing` picks the objects and layers that a plot draws nothing of: a path that paints
/// nothing, objects at 0% opacity, placed images, meshes with every point at 0% opacity and
/// non-printing layers, and not a painted path or a mesh.
#[test]
fn plots_nothing_picks_what_a_plot_draws_nothing_of() {
type Make = fn(&mut Document) -> Node;
let cases: [(&str, Make, bool); 7] = [
("stroked", |d| stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK), false),
("unpainted", |d| Node::path(d.alloc_id(), rect(10.0, 10.0, 40.0, 40.0), Appearance::basic(Paint::None, Paint::None, 1.0)), true),
(
"clear",
|d| {
let mut n = filled(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK);
n.opacity = 0.0;
n
},
true,
),
(
"image",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)))
},
true,
),
(
"image with Crop Marks",
|d| {
let image = vectorcraft_doc::ImageObject {
key: "raster-1".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
n.appearance.effects.push(vectorcraft_doc::Effect { id: "cropMarks".into(), params: serde_json::json!({}), visible: true });
n
},
false,
),
("mesh", |d| Node::new(d.alloc_id(), NodeKind::Mesh(mesh_at(10.0))), false),
(
"clear mesh",
|d| {
let mut clear = mesh_at(10.0);
clear.points.iter_mut().for_each(|p| p.opacity = 0.0);
Node::new(d.alloc_id(), NodeKind::Mesh(clear))
},
true,
),
];
for (name, make, nothing) in cases {
let mut held = None;
let d = doc_with(|d| {
let n = make(d);
held = Some(n.clone());
vec![n]
});
let Some(n) = held else { panic!("{name}") };
assert_eq!(plots_nothing(&d, &n), nothing, "{name}");
assert_eq!(text(&plot(&d, &opts(&d))) == "IN;PU;SP0;", nothing, "{name}");
}
let mut d = doc_with(|d| vec![stroked(d, rect(10.0, 10.0, 40.0, 40.0), Color::BLACK)]);
let layer = d.layers[0].id;
assert!(!plots_nothing(&d, &d.layers[0]));
if let Some(NodeKind::Layer { printable, .. }) = d.node_mut(layer).map(|n| &mut n.kind) {
*printable = false;
}
assert!(plots_nothing(&d, &d.layers[0]));
assert_eq!(text(&plot(&d, &opts(&d))), "IN;PU;SP0;");
}
/// Live art that makes more objects than the plot's limit (1,000 in tests) is left out with a
/// warning.
#[test]
+3 -1
View File
@@ -428,7 +428,9 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
return Err("the export region is not finite".into());
}
let baked = vectorcraft_effects::bake_document(doc);
// Symbols' art is placed without clipping, as the scene places it.
let baked =
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
}
+23
View File
@@ -1410,6 +1410,29 @@ fn a_stained_instance_is_written_in_its_stained_color() {
assert!(!colors.is_empty() && colors.iter().all(|c| c.as_deref() == Some("255")), "{colors:?}");
}
#[test]
fn symbol_art_effects_are_written_where_they_draw() {
// A line and the symbol's line below it, each moved 100 pt right by a Transform effect, start
// at the same x.
let moved = |mut n: Node| {
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "distort.transform".into(),
params: serde_json::json!({"moveH": 100.0}),
visible: true,
});
n
};
let mut d = doc_with(|d| {
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
vec![moved(line), Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })]
});
let art = path(&mut d, shapes::line((10.0, 40.0).into(), (20.0, 40.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) });
let starts: Vec<f64> = entities(&export(&d, &opts(&d)).unwrap()).iter().map(|e| all(e, 10).into_iter().fold(f64::INFINITY, f64::min)).collect();
assert_eq!(starts.len(), 2, "{starts:?}");
assert!((starts[0] - starts[1]).abs() < 1e-6, "{starts:?}");
}
#[test]
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
+104 -12
View File
@@ -9,13 +9,16 @@
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
//! [`crate::Color::to_rgb`] uses them. [`with_active`] puts other settings in their place on one
//! thread, as for a document drawn through its own profiles ([`for_document`]). Code that needs
//! deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod display;
pub mod generic;
pub mod icc;
pub mod lab;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
@@ -910,9 +913,32 @@ static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
thread_local! {
/// The settings [`with_active`] put in place of the active settings on this thread.
static SCOPED: RefCell<Option<Arc<Cms>>> = const { RefCell::new(None) };
/// [`SCOPED`]'s flags for the fast paths: [`SCOPED_SET`] while it is set, [`SCOPED_SRGB`] when
/// its RGB space is sRGB, and [`SCOPED_DEVICE`] when its CMYK space is device CMYK.
static SCOPED_FLAGS: Cell<u8> = const { Cell::new(0) };
}
const SCOPED_SET: u8 = 1;
const SCOPED_SRGB: u8 = 2;
const SCOPED_DEVICE: u8 = 4;
/// The active color-management context: the working settings, with the profiles
/// [`use_document_profiles`] last put in place of the working spaces.
/// [`use_document_profiles`] last put in place of the working spaces. Inside [`with_active`] on
/// this thread: the settings it was given.
pub fn active() -> Arc<Cms> {
if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0
&& let Some(c) = SCOPED.with(|s| s.borrow().clone())
{
return c;
}
installed()
}
/// The active settings of the process, as [`use_document_profiles`] or [`set_active`] last put them
/// in place.
fn installed() -> Arc<Cms> {
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
}
@@ -954,14 +980,8 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
/// the active settings changed.
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
let working = working();
let mut st = working.settings.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
if st == active().settings {
let st = document_settings(&working.settings, rgb, cmyk);
if st == installed().settings {
return false;
}
if st == working.settings {
@@ -976,6 +996,72 @@ pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
true
}
/// The working settings `working` with the profiles a document is assigned (`None`: none) in place
/// of the working spaces, as [`use_document_profiles`] takes them.
fn document_settings(working: &ColorSettings, rgb: Option<&str>, cmyk: Option<&str>) -> ColorSettings {
let mut st = working.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
st
}
/// How many contexts [`for_document`] keeps.
const DOCUMENT_CONTEXTS: usize = 8;
/// The color-management context a document assigned the profiles `rgb` and `cmyk` (`None`: none)
/// draws through: the one [`use_document_profiles`] would make active for it. A context that is the
/// active or the working one is that one; the others are kept for the same working settings and
/// loaded profiles, so the same document gets the same context again. A profile that cannot be
/// loaded gives the working settings.
pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
static KEPT: Mutex<Vec<(u64, Arc<Cms>)>> = Mutex::new(Vec::new());
let working = working();
let st = document_settings(&working.settings, rgb, cmyk);
let installed = installed();
if st == installed.settings {
return installed;
}
if st == working.settings {
return working;
}
let generation = profiles_generation();
let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
kept.retain(|(g, c)| *g == generation && c.working.as_ref().is_some_and(|w| Arc::ptr_eq(w, &working)));
if let Some((_, c)) = kept.iter().find(|(_, c)| c.settings == st) {
return c.clone();
}
let Ok(mut cms) = Cms::new(&st) else { return working };
cms.working = Some(working);
let cms = Arc::new(cms);
if kept.len() >= DOCUMENT_CONTEXTS {
kept.remove(0);
}
kept.push((generation, cms.clone()));
cms
}
/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`]
/// and the conversions that read them), as when drawing a document other than the front one
/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had.
pub fn with_active<R>(cms: Arc<Cms>, f: impl FnOnce() -> R) -> R {
/// Puts back the settings this thread had before, when `f` returns or unwinds.
struct Restore(Option<Arc<Cms>>, u8);
impl Drop for Restore {
fn drop(&mut self) {
SCOPED.with(|s| *s.borrow_mut() = self.0.take());
SCOPED_FLAGS.with(|c| c.set(self.1));
}
}
let flags = SCOPED_SET | if cms.rgb_is_srgb() { SCOPED_SRGB } else { 0 } | if matches!(cms.cmyk, CmykSpace::Device) { SCOPED_DEVICE } else { 0 };
let before = SCOPED.with(|s| s.borrow_mut().replace(cms));
let _restore = Restore(before, SCOPED_FLAGS.with(|c| c.replace(flags)));
f()
}
fn install(cms: Arc<Cms>) {
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
@@ -984,10 +1070,16 @@ fn install(cms: Arc<Cms>) {
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
pub(crate) fn rgb_is_srgb() -> bool {
RGB_IS_SRGB.load(Ordering::Relaxed)
match SCOPED_FLAGS.with(Cell::get) {
f if f & SCOPED_SET != 0 => f & SCOPED_SRGB != 0,
_ => RGB_IS_SRGB.load(Ordering::Relaxed),
}
}
pub(crate) fn cmyk_is_device() -> bool {
CMYK_IS_DEVICE.load(Ordering::Relaxed)
match SCOPED_FLAGS.with(Cell::get) {
f if f & SCOPED_SET != 0 => f & SCOPED_DEVICE != 0,
_ => CMYK_IS_DEVICE.load(Ordering::Relaxed),
}
}
#[cfg(test)]
+39
View File
@@ -403,3 +403,42 @@ fn lab_colours_round_trip_through_the_cms() {
let Color::Gray { k } = c.convert(&Color::lab(50.0, 0.0, 0.0), Model::Gray, ri) else { panic!("Gray") };
assert!((k - 0.53).abs() < 0.01, "{k}");
}
#[test]
fn with_active_puts_settings_in_place_on_this_thread_only() {
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
let (rgb, ink) = (Color::Rgb { r: 0.2, g: 0.6, b: 0.4 }, Color::Cmyk { c: 0.2, m: 0.3, y: 0.4, k: 0.1 });
let before = (rgb.to_rgb(), ink.to_rgb());
let (inside, ink_inside, other_thread, nested) = with_active(p3.clone(), || {
let other = std::thread::spawn(move || rgb.to_rgb()).join().unwrap();
let nested = with_active(Arc::new(cms()), || rgb.to_rgb());
(rgb.to_rgb(), ink.to_rgb(), other, nested)
});
assert_eq!(inside, p3.display_rgb(&rgb), "RGB is drawn through the settings given");
assert_ne!(inside, before.0);
assert_eq!(ink_inside, naive_cmyk_to_rgb([0.2, 0.3, 0.4, 0.1]), "CMYK takes the device formula of the settings given");
assert_eq!(other_thread, before.0, "another thread keeps the active settings");
assert_eq!(nested, before.0, "an inner call puts its own settings in place");
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after");
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| with_active(p3.clone(), || panic!("unwinds"))));
assert!(unwound.is_err());
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
}
#[test]
fn a_document_gets_the_same_context_for_the_same_profiles() {
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
// of calls sees none.
let same = (0..100).any(|_| {
let generation = profiles_generation();
let (a, b) = (for_document(Some(DISPLAY_P3), None), for_document(Some(DISPLAY_P3), None));
profiles_generation() == generation && Arc::ptr_eq(&a, &b)
});
assert!(same, "the same profiles give the same context");
let p3 = for_document(Some(DISPLAY_P3), None);
assert_eq!(p3.settings().rgb, DISPLAY_P3);
assert_eq!(p3.settings().cmyk, working_settings().cmyk, "the working CMYK space stays");
assert_eq!(for_document(None, None).settings(), &working_settings(), "no profiles: the working settings");
let unknown = for_document(Some("no such profile"), Some(SRGB));
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
}
+37 -4
View File
@@ -435,9 +435,10 @@ impl Paint {
}
/// Apply `f` to the colours of this paint that can link to a swatch (a solid colour, each
/// gradient stop) with their link and tint; `f` returns true when it changed them. A colour
/// left without a link gets tint 1. A freeform gradient's points, which it draws from, go
/// through `f` too, as unlinked colours (a link `f` gives them is dropped). Returns whether
/// anything changed.
/// left without a link gets tint 1, and a stop left without one also loses its process plates
/// ([`GradientStop::plates`], which print with a linked spot tint). A freeform gradient's
/// points, which it draws from, go through `f` too, as unlinked colours (a link `f` gives them
/// is dropped). Returns whether anything changed.
pub fn map_links(&mut self, f: &mut dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool) -> bool {
let mut one = |c: &mut Color, link: &mut Option<String>, tint: &mut f32| {
let changed = f(c, link, tint);
@@ -449,7 +450,11 @@ impl Paint {
match self {
Paint::Solid { color, swatch, tint } => one(color, swatch, tint),
Paint::Gradient(g) => {
let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| one(&mut s.color, &mut s.swatch, &mut s.tint) | ch);
let stops = g.gradient.stops.iter_mut().fold(false, |ch, s| {
let changed = one(&mut s.color, &mut s.swatch, &mut s.tint);
let unplated = s.swatch.is_none() && s.plates.take().is_some();
changed | unplated | ch
});
let points =
g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()).fold(false, |ch, p| one(&mut p.color, &mut None, &mut 1.0) | ch);
stops | points
@@ -593,6 +598,34 @@ mod tests {
assert!(g.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.5));
}
#[test]
fn mapping_links_drops_the_process_plates_of_unlinked_stops() {
let mut gradient = Gradient::default();
let ink = Color::cmyk(0.0, 0.4, 0.0, 0.0);
gradient.stops[0].swatch = Some("Ink".into());
(gradient.stops[0].color, gradient.stops[0].tint, gradient.stops[0].plates) = (ink, 0.4, Some([0.3, 0.0, 0.0, 0.0]));
let mut g = Paint::Gradient(Box::new(GradientPaint::new(gradient)));
// Unlinking the stop takes its plates with its tint and keeps the colour it shows.
assert!(g.map_links(&mut |_, l, _| l.take().is_some()));
let Paint::Gradient(gp) = &g else { panic!("a gradient") };
let st = &gp.gradient.stops[0];
assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (ink, None, 1.0, None));
// A linked stop keeps its plates.
let mut linked = Gradient::default();
(linked.stops[0].swatch, linked.stops[0].plates) = (Some("Ink".into()), Some([0.3, 0.0, 0.0, 0.0]));
let mut l = Paint::Gradient(Box::new(GradientPaint::new(linked)));
assert!(!l.map_links(&mut |_, _, _| false));
let Paint::Gradient(lp) = &l else { panic!("a gradient") };
assert_eq!(lp.gradient.stops[0].plates, Some([0.3, 0.0, 0.0, 0.0]));
// An unlinked stop that still has plates loses them, and that counts as a change.
let mut stale = Gradient::default();
stale.stops[1].plates = Some([0.0, 0.0, 0.2, 0.0]);
let mut p = Paint::Gradient(Box::new(GradientPaint::new(stale)));
assert!(p.map_links(&mut |_, _, _| false));
let Paint::Gradient(pp) = &p else { panic!("a gradient") };
assert!(pp.gradient.stops.iter().all(|s| s.plates.is_none()));
}
#[test]
fn lab_colours_serialize_with_their_tag_and_keep_their_model() {
let c = Color::lab(52.5, 70.0, -30.0);
+4
View File
@@ -8,6 +8,10 @@ description = "VectorCraft document model: artboards, layers, objects, appearanc
[lints]
workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
+190 -26
View File
@@ -45,7 +45,24 @@ fn lerp_f64(x: f64, y: f64, t: f64) -> f64 {
x + (y - x) * t
}
/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`).
/// The process plates between two stops linked to one spot swatch: each of C, M, Y and K in turn,
/// a stop without plates counting as none of each. The ends keep their own plates.
fn lerp_plates(a: Option<[f32; 4]>, b: Option<[f32; 4]>, t: f32) -> Option<[f32; 4]> {
if t <= 0.0 {
return a;
}
if t >= 1.0 {
return b;
}
if a.is_none() && b.is_none() {
return None;
}
let (a, b) = (a.unwrap_or_default(), b.unwrap_or_default());
Some(std::array::from_fn(|i| lerp_f32(a[i], b[i], t)))
}
/// `like` with every stop painting `c`, linked as the solid is (`swatch` at `tint`), with no
/// process plates (a solid has none).
fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> Gradient {
let mut g = like.clone();
for s in &mut g.stops {
@@ -53,16 +70,18 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) ->
s.opacity = 1.0;
s.swatch = swatch.map(str::to_string);
s.tint = tint;
s.plates = None;
}
g
}
/// The swatch and tint `g` paints at `t`: a stop's own link, or the shared swatch of the two stops
/// around `t` at the tint between theirs (unlinked when they differ), as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32) {
/// The swatch, tint and process plates `g` paints at `t`: a stop's own link, or the shared swatch
/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ),
/// as [`Gradient::sample_with`] walks.
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
let stops = &g.stops;
let link = |s: &GradientStop| (s.swatch.clone(), s.tint);
let Some(first) = stops.first() else { return (None, 1.0) };
let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates);
let Some(first) = stops.first() else { return (None, 1.0, None) };
if t <= first.offset {
return link(first);
}
@@ -74,14 +93,14 @@ fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32) {
let m = a.midpoint.clamp(0.01, 0.99);
let v = if u < m { 0.5 * u / m } else { 0.5 + 0.5 * (u - m) / (1.0 - m) };
return match (&a.swatch, &b.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v)),
_ if v <= 0.0 => link(a),
_ if v >= 1.0 => link(b),
_ => (None, 1.0),
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(a.tint, b.tint, v), lerp_plates(a.plates, b.plates, v)),
_ => (None, 1.0, None),
};
}
}
stops.last().map_or((None, 1.0), link)
stops.last().map_or((None, 1.0, None), link)
}
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred).
@@ -91,8 +110,8 @@ fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
.iter()
.map(|&o| {
let (color, opacity) = g.sample_keep_model(o);
let (swatch, tint) = link_at(g, o);
GradientStop { opacity, swatch, tint, ..GradientStop::new(o, color) }
let (swatch, tint, plates) = link_at(g, o);
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
})
.collect();
out
@@ -139,16 +158,18 @@ fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<Gradien
.iter()
.zip(&gb.stops)
.map(|(sa, sb)| {
// Stops on two tints of one swatch stay linked to it, as solids do (#3234).
let (swatch, tint) = match (&sa.swatch, &sb.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t)),
_ => (None, 1.0),
// Stops on two tints of one swatch stay linked to it, as solids do (#3234), and keep
// the process plates printed with it.
let (swatch, tint, plates) = match (&sa.swatch, &sb.swatch) {
(Some(x), Some(y)) if x == y => (Some(x.clone()), lerp_f32(sa.tint, sb.tint, t), lerp_plates(sa.plates, sb.plates, t)),
_ => (None, 1.0, None),
};
GradientStop {
opacity: lerp_f32(sa.opacity, sb.opacity, t),
midpoint: lerp_f32(sa.midpoint, sb.midpoint, t),
swatch,
tint,
plates,
..GradientStop::new(lerp_f32(sa.offset, sb.offset, t), lerp_color(&sa.color, &sb.color, t))
}
})
@@ -606,9 +627,8 @@ fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr
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.
/// A stroke read along its subpath turned as `o` says: its width profile (whose sides swap when
/// reversed), pen pressure, tilt, bearing and rotation. Its arrowheads stay as they are.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
if o.is_identity() {
return;
@@ -648,15 +668,45 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
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, and on a reversed open path
/// its arrowheads swapped.
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);
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() {
/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
/// end.
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
let NodeKind::Path { path, .. } = &n.kind else { return };
let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
let mut o = Orient::of(sp);
if reversed.get(i).copied().unwrap_or(false) {
if sp.closed {
o.start_at(sp, sp.anchors.len().saturating_sub(1));
}
o.reverse();
}
o
});
let Some(o) = turns.next() else { return };
if o.is_identity() || !turns.all(|t| t.same_turn(&o)) {
return;
}
for it in n.appearance.items.iter_mut() {
@@ -1205,13 +1255,21 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
// Spine
// =====================================================================================
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
thread_local! {
/// How many times [`Spine::new`] has run on this thread, for tests that count how often a path
/// is flattened.
pub(crate) static SPINES_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How many times [`Spine::new`] has run on this thread, for other crates' tests that count how
/// often a path is flattened (the `spine-count` feature, dev-dependencies only).
#[cfg(any(test, feature = "spine-count"))]
#[doc(hidden)]
pub fn spines_built() -> usize {
SPINES_BUILT.with(|n| n.get())
}
/// A spine (the first subpath of a path) flattened to a polyline, with cumulative lengths and the
/// arc length at each of its anchors.
pub struct Spine {
@@ -1230,7 +1288,7 @@ impl Spine {
/// arc lengths, and the arc length at each anchor. `None` when `path` has no subpath, or when
/// the first one flattens to fewer than two points (so it has no length to walk).
pub fn new(path: &PathData) -> Option<Self> {
#[cfg(test)]
#[cfg(any(test, feature = "spine-count"))]
SPINES_BUILT.with(|n| n.set(n.get() + 1));
let sp = path.subpaths.first()?;
let mut pts: Vec<Point> = Vec::new();
@@ -2462,6 +2520,112 @@ mod tests {
assert!(m.gradient.stops.iter().any(|s| s.swatch.is_none()), "{:?}", m.gradient.stops);
}
/// A stop linked to the spot swatch "Spot" at `tint`, printed with process `plates`.
fn spot_stop(offset: f32, tint: f32, plates: Option<[f32; 4]>) -> GradientStop {
let mut stop = GradientStop::new(offset, Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(tint));
stop.swatch = Some("Spot".into());
stop.tint = tint;
stop.plates = plates;
stop
}
fn gradient_paint(stops: Vec<GradientStop>) -> Paint {
Paint::Gradient(Box::new(GradientPaint::new(Gradient { stops, ..Gradient::default() })))
}
fn assert_plates(got: Option<[f32; 4]>, want: [f32; 4]) {
let got = got.unwrap_or_else(|| panic!("plates {want:?}, not none"));
assert!(got.iter().zip(&want).all(|(g, w)| (g - w).abs() < 1e-5), "{got:?} != {want:?}");
}
#[test]
fn blend_gradient_spot_process_plates_interpolate() {
let (p, q) = ([0.2, 0.4, 0.0, 0.0], [0.6, 0.0, 0.8, 1.0]);
let a = gradient_paint(vec![spot_stop(0.0, 0.2, Some(p)), spot_stop(1.0, 0.2, Some(p))]);
let b = gradient_paint(vec![spot_stop(0.0, 1.0, Some(q)), spot_stop(1.0, 1.0, Some(q))]);
let Paint::Gradient(m) = lerp_paint(&a, &b, 0.25) else { panic!() };
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
assert_plates(s.plates, [0.3, 0.3, 0.2, 0.25]);
}
// Without plates on either side the steps print the spot ink alone, as before.
let bare = |tint| gradient_paint(vec![spot_stop(0.0, tint, None), spot_stop(1.0, tint, None)]);
let Paint::Gradient(m) = lerp_paint(&bare(0.2), &bare(1.0), 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
}
#[test]
fn resampled_gradient_spot_process_plates_interpolate() {
let (p, q, r) = ([0.0, 0.4, 0.0, 0.0], [0.6, 0.4, 0.3, 0.0], [0.2, 0.2, 0.2, 0.2]);
let mut first = spot_stop(0.0, 0.2, Some(p));
first.midpoint = 0.25;
let two = Gradient { stops: vec![first, spot_stop(1.0, 0.8, Some(q))], ..Gradient::default() };
let three =
Gradient { stops: vec![spot_stop(0.0, 1.0, Some(r)), spot_stop(0.5, 1.0, Some(r)), spot_stop(1.0, 1.0, Some(r))], ..Gradient::default() };
let Some((ra, rb)) = common_stops(&two, &three) else { panic!() };
let offsets: Vec<f32> = ra.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.25, 0.5, 1.0]);
// The original stops keep their plates; between them, the midpoint at 0.25 puts 0.5 two
// thirds of the way along the inks.
assert_eq!((ra.stops[0].plates, ra.stops[3].plates), (Some(p), Some(q)));
assert_plates(ra.stops[1].plates, [0.3, 0.4, 0.15, 0.0]);
assert_plates(ra.stops[2].plates, [0.4, 0.4, 0.2, 0.0]);
assert!((ra.stops[2].tint - 0.6).abs() < 1e-5, "{}", ra.stops[2].tint);
assert!(rb.stops.iter().all(|s| s.plates == Some(r)), "{:?}", rb.stops);
let Paint::Gradient(m) = lerp_paint(&gradient_paint(two.stops), &gradient_paint(three.stops), 0.5) else { panic!() };
assert_eq!(m.gradient.stops.len(), 4);
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
assert_plates(m.gradient.stops[2].plates, [0.3, 0.3, 0.2, 0.1]);
}
#[test]
fn blend_gradient_missing_plates_mean_zero() {
let p = [0.4, 0.8, 0.0, 0.2];
let with = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let without = gradient_paint(vec![spot_stop(0.0, 1.0, None), spot_stop(1.0, 1.0, None)]);
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.25) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.as_deref() == Some("Spot")), "{:?}", m.gradient.stops);
m.gradient.stops.iter().for_each(|s| assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]));
// The ends keep their own plates.
let Paint::Gradient(m) = lerp_paint(&without, &with, 0.0) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.plates.is_none()), "{:?}", m.gradient.stops);
// Another swatch, or an unlinked stop: process steps with no plates, as before.
let mut other = spot_stop(0.0, 1.0, Some(p));
other.swatch = Some("Other".into());
let other = gradient_paint(vec![other.clone(), GradientStop { offset: 1.0, ..other }]);
let mut plain = spot_stop(0.0, 1.0, None);
plain.swatch = None;
let plain = gradient_paint(vec![plain.clone(), GradientStop { offset: 1.0, ..plain }]);
for b in [&other, &plain] {
let Paint::Gradient(m) = lerp_paint(&with, b, 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
}
#[test]
fn blend_solid_to_spot_gradient_does_not_copy_plates() {
let p = [0.4, 0.8, 0.0, 0.2];
let gradient = gradient_paint(vec![spot_stop(0.0, 1.0, Some(p)), spot_stop(1.0, 1.0, Some(p))]);
let Paint::Gradient(g) = &gradient else { panic!() };
assert!(solid_gradient(Color::BLACK, Some("Spot"), 0.2, &g.gradient).stops.iter().all(|s| s.plates.is_none()));
let solid = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4).tinted(0.2), swatch: Some("Spot".into()), tint: 0.2 };
// The solid's end has no plates: they grow from none toward the gradient's, both ways round.
for (a, b, t) in [(&solid, &gradient, 0.25), (&gradient, &solid, 0.75)] {
let Paint::Gradient(m) = lerp_paint(a, b, t) else { panic!() };
for s in &m.gradient.stops {
assert_eq!(s.swatch.as_deref(), Some("Spot"));
assert!((s.tint - 0.4).abs() < 1e-6, "{}", s.tint);
assert_plates(s.plates, [0.1, 0.2, 0.0, 0.05]);
}
}
// A process solid unlinks the steps, and they take no plates.
let Paint::Gradient(m) = lerp_paint(&Paint::solid(Color::BLACK), &gradient, 0.5) else { panic!() };
assert!(m.gradient.stops.iter().all(|s| s.swatch.is_none() && s.plates.is_none()), "{:?}", m.gradient.stops);
}
#[test]
fn gradients_with_different_stop_counts_interpolate() {
let g = |stops: &[(f32, Color)]| {
+15
View File
@@ -386,6 +386,21 @@ impl ImageBlob {
if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }
}
/// The CMYK ICC profile a CMYK image carries: a four-component JPEG's `ICC_PROFILE` APP2
/// segments put together, or a CMYK TIFF's tag 34675. `None` for other images, and for a
/// profile that isn't one of CMYK colors. Reads only the file's headers and tags.
pub fn cmyk_icc_profile(&self) -> Option<Vec<u8>> {
let bytes = self.bytes.as_slice();
if jpeg_components(bytes) == Some(4) {
return cmyk_icc(jpeg_icc(bytes));
}
let (kind, mut d) = tiff(bytes)?;
if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
return None;
}
cmyk_icc(tiff_icc(&mut d))
}
/// The ink amounts around pixel (`x`, `y`) of a CMYK image, in the pixel space of an image
/// object of `object` (width, height) pixels: the average of the `size` × `size` pixels centered
/// on it, clipped to the image, as C, M, Y and K bytes. `None` outside the image and for images
+58
View File
@@ -251,6 +251,45 @@ fn undrawable(heights: &Heights, used: Def, depth: usize) -> bool {
heights.get(&used).is_some_and(|h| h.is_none_or(|h| depth + h > MAX_DRAWN_DEPTH))
}
/// How deep the art of a document's symbols and patterns draws, to measure objects that use them
/// outside the document's layers ([`Self::deepest`]).
#[derive(Clone, Debug, Default)]
pub struct DrawnHeights {
symbols: HashMap<String, usize>,
patterns: HashMap<String, usize>,
}
impl DrawnHeights {
/// The heights of `doc`'s symbols and patterns, as [`Document::too_deep`] counts them: the art
/// is 1 deep, and what it uses is counted under it. A symbol or pattern that uses itself, or
/// draws deeper than [`MAX_DRAWN_DEPTH`], has none.
pub fn of(doc: &Document) -> Self {
let mut out = Self::default();
for ((pattern, name), h) in heights(doc) {
if let Some(h) = h {
let map = if pattern { &mut out.patterns } else { &mut out.symbols };
map.insert(name.to_string(), h);
}
}
out
}
/// The deepest `n`, placed `depth` deep, draws: its own objects and the art of their opacity
/// masks, and under the objects the art of the symbols and patterns they use. A use of a
/// symbol or pattern without a height ([`Self::of`]) counts as the object alone. `n`'s own
/// nesting may pass [`MAX_DEPTH`]. Without recursion.
pub fn deepest(&self, n: &Node, depth: usize) -> usize {
let mut out = depth;
let mut stack = vec![(n, depth)];
while let Some((n, d)) = stack.pop() {
let used = uses(n).filter_map(|(pattern, name)| if pattern { self.patterns.get(name) } else { self.symbols.get(name) }).max();
out = out.max(d + used.copied().unwrap_or(0));
stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| (&**c, d + 1)));
}
out
}
}
/// Take out of `nodes` (each `depth` deep) the uses `bad` picks (given the depth of the object):
/// an instance goes, a pattern paint becomes no paint. Returns whether anything changed. For trees
/// within [`MAX_DEPTH`].
@@ -623,4 +662,23 @@ mod tests {
d.patterns.push(crate::PatternDef::new("q", vec![painted(3, "none")]));
assert!(!d.too_deep(None) && !d.limit_depth());
}
#[test]
fn drawn_heights_measure_objects_outside_the_layers() {
// s0 holds s1 two groups deep, which holds s2, which holds an instance of nothing known:
// s2 draws 3 deep, s1 6 and s0 9.
let d = symbols(3, 2, "none");
let heights = DrawnHeights::of(&d);
let on_layer = instance(1, "s0");
assert_eq!(heights.deepest(&on_layer, 2), 2 + 9);
// An object's own nesting and its mask's art count past MAX_DEPTH.
let mut deep = Node::group(NodeId(5), vec![nested(MAX_DEPTH + 10)]);
deep.extras_mut().mask = Some(Box::new(OpacityMask::new((*instance(6, "s2")).clone(), true)));
assert_eq!(heights.deepest(&deep, 1), 1 + 1 + MAX_DEPTH + 10);
let shallow = Node::group(NodeId(5), vec![instance(7, "s1")]);
assert_eq!(heights.deepest(&shallow, 100), 101 + 6);
// A symbol that holds itself has no height, so its instance counts alone.
let looped = DrawnHeights::of(&symbols(2, 1, "s0"));
assert_eq!(looped.deepest(&instance(1, "s0"), 2), 2);
}
}
+4
View File
@@ -815,6 +815,10 @@ impl Dimension {
if self.line_between_points() && !old.line_between_points() {
self.keep_gap(&old);
}
} else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 {
// A reflection turns the left normal of a → b to the other side, so an aligned
// dimension's line stays on the reflected side of its points.
self.offset = -self.offset;
}
if self.mode == DimensionMode::Linear {
self.length = self.measured();
+2
View File
@@ -79,6 +79,7 @@ impl Document {
index: _,
guide_cache: _,
inline_cycles: _,
mounted_art: _,
} = self;
*version == other.version
&& *title == other.title
@@ -264,6 +265,7 @@ impl Document {
index: Default::default(),
guide_cache: Default::default(),
inline_cycles: Default::default(),
mounted_art: vec![],
};
let id = d.alloc_id();
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
+4 -2
View File
@@ -128,8 +128,8 @@ impl Document {
}
/// The roots of every tree of the document's art: the layers, symbol definitions, graph designs,
/// pattern swatches and the original of the pattern being edited. Opacity masks hang off nodes
/// in these trees.
/// pattern swatches, the original of the pattern being edited and [`Self::mounted_art`].
/// Opacity masks hang off nodes in these trees.
pub fn art_roots(&self) -> impl Iterator<Item = &Arc<Node>> {
self.layers
.iter()
@@ -137,6 +137,7 @@ impl Document {
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()))
.chain(self.mounted_art.iter().map(|(n, _)| n))
}
/// [`Self::art_roots`], to change.
@@ -147,6 +148,7 @@ impl Document {
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n))
}
/// Does `wants` hold for a node anywhere in the document's art ([`Self::art_roots`]) or its
+13 -63
View File
@@ -1,6 +1,7 @@
use super::document_ext::free_id;
use super::guides::Guide;
use super::limits::MAX_NEXT_ID;
use super::node::{held_guides, map_held, strip_held};
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
use std::collections::{BTreeMap, HashSet};
@@ -272,8 +273,8 @@ impl Document {
return;
}
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
drop_picked(l, held);
if let Some(held) = held_guides(l, &Node::is_ruler_guide) {
strip_held(Arc::make_mut(l), held);
}
}
self.saved_guides.extend(guides);
@@ -347,14 +348,14 @@ impl Document {
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
let mut layer = self.remove(id)?;
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let Some(held) = held_guides(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
let mut guides = vec![];
layer.walk(&mut |c| {
if c.is_ruler_guide() {
guides.push(Arc::new(c.clone()));
}
});
drop_picked(&mut layer, held);
strip_held(Arc::make_mut(&mut layer), held);
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
self.children_mut(Some(home))?.extend(guides);
Ok(layer)
@@ -418,8 +419,8 @@ impl Document {
}
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &pick) {
drop_picked(l, held);
if let Some(held) = held_guides(l, &pick) {
strip_held(Arc::make_mut(l), held);
}
}
sel.guides.retain(|id| !gone.contains(id));
@@ -434,8 +435,8 @@ impl Document {
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
for l in &mut self.layers {
if let Some(held) = picked_in_layers(l, &pick) {
edit_picked(l, held, f);
if let Some(held) = held_guides(l, &pick) {
map_held(Arc::make_mut(l), held, f);
}
}
}
@@ -569,57 +570,6 @@ impl Picked {
}
}
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
/// each child of the layers once.
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
if !n.is_layer() {
return None;
}
let children = n
.children()
.into_iter()
.flatten()
.enumerate()
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
.collect();
Picked { children, mask: None }.some()
}
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
/// Only the layers holding one are copied, and only those are visited.
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
let mut held = held.children.into_iter().peekable();
let mut next = 0;
ch.retain_mut(|c| {
let at = next;
next += 1;
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
// A sublayer holds something; a child picked itself has nothing inside.
if inner.is_empty() {
return false;
}
drop_picked(c, inner);
true
});
}
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
/// the layers holding one, and the guides, are copied, and only those layers are visited.
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
for (i, inner) in held.children {
let Some(c) = ch.get_mut(i) else { continue };
if !inner.is_empty() {
edit_picked(c, inner, f);
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
f(*vertical, pos);
}
}
}
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
/// ([`guides_below`]).
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
@@ -872,9 +822,9 @@ mod tests {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
let held = held_guides(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
drop_picked(&mut d.layers[0], held);
strip_held(Arc::make_mut(&mut d.layers[0]), held);
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
@@ -932,10 +882,10 @@ mod tests {
looked.set(looked.get() + 1);
on_artboard_7(n)
};
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
let held = held_guides(&d.layers[0], &pick).unwrap();
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
let mut seen = vec![];
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
map_held(Arc::make_mut(&mut d.layers[0]), held, &mut |vertical, pos: &mut f64| {
seen.push((vertical, *pos));
*pos += 9.0;
});
+24
View File
@@ -150,6 +150,10 @@ pub struct LabelStyles {
pub categories: Option<crate::CharStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<crate::CharStyle>,
/// The fill of [`Self::legend`] was set on the legend labels, so it is drawn on every pie wedge with Legends in
/// Wedges. `false`: a black fill there is the default, and the labels on dark wedges are drawn white.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub legend_fill_set: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub values_para: Option<crate::ParaStyle>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -182,6 +186,18 @@ impl LabelStyles {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Is the kept legend fill the legend labels' own: set on them ([`Self::legend_fill_set`]), or not black (a file
/// saved without the mark)? Otherwise it is the default black, which edits that map the kept paints leave as it is.
pub fn legend_fill_is_own(&self) -> bool {
self.legend.as_ref().is_some_and(|st| self.legend_fill_set || st.fill != vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK))
}
/// Mark a kept legend fill that is the labels' own ([`Self::legend_fill_is_own`]) as set on them, before an edit
/// that maps the kept paints can turn it black.
pub fn mark_own_legend_fill(&mut self) {
self.legend_fill_set = self.legend_fill_is_own();
}
}
/// Graph Type › Position for pie graphs with several pies: the same size (Even), sized by their totals (Ratio), or
@@ -532,6 +548,14 @@ impl GraphSpec {
self.series_kinds.get(s).copied().flatten().filter(|k| k.combines_with(self.kind)).unwrap_or(self.kind)
}
/// Does the graph pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie
/// with Legends in Wedges whose legend labels keep no fill of their own ([`LabelStyles::legend_fill_is_own`])? Only
/// then is a black legend fill it keeps the default, which edits that map the kept paints leave as it is; other
/// graphs draw the kept fill as it is.
pub fn picks_legend_fill(&self) -> bool {
self.kind == GraphKind::Pie && self.legend && self.pie_legend_in_wedges && !self.label_styles.legend_fill_is_own()
}
/// The data with blank cells as `None`, every row as long as the longest (at most [`MAX_GRAPH_CATEGORIES`] rows
/// of [`MAX_GRAPH_SERIES`] cells).
pub fn cells(&self) -> Vec<Vec<Option<f64>>> {
+27 -23
View File
@@ -974,43 +974,45 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
/// The art of a symbol instance with its own appearance changes, in the symbol's coordinates, and
/// how the canvas places each object of it: through the symbol's 9-slice guides when the instance
/// is scaled by them ([`Document::place_symbol_art`]), otherwise by the instance's transform.
struct InstanceArt {
struct InstanceArt<'a> {
art: Node,
map: Option<crate::NineSliceMap>,
xf: vectorcraft_geom::Affine,
/// Quick boxes, which measure the instances in the art as it is placed through the guides.
boxes: SymbolBoxes<'a>,
}
impl InstanceArt {
impl<'a> InstanceArt<'a> {
/// The art of symbol instance `inst`. `None` for anything else, a missing symbol, or art that
/// placing through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of,
/// which [`Document::place_symbol_art`] does not place and the canvas does not draw.
fn of(doc: &Document, inst: &Node) -> Option<Self> {
fn of(doc: &'a Document, inst: &Node) -> Option<Self> {
let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
let art = crate::symbol_overrides::dynamic_art(&sym.art, inst);
let map = doc.symbol_slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed(&art, doc) > crate::MAX_SYMBOL_NODES) {
let boxes = doc.symbol_boxes().quick();
let art = crate::symbol_overrides::dynamic_art(boxes.symbol_art(symbol)?, inst);
let map = boxes.slice_map(symbol, *xf);
if map.as_ref().is_some_and(|m| m.most_placed_with(&art, &boxes) > crate::MAX_SYMBOL_NODES) {
return None;
}
Some(Self { art, map, xf: *xf })
Some(Self { art, map, xf: *xf, boxes })
}
/// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the
/// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell
/// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides
/// object by object.
fn whole(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell(n, doc))
fn whole(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<vectorcraft_geom::Affine> {
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
/// [`Document::place_symbol_art`] refuses it.
fn place(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place(n, doc)),
(Some(m), None) => (m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes)),
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1018,10 +1020,13 @@ impl InstanceArt {
/// Object `n` of the art placed on the canvas without clip groups
/// ([`crate::NineSliceMap::place_unclipped`]), as [`Self::place`] places it and within the
/// same limit ([`Document::place_symbol_art_unclipped`]).
fn place_unclipped(&self, n: &Node, doc: &Document, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
fn place_unclipped(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> Option<Node> {
match (&self.map, whole) {
(_, Some(a)) => Some(moved(n, a)),
(Some(m), None) => (m.most_placed_unclipped(n, doc) <= crate::MAX_SYMBOL_NODES).then(|| m.place_unclipped(n, doc)),
(Some(m), None) => {
let m = m.unclipped();
(m.most_placed_with(n, &self.boxes) <= crate::MAX_SYMBOL_NODES).then(|| m.place_with(n, &self.boxes))
}
(None, None) => Some(moved(n, self.xf)),
}
}
@@ -1046,15 +1051,14 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
struct Find<'a> {
doc: &'a Document,
art: &'a InstanceArt,
art: &'a InstanceArt<'a>,
p: Point,
opt: HitOptions,
symbols: &'a SymbolBoxes<'a>,
}
impl Find<'_> {
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
self.art.place(n, self.doc, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
}
fn skips_guide(&self, n: &Node) -> bool {
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
@@ -1067,11 +1071,11 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
return self.hit(n, whole);
}
let whole = self.art.whole(n, self.doc, whole);
let whole = self.art.whole(n, whole);
if n.clips()
&& let Some(first) = children.first()
{
let Some(clip) = self.art.place_unclipped(first, self.doc, whole) else { return false };
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
if self.opt.clip_outlines
&& first.visible
&& !first.locked
@@ -1103,7 +1107,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
Find { doc, art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
}
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
@@ -1123,11 +1127,11 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
let mut n = &art.art;
for &i in path {
let children = n.children()?;
whole = art.whole(n, doc, whole);
whole = art.whole(n, whole);
if i != 0
&& n.clips()
&& let Some(first) = children.first()
&& let Some(clip) = art.place_unclipped(first, doc, whole)?.geometric_bounds()
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
{
match meet(Some(clip), limit) {
Some(r) => limit = Some(r),
@@ -1136,7 +1140,7 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
}
n = children.get(usize::try_from(i).ok()?)?;
}
outline_within(&art.place(part, doc, whole)?, limit, &mut out);
outline_within(&art.place(part, whole)?, limit, &mut out);
Some(out)
}
+47
View File
@@ -1586,6 +1586,53 @@ fn symbol_art_past_the_object_limit_picks_nothing() {
assert!(symbol_part_outline(&d, n, &[0]).is_some());
}
/// Picking and outlining an object of a 9-slice instance's art, and placing that art, read the
/// symbol list once for each call, however many instances the art holds.
#[test]
fn picking_in_9_slice_art_reads_the_symbol_list_once() {
let mut d = Document::new(400.0, 400.0);
for i in 0..2_000 {
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: format!("Dot {i}"), art: Arc::new(dot) });
}
// A frame, a group of 20 squares in its top left cell, and 20 instances of the dots across
// the guides.
let square = |d: &mut Document, x: f64, y: f64| {
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Appearance::default_art()))
};
let corner: Vec<_> = (0..20).map(|i| square(&mut d, f64::from(i % 5) * 4.0, f64::from(i / 5) * 4.0)).collect();
let dot = |d: &mut Document, i: u32| {
let xf = vectorcraft_geom::Affine::translate((f64::from(i) * 4.5 + 5.0, 48.0)) * vectorcraft_geom::Affine::scale(4.0);
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Dot {i}"), xf }))
};
let across: Vec<_> = (0..20).map(|i| dot(&mut d, i)).collect();
let frame = Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()));
let mut kids = vec![frame, Arc::new(Node::group(d.alloc_id(), corner))];
kids.extend(across);
let root = Node::group(d.alloc_id(), kids);
d.symbols.push(crate::Symbol { dynamic: true, name: "Panel".into(), art: Arc::new(root) });
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let xf = vectorcraft_geom::Affine::scale_non_uniform(2.0, 1.5);
let inst = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Panel".into(), xf });
let art = d.symbols[2_000].art.clone();
let symbols = d.symbols.len();
let read = || crate::symbols::SYMBOLS_READ.with(std::cell::Cell::get);
let reads = |f: &dyn Fn()| {
let before = read();
f();
read() - before
};
// Picking also tests the placed art with boxes of its own, as a click outside symbols does.
let n = reads(&|| assert_eq!(symbol_part_at(&d, &inst, Point::new(2.0, 2.0), HitOptions::default()).map(|p| p[0]), Some(1)));
assert!(n <= 2 * symbols, "picking read {n} symbols");
let n = reads(&|| assert!(symbol_part_outline(&d, &inst, &[2]).is_some()));
assert!(n <= symbols, "outlining read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing read {n} symbols");
let n = reads(&|| assert!(d.place_symbol_art_unclipped("Panel", &art, xf).is_some()));
assert!(n <= symbols, "placing without clips read {n} symbols");
}
/// A clip group that lies in one 9-slice cell is moved by that cell as one piece, everything in it
/// included, so an object in it is picked and outlined there even when placing that object through
/// the guides on its own would pass [`crate::MAX_SYMBOL_NODES`] objects.
+100 -13
View File
@@ -94,25 +94,45 @@ pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent)
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
}
/// Visits one colour: the colour, its swatch link and its tint, all of which it may change.
pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) + 'a;
/// Process plates a colour prints together with its spot tint (C, M, Y, K, 0..1): a gradient
/// stop's [`vectorcraft_color::GradientStop::plates`]; `None` for every other colour.
pub type StopPlates = Option<[f32; 4]>;
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
let mut ink = inks(doc, c, color, link, intent);
if let (Some(p), Some(_)) = (plates, &ink.spot) {
ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
}
ink
}
/// Visits one colour: the colour, its swatch link, its tint and its process plates
/// ([`StopPlates`]), all of which it may change.
pub type ColorVisitor<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32, &mut StopPlates) + 'a;
fn visit_paint(p: &mut Paint, f: &mut ColorVisitor) {
match p {
Paint::Solid { color, swatch, tint } => f(color, swatch, tint),
Paint::Solid { color, swatch, tint } => f(color, swatch, tint, &mut None),
Paint::Gradient(g) => {
for s in &mut g.gradient.stops {
f(&mut s.color, &mut s.swatch, &mut s.tint);
f(&mut s.color, &mut s.swatch, &mut s.tint, &mut s.plates);
}
for p in g.freeform.iter_mut().flat_map(|ff| ff.points.iter_mut()) {
f(&mut p.color, &mut None, &mut 1.0, &mut None);
}
}
_ => {}
}
}
/// Visit every colour of a node tree (fills, strokes, gradient stops, text runs, mesh points, an
/// image's colorize color, the fills and strokes a dynamic symbol instance keeps for objects of its
/// art, not opacity masks) with its swatch link and tint. Mesh points have no link: changes to it
/// are dropped.
/// Visit every colour of a node tree (fills, strokes, gradient stops, a freeform gradient's
/// points, text runs, mesh points, an image's colorize color, the fills and strokes a dynamic
/// symbol instance keeps for objects of its art, not opacity masks) with its swatch link, tint and
/// process plates. Freeform and mesh points have no link or plates: a link or plates `f` gives
/// them are dropped.
pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
for it in &mut n.appearance.items {
match it {
@@ -137,7 +157,7 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
}
NodeKind::Mesh(m) => {
for p in &mut m.points {
f(&mut p.color, &mut None, &mut 1.0);
f(&mut p.color, &mut None, &mut 1.0, &mut None);
}
}
_ => {}
@@ -149,11 +169,16 @@ pub fn visit_node_colors(n: &mut Node, f: &mut ColorVisitor) {
}
}
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, text runs, mesh
/// points, a dynamic symbol instance's own fills and strokes) given its swatch link and tint,
/// keeping the links.
/// Apply `f` to every colour of a node tree (fills, strokes, gradient stops, a freeform
/// gradient's points, text runs, mesh points, a dynamic symbol instance's own fills and strokes)
/// given its swatch link and tint, keeping the links and process plates.
pub fn map_node_colors(n: &mut Node, f: &mut dyn FnMut(&Color, Link) -> Color) {
visit_node_colors(n, &mut |c, swatch, tint| *c = f(c, swatch.as_deref().map(|s| (s, *tint))));
map_node_inks(n, &mut |c, link, _| f(c, link));
}
/// [`map_node_colors`], with each colour's process plates ([`StopPlates`]) passed to `f` too.
pub fn map_node_inks(n: &mut Node, f: &mut dyn FnMut(&Color, Link, StopPlates) -> Color) {
visit_node_colors(n, &mut |c, swatch, tint, plates| *c = f(c, swatch.as_deref().map(|s| (s, *tint)), *plates));
}
/// Apply `f` to every colour in the document's art and symbol definitions.
@@ -170,8 +195,70 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
mod tests {
use super::*;
use crate::{NodeId, SymbolOverride};
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
use vectorcraft_geom::Affine;
/// A document with spot swatch `Gold` and process swatch `Teal`.
fn gold_doc() -> Document {
let mut d = Document::new(100.0, 100.0);
d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
d.swatches.push(Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.8, 0.0, 0.3, 0.0)), global: true, spot: false });
d
}
#[test]
fn a_spot_stops_process_plates_print_with_its_tint() {
let d = gold_doc();
let c = vectorcraft_color::cms::active();
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
let ink = |link: Link, plates: StopPlates| stop_inks(&d, &c, &look, link, plates, Intent::RelativeColorimetric);
let mixed = ink(Some(("Gold", 0.5)), Some([0.25, 0.0, 0.4, 0.0]));
assert_eq!(mixed, Inks { cmyk: [0.25, 0.0, 0.4, 0.0], spot: Some(("Gold".into(), 0.5)), registration: false });
assert_eq!((mixed.on_plate("Cyan"), mixed.on_plate("Gold")), (0.25, 0.5));
// Amounts outside 0..1 are clamped; one that is not a number prints no ink.
let odd = ink(Some(("Gold", 1.0)), Some([f32::NAN, 2.0, -1.0, f32::INFINITY]));
assert_eq!(odd.cmyk, [0.0, 1.0, 0.0, 0.0]);
// Without plates the spot ink prints alone, as `inks` separates it.
assert_eq!(ink(Some(("Gold", 0.5)), None), inks(&d, &c, &look, Some(("Gold", 0.5)), Intent::RelativeColorimetric));
// Plates beside no spot ink print nothing of their own: a process swatch, an unknown
// swatch, no link and Registration separate as `inks` does.
for link in [Some(("Teal", 1.0)), Some(("Missing", 1.0)), None, Some((REGISTRATION, 0.5))] {
assert_eq!(ink(link, Some([0.25, 0.0, 0.4, 0.0])), inks(&d, &c, &look, link, Intent::RelativeColorimetric), "{link:?}");
}
}
#[test]
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
(stop.swatch, stop.tint, stop.plates) = (Some("Gold".into()), 0.5, Some([0.25, 0.0, 0.4, 0.0]));
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop, GradientStop::new(1.0, Color::rgb(1.0, 1.0, 1.0))]));
let point = FreeformPoint::new(kurbo::Point::new(10.0, 10.0), Color::rgb(0.0, 1.0, 0.0));
g.freeform = Some(Freeform { points: vec![point], ..Default::default() });
let mut n = Node::path(
NodeId(1),
vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)),
crate::Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0),
);
let mut seen = vec![];
let gray = Color::Gray { k: 0.5 };
map_node_inks(&mut n, &mut |c, link, plates| {
seen.push((*c, link.map(|(s, t)| (s.to_string(), t)), plates));
gray
});
assert_eq!(
seen,
vec![
(Color::cmyk(0.25, 0.1, 0.8, 0.05), Some(("Gold".to_string(), 0.5)), Some([0.25, 0.0, 0.4, 0.0])),
(Color::rgb(1.0, 1.0, 1.0), None, None),
(Color::rgb(0.0, 1.0, 0.0), None, None),
]
);
let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| f.paint.clone()) else { panic!("no gradient fill") };
assert_eq!(g.gradient.stops[0].plates, Some([0.25, 0.0, 0.4, 0.0]), "mapping a colour keeps its plates");
assert!(g.gradient.stops.iter().all(|s| s.color == gray));
assert_eq!(g.freeform.map(|f| f.points[0].color), Some(gray), "the freeform point is mapped too");
}
#[test]
fn a_dynamic_instances_own_fills_and_strokes_are_visited() {
let red = Color::rgb(1.0, 0.0, 0.0);
+177 -36
View File
@@ -8,13 +8,20 @@ use std::sync::{Arc, RwLock, Weak};
use vectorcraft_geom::{Affine, Rect};
use crate::{Document, Node, NodeId, NodeKind, Symbol, TextObject};
use crate::symbols::SymbolNames;
use crate::{Document, Node, NodeId, NodeKind, Symbol, SymbolBoxes, TextObject};
/// The document key under which the app records each symbol's natural size (`{name: [w, h]}`).
pub const SYMBOL_SIZES: &str = "symbolSizes";
/// Half the side of the square symbol art is normalised to.
pub const SYMBOL_HALF: f64 = 10.0;
/// The box symbol art `art` is measured by in [`Document::symbol_art_bounds`]: its visual bounds,
/// or its geometric bounds when it has no visual bounds.
fn art_extent(art: &Node, boxes: &SymbolBoxes) -> Option<Rect> {
art.visual_bounds_with(boxes).or_else(|| art.geometric_bounds_with(boxes))
}
/// Usable art bounds: finite, non-degenerate.
fn usable(r: Option<Rect>) -> Option<Rect> {
r.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) && r.width() >= 0.0 && r.height() > 1e-9)
@@ -35,27 +42,38 @@ impl Document {
}
/// Visual bounds of the art of the symbol named `name` at its natural size (see
/// [`Self::symbol_natural_xf`]), if it exists and has a usable extent.
/// [`Self::symbol_natural_xf`]), if it exists and has a usable extent. The symbol instances in
/// the art are measured by their own symbols' art ([`Node::visual_bounds_with`]), or by the
/// 20 × 20 square where [`crate::SymbolBoxes`] measures them by it.
pub fn symbol_art_bounds(&self, name: &str) -> Option<Rect> {
let s = self.symbols.iter().find(|s| s.name == name)?;
let b = usable(s.art.visual_bounds().or_else(|| s.art.geometric_bounds()))?;
self.symbol_art_bounds_in(name, &self.symbol_boxes())
}
/// [`Self::symbol_art_bounds`], with the symbols found and the instances measured by `boxes`
/// (new boxes of this document).
fn symbol_art_bounds_in(&self, name: &str, boxes: &SymbolBoxes) -> Option<Rect> {
let b = usable(art_extent(boxes.symbol_art(name)?, boxes))?;
usable(Some(self.symbol_natural_xf(name).transform_rect_bbox(b)))
}
/// The art bounds an inline graphic of the symbol named `name` takes: [`Self::symbol_art_bounds`],
/// or `None` (an empty slot) when the symbol's art shows the symbol itself inline, directly or
/// through the inline graphics in other symbols' art, so that its size would depend on itself.
/// through the inline graphics and symbol instances in other symbols' art, so that its size
/// would depend on itself.
pub fn inline_art_bounds(&self, name: &str) -> Option<Rect> {
if self.inline_cycles().contains(name) { None } else { self.symbol_art_bounds(name) }
let (cyclic, names) = self.inline_cycles();
if cyclic.contains(name) { None } else { self.symbol_art_bounds_in(name, &self.symbol_boxes().with_names(&names)) }
}
/// The names of the symbols that reach themselves through the inline graphics in symbol art,
/// found once while the symbols stay as they are.
fn inline_cycles(&self) -> Arc<HashSet<String>> {
/// The names of the symbols that reach themselves through the inline graphics in symbol art
/// ([`InlineGraph`]), with each symbol name → the index of the first symbol of that name, found
/// once while the symbols stay as they are.
fn inline_cycles(&self) -> (Arc<HashSet<String>>, Arc<SymbolNames>) {
if let Some(found) = self.inline_cycles.get(&self.symbols) {
return found;
}
let found = Arc::new(InlineGraph::of(self).cyclic);
let graph = InlineGraph::of(self);
let found = (Arc::new(graph.cyclic), graph.names);
self.inline_cycles.set(&self.symbols, &found);
found
}
@@ -94,7 +112,8 @@ impl Document {
/// of symbols, graph designs and pattern tiles, and the opacity masks and live objects in
/// them. Each text whose inline graphics changed has its cached layout cleared and is passed
/// to `layout` to be laid out again. The symbols are resolved first, each after the symbols its
/// inline graphics show, so a symbol's art is measured with its type already laid out; a
/// inline graphics and symbol instances show, so a symbol's art is measured with its type, and
/// the type in the art of the symbols its instances show, already laid out; a
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
@@ -241,34 +260,48 @@ fn inline_symbols(n: &Node) -> Vec<String> {
out
}
/// Each symbol name of `d` → the index of the first symbol of that name (the one a name finds).
fn symbol_index(d: &Document) -> HashMap<&str, usize> {
let mut index = HashMap::with_capacity(d.symbols.len());
for (i, s) in d.symbols.iter().enumerate() {
index.entry(s.name.as_str()).or_insert(i);
}
index
}
/// The symbols of a document as their inline graphics depend on each other.
/// The symbols of a document as their sizes depend on each other: a symbol's art depends on the
/// symbols its type shows inline, and on the symbols its instances show when those instances are
/// measured by their symbols' art ([`crate::SymbolBoxes`]).
struct InlineGraph {
/// Every symbol index, each after the symbols its art shows inline (except along a cycle).
/// Every symbol index, each after the symbols its art depends on (except along a cycle).
order: Vec<usize>,
/// The names of the symbols that reach themselves through inline graphics.
/// The names of the symbols that reach themselves through inline graphics. Instances alone make
/// no cycle: an instance of a symbol that holds an instance of itself is measured by the
/// 20 × 20 square, so every cycle passes through an inline graphic.
cyclic: HashSet<String>,
/// Each symbol name → the index of the first symbol of that name, which stay the same while
/// [`Document::resolve_inline_art_with`] changes the symbols' art.
names: Arc<SymbolNames>,
}
impl InlineGraph {
/// The graph of `d`'s symbols: each symbol's art is walked once, and the order and cycles are
/// found in time linear in the symbols and their inline references (Tarjan's strongly
/// connected components, without recursion).
/// The graph of `d`'s symbols: each symbol's art is walked once, and, when the art of any
/// symbol holds an inline graphic, measured once with the art boxes of the symbols its
/// instances show measured once in all ([`SymbolBoxes::consulted`]: an instance that does not
/// size the art, such as one a clipping path hides, adds nothing). The order and cycles are
/// found in time linear in the symbols and their inline references and instances (Tarjan's
/// strongly connected components, without recursion).
fn of(d: &Document) -> Self {
let index = symbol_index(d);
let names = Arc::new(d.symbol_names());
let boxes = d.symbol_boxes().quick().with_names(&names);
let inline: Vec<Vec<String>> = d.symbols.iter().map(|s| inline_symbols(&s.art)).collect();
// Without inline graphics in symbol art, no symbol's type depends on another symbol.
let any_inline = inline.iter().any(|v| !v.is_empty());
let edges: Vec<Vec<usize>> = d
.symbols
.iter()
.map(|s| {
let mut e: Vec<usize> = inline_symbols(&s.art).iter().filter_map(|n| index.get(n.as_str()).copied()).collect();
.zip(inline)
.map(|(s, inline)| {
let measured = if any_inline {
boxes.consulted(|| {
art_extent(&s.art, &boxes);
})
} else {
HashSet::new()
};
let shows = inline.into_iter().chain(measured);
let mut e: Vec<usize> = shows.filter_map(|n| names.get(n.as_str()).copied()).collect();
e.sort_unstable();
e.dedup();
e
@@ -276,12 +309,13 @@ impl InlineGraph {
.collect();
let (order, cyclic) = components(&edges);
let cyclic = order.iter().filter(|&&i| cyclic[i]).map(|&i| d.symbols[i].name.clone()).collect();
Self { order, cyclic }
Self { order, cyclic, names }
}
/// [`Document::inline_art_bounds`] with the cycles found in this graph.
/// [`Document::inline_art_bounds`] with the cycles found in this graph, for `d` with the
/// symbols' names and order the graph was made with.
fn bounds(&self, d: &Document, name: &str) -> Option<Rect> {
if self.cyclic.contains(name) { None } else { d.symbol_art_bounds(name) }
if self.cyclic.contains(name) { None } else { d.symbol_art_bounds_in(name, &d.symbol_boxes().with_names(&self.names)) }
}
}
@@ -354,12 +388,16 @@ fn components(edges: &[Vec<usize>]) -> (Vec<usize>, Vec<bool>) {
#[derive(Default)]
pub(crate) struct InlineCycles(RwLock<Option<Arc<Found>>>);
/// The name and art of each symbol the cycles were found in, and the names of the symbols on one.
type Found = (Vec<(String, Weak<Node>)>, Arc<HashSet<String>>);
/// The names of the symbols on a cycle, and each symbol name → the index of the first symbol of that
/// name.
type Cycles = (Arc<HashSet<String>>, Arc<SymbolNames>);
/// The name and art of each symbol the cycles were found in, and what was found.
type Found = (Vec<(String, Weak<Node>)>, Cycles);
impl InlineCycles {
/// The cached names, when they were found in `symbols`.
fn get(&self, symbols: &[Symbol]) -> Option<Arc<HashSet<String>>> {
fn get(&self, symbols: &[Symbol]) -> Option<Cycles> {
let g = self.0.read().ok()?;
let (from, found) = &**g.as_ref()?;
let same = from.len() == symbols.len()
@@ -368,7 +406,7 @@ impl InlineCycles {
}
/// Keep `found`, found in `symbols`.
fn set(&self, symbols: &[Symbol], found: &Arc<HashSet<String>>) {
fn set(&self, symbols: &[Symbol], found: &Cycles) {
if let Ok(mut g) = self.0.write() {
*g = Some(Arc::new((symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), found.clone())));
}
@@ -485,6 +523,109 @@ mod tests {
assert_eq!(count.get(), 2);
}
/// A rectangle `r` filled black, with a 2 pt black stroke.
fn stroked(d: &mut Document, r: Rect) -> Arc<Node> {
use vectorcraft_color::{Color, Paint};
let look = crate::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
}
fn instance(d: &mut Document, symbol: &str, xf: Affine) -> Arc<Node> {
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf }))
}
/// Symbol `name` holding `art` in a group.
fn symbol(d: &mut Document, name: &str, art: Vec<Arc<Node>>) {
let group = Node::group(d.alloc_id(), art);
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(group) });
}
#[test]
fn a_symbol_nested_in_symbol_art_is_measured_by_its_own_art() {
// `Far` is a rectangle from (200, 100) to (240, 130) with a 2 pt stroke, far from the
// 20 × 20 square around the origin.
let mut d = Document::new(500.0, 500.0);
let far = stroked(&mut d, Rect::new(200.0, 100.0, 240.0, 130.0));
symbol(&mut d, "Far", vec![far]);
let moved = instance(&mut d, "Far", Affine::translate((-100.0, 0.0)));
symbol(&mut d, "Moved", vec![moved.clone()]);
let scaled = instance(&mut d, "Far", Affine::scale(2.0));
symbol(&mut d, "Scaled", vec![scaled]);
symbol(&mut d, "Sized", vec![moved]);
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "Sized": [40.0, 20.0] }));
assert_eq!(d.symbol_art_bounds("Far"), Some(Rect::new(199.0, 99.0, 241.0, 131.0)));
// The stroke paints 1 pt around the moved rectangle.
assert_eq!(d.symbol_art_bounds("Moved"), Some(Rect::new(99.0, 99.0, 141.0, 131.0)));
// Scaled 2 times, the stroke keeps its weight.
assert_eq!(d.symbol_art_bounds("Scaled"), Some(Rect::new(399.0, 199.0, 481.0, 261.0)));
// At its natural size, 40 × 20 for the 20 × 20 square: 2 times across.
assert_eq!(d.symbol_art_bounds("Sized"), Some(Rect::new(198.0, 99.0, 282.0, 131.0)));
assert_eq!(d.inline_art_bounds("Moved"), d.symbol_art_bounds("Moved"));
}
#[test]
fn nested_instances_without_art_of_their_own_are_measured_by_the_square() {
let mut d = Document::new(500.0, 500.0);
let r = Rect::new(0.0, 0.0, 10.0, 10.0);
// An instance of a missing symbol and one of a symbol with no art, beside a rectangle.
symbol(&mut d, "Empty", vec![]);
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Nowhere", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Missing", pieces);
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Empty", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Holds empty", pieces);
let with_square = Some(Rect::new(-1.0, -10.0, 110.0, 11.0));
assert_eq!(d.symbol_art_bounds("Empty"), None);
assert_eq!(d.symbol_art_bounds("Missing"), with_square);
assert_eq!(d.symbol_art_bounds("Holds empty"), with_square);
// A symbol that holds an instance of itself: the instance is measured by the square, and
// an inline graphic of it is not an empty slot.
let pieces = vec![stroked(&mut d, r), instance(&mut d, "Loop", Affine::translate((100.0, 0.0)))];
symbol(&mut d, "Loop", pieces);
assert_eq!(d.symbol_art_bounds("Loop"), with_square);
assert_eq!(d.inline_art_bounds("Loop"), with_square);
// A chain of 40 symbols, each holding a rectangle and an instance of the next one 1 pt to
// the right: symbols nest 39 deep in Link 0's art, past the limit of 32, so its instance of
// Link 1 is measured by the square.
for i in 0..40 {
let unit = stroked(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0));
let next = instance(&mut d, &format!("Link {}", i + 1), Affine::translate((1.0, 0.0)));
symbol(&mut d, &format!("Link {i}"), if i < 39 { vec![unit, next] } else { vec![unit] });
}
assert_eq!(d.symbol_art_bounds("Link 0"), Some(Rect::new(-9.0, -10.0, 11.0, 10.0)));
// Link 8's art nests 31 deep: measured by the art of the links after it.
assert_eq!(d.symbol_art_bounds("Link 8"), Some(Rect::new(-1.0, -1.0, 33.0, 2.0)));
}
/// Type showing the symbol named `symbol` inline.
fn showing(d: &mut Document, symbol: &str) -> Arc<Node> {
let style = crate::CharStyle::default();
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Type", style.clone());
t.runs.push(crate::TextRun::new("", style));
t.runs[1].inline = Some(crate::InlineArt { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None });
Arc::new(Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))))
}
#[test]
fn only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol() {
// B's type shows A inline. A's art is a clip group: a clipping rectangle, then an instance
// of B that the rectangle clips, so A's size does not depend on B's.
let mut d = Document::new(500.0, 500.0);
let text = showing(&mut d, "A");
symbol(&mut d, "B", vec![text]);
let clip = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
let inner = instance(&mut d, "B", Affine::IDENTITY);
let group = Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children: vec![clip, inner.clone()], clip: true }));
symbol(&mut d, "A", vec![group]);
assert_eq!(d.inline_art_bounds("A"), Some(Rect::new(-1.0, -1.0, 11.0, 11.0)));
// Without the clip, A's size depends on B's and B's on A's: both are empty slots.
let art = Arc::new(Node::group(d.alloc_id(), vec![inner]));
if let Some(a) = d.symbols.iter_mut().find(|s| s.name == "A") {
a.art = art;
}
assert_eq!(d.inline_art_bounds("A"), None);
assert_eq!(d.inline_art_bounds("B"), None);
}
#[test]
fn components_handle_a_long_chain_without_recursion() {
let n = 200_000;
+7
View File
@@ -61,6 +61,7 @@ pub mod range;
pub mod rastersettings;
mod reach;
pub mod recolor;
pub mod resample;
pub mod selection;
pub mod separated;
pub mod setup;
@@ -367,6 +368,12 @@ pub struct Document {
/// saved.
#[serde(skip)]
inline_cycles: inline::InlineCycles,
/// Art kept elsewhere in the document's data (the art of the stored brushes, which
/// `vectorcraft-brush` reads from [`Self::unknown`]) while it is set here, each root with the
/// `owner` the Links panel names for it, so the stored-art lookups ([`StoredRoot::Mounted`])
/// find its objects too. Empty otherwise; never saved.
#[serde(skip)]
pub mounted_art: Vec<(Arc<Node>, serde_json::Value)>,
}
fn ppi72() -> f64 {
+26 -6
View File
@@ -229,7 +229,8 @@ fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
/// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG.
fn proxy_of(img: &image::DynamicImage) -> Option<Vec<u8>> {
let small = img.thumbnail(PROXY_SIZE, PROXY_SIZE);
let (w, h) = crate::resample::fit_size(img.width(), img.height(), PROXY_SIZE, PROXY_SIZE);
let small = crate::resample::averaged(img, w, h);
let mut png = Vec::new();
small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(png)
@@ -248,14 +249,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
impl Document {
/// Visit every image object: in the layers, then in symbol definitions and pattern swatches,
/// opacity-mask art included.
/// then in [`Document::mounted_art`], opacity-mask art included.
pub fn visit_images<'a>(&'a self, mut f: impl FnMut(&'a Node, &'a ImageObject)) {
let roots = self
.layers
.iter()
.chain(self.symbols.iter().map(|s| &s.art))
.chain(self.graph_designs.iter().map(|g| &g.art))
.chain(self.patterns.iter().flat_map(|p| &p.art));
.chain(self.patterns.iter().flat_map(|p| &p.art))
.chain(self.mounted_art.iter().map(|(n, _)| n));
for root in roots {
walk_all(root, &mut |n| {
if let NodeKind::Image(im) = &n.kind {
@@ -384,7 +386,8 @@ impl Align {
impl Document {
/// Rewrite linked file locations in both raster images and placed VectorCraft documents,
/// including those inside symbols, patterns and opacity masks. Used to make packages portable.
/// including those inside symbols, patterns, opacity masks and [`Document::mounted_art`]. Used to
/// make packages portable.
pub fn update_links(&mut self, mut f: impl FnMut(&mut LinkInfo)) {
fn walk(n: &mut Arc<Node>, f: &mut dyn FnMut(&mut LinkInfo)) {
let n = Arc::make_mut(n);
@@ -409,7 +412,8 @@ impl Document {
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n));
for root in roots {
walk(root, &mut f);
}
@@ -471,7 +475,8 @@ impl Document {
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art));
.chain(self.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(self.mounted_art.iter_mut().map(|(n, _)| n));
for root in roots {
update(root, &pick, &mut f);
}
@@ -728,4 +733,19 @@ mod tests {
image(&mut d, "c", None);
assert_eq!(d.linked_only_images().into_iter().collect::<Vec<_>>(), ["a"]);
}
/// The preview of an image with clear pixels keeps the color of its opaque ones: the clear
/// black beside them does not darken them, whichever way the preview is made.
#[test]
fn a_preview_keeps_the_color_beside_clear_pixels() {
let mut full = vec![];
image::RgbaImage::from_fn(1024, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) })
.write_to(&mut Cursor::new(&mut full), image::ImageFormat::Png)
.unwrap();
for blob in [ImageBlob::png(full.clone()).with_proxy(), ImageBlob::png(full.clone()).checked_with_proxy(true).unwrap()] {
let p = image::load_from_memory(blob.proxy.as_ref().unwrap()).unwrap().into_rgba8();
assert_eq!(p.dimensions(), (PROXY_SIZE, 1));
assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0));
}
}
}
+1
View File
@@ -32,6 +32,7 @@ pub use kind::{ImageObject, MAX_BUFFERED_VALUES, NodeKind, with_buffered_value_b
pub use live_shape::{LiveShape, Scaling};
pub use opacity::{Knockout, OpacityMask, whiten};
pub use ops::{flattens, keeps_gradient_fit};
pub(crate) use ops::{held_guides, map_held, strip_held};
use wire::NodeWire;
pub(crate) use wire::counted_list;
pub use wire::{MAX_READ_NODES, with_node_budget};
+4 -4
View File
@@ -823,11 +823,11 @@ impl Node {
/// The ruler guides a layer holds: its children that are one, by index in order (each with
/// nothing inside), and its sublayers holding one (with what they hold).
#[derive(Debug, Default)]
pub(super) struct HeldGuides(Vec<(usize, HeldGuides)>);
pub(crate) struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The ruler guides, by `is_guide`, that `n` holds if it is a layer, or `None` when it holds
/// none. `is_guide` looks at each child of `n` and of its sublayers once.
pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
pub(crate) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<HeldGuides> {
if !n.is_layer() {
return None;
}
@@ -843,7 +843,7 @@ pub(super) fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option
/// Remove the ruler guides of `layer` and of its sublayers that [`held_guides`] found (`held`).
/// Only the sublayers holding one are copied, and only those are visited.
pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
pub(crate) fn strip_held(layer: &mut Node, held: HeldGuides) {
let Some(ch) = layer.children_mut() else { return };
let mut held = held.0.into_iter().peekable();
let mut next = 0;
@@ -863,7 +863,7 @@ pub(super) fn strip_held(layer: &mut Node, held: HeldGuides) {
/// Call `f` (whether it is vertical, its position) on each ruler guide of `layer` and of its
/// sublayers that [`held_guides`] found (`held`), in the order they lie in. Only the sublayers
/// holding one, and the guides, are copied, and only those sublayers are visited.
pub(super) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
pub(crate) fn map_held(layer: &mut Node, held: HeldGuides, f: &mut impl FnMut(bool, &mut f64)) {
let Some(ch) = layer.children_mut() else { return };
for (i, inner) in held.0 {
let Some(c) = ch.get_mut(i) else { continue };
+42 -9
View File
@@ -234,8 +234,14 @@ pub fn is_objects_on_path(n: &Node) -> bool {
/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path
/// (not a guide) whose first subpath has a length ([`path_length`]).
pub fn attachable_path(n: &Node) -> Option<&PathData> {
attachable(n).map(|(path, _)| path)
}
/// [`attachable_path`] with the path measured ([`Measured`]), from the one flattening that checks
/// its length.
pub fn attachable(n: &Node) -> Option<(&PathData, Measured)> {
match &n.kind {
NodeKind::Path { path, guide: false, .. } if path_length(path).is_some() => Some(path),
NodeKind::Path { path, guide: false, .. } => Some((path, Measured::new(path)?)),
_ => None,
}
}
@@ -301,20 +307,51 @@ pub fn path_length(path: &PathData) -> Option<(f64, bool)> {
/// A path's first subpath flattened ([`Spine`]), with its length and whether it is closed, so that
/// one flattening serves both measuring the path and finding points along it.
struct Measured {
pub struct Measured {
spine: Spine,
len: f64,
closed: bool,
}
impl std::fmt::Debug for Measured {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Measured").field("len", &self.len).field("closed", &self.closed).finish_non_exhaustive()
}
}
impl Measured {
/// `None` for a path without length, or with a length too large to be finite.
fn new(path: &PathData) -> Option<Self> {
pub fn new(path: &PathData) -> Option<Self> {
let spine = Spine::new(path)?;
let len = spine.length();
let closed = path.subpaths.first().is_some_and(|s| s.closed);
(len.is_finite() && len > 1e-9).then_some(Self { spine, len, closed })
}
/// The flattened first subpath, to measure along.
pub fn spine(&self) -> &Spine {
&self.spine
}
/// The length of the first subpath (points), as [`path_length`] gives it.
pub fn length(&self) -> f64 {
self.len
}
/// Is the first subpath closed?
pub fn closed(&self) -> bool {
self.closed
}
/// [`stops`] on this path.
pub fn stops(&self, n: usize, spacing: Option<f64>, start: f64) -> Vec<(Point, f64)> {
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
(0..n).map(|i| self.spine.at_length(nth_length(self.len, self.closed, start, gap, i))).collect()
}
/// [`stop`] on this path: `None` for an `i` of `n` or more.
pub fn stop(&self, n: usize, spacing: Option<f64>, start: f64, i: usize) -> Option<(Point, f64)> {
if i >= n {
return None;
}
let (start, gap) = layout(self.len, self.closed, n, spacing, start);
Some(self.spine.at_length(nth_length(self.len, self.closed, start, gap, i)))
}
}
/// Where the first of `n` objects attaches along a path of length `len` (closed or not), and the
@@ -359,9 +396,7 @@ fn wrap(s: f64, len: f64) -> f64 {
/// (radians, as `atan2` gives in the document's axes). They go along it as [`layout`] spaces them
/// for Space `spacing` (`None`: Auto) from `start`. `None` for a path without length.
pub fn stops(path: &PathData, n: usize, spacing: Option<f64>, start: f64) -> Option<Vec<(Point, f64)>> {
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some((0..n).map(|i| spine.at_length(nth_length(len, closed, start, gap, i))).collect())
Some(Measured::new(path)?.stops(n, spacing, start))
}
/// Where object `i` of `n` attaches along `path`, as [`stops`] places it, without the others.
@@ -370,9 +405,7 @@ pub fn stop(path: &PathData, n: usize, spacing: Option<f64>, start: f64, i: usiz
if i >= n {
return None;
}
let Measured { spine, len, closed } = Measured::new(path)?;
let (start, gap) = layout(len, closed, n, spacing, start);
Some(spine.at_length(nth_length(len, closed, start, gap, i)))
Measured::new(path)?.stop(n, spacing, start, i)
}
/// The distance along a path of length `len` (closed or not) to object `i`, from `start` and
+4 -1
View File
@@ -166,13 +166,15 @@ fn walk_all<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
}
}
/// The roots of `d`'s art: layers, symbol definitions and pattern swatches.
/// The roots of `d`'s art: layers, symbol definitions, pattern swatches and
/// [`Document::mounted_art`].
fn roots(d: &Document) -> impl Iterator<Item = &Arc<Node>> {
d.layers
.iter()
.chain(d.symbols.iter().map(|s| &s.art))
.chain(d.graph_designs.iter().map(|g| &g.art))
.chain(d.patterns.iter().flat_map(|p| &p.art))
.chain(d.mounted_art.iter().map(|(n, _)| n))
}
fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
@@ -181,6 +183,7 @@ fn roots_mut(d: &mut Document) -> impl Iterator<Item = &mut Arc<Node>> {
.chain(d.symbols.iter_mut().map(|s| &mut s.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(d.patterns.iter_mut().flat_map(|p| &mut p.art))
.chain(d.mounted_art.iter_mut().map(|(n, _)| n))
}
impl Document {
+259
View File
@@ -0,0 +1,259 @@
//! Scaling images whose pixels carry straight (not premultiplied) alpha.
//!
//! `image`'s filtered resampling filters each channel on its own, which is correct only for
//! premultiplied pixels, and its thumbnail averages each channel on its own too, so on
//! straight-alpha pixels the color under clear pixels bleeds into the opaque ones next to them
//! (clear black darkens a cut-out's edge). [`resized`], [`fitted`] and [`averaged`] weight each
//! pixel's color by its alpha while scaling, as the streaming shrink in the renderer does.
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
/// How [`resized`] makes each new pixel from the old ones.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Resample {
/// `image`'s filtered resampling with this filter.
Filter(FilterType),
/// The mean of the old pixels each new one covers ([`averaged`]).
Average,
}
/// `img` scaled to `w` × `h` pixels as `how` says, each pixel's color weighted by its alpha.
/// Filtered or averaged, an image with clear or partly clear pixels comes back as 8-bit RGBA
/// whatever its own pixel format, and a pixel that ends up wholly clear is transparent black. An
/// image without clear pixels is scaled as `image` scales it, in its own pixel format.
/// Nearest-neighbor picking leaves the pixels as they are, in their own format, and is not
/// weighted. Filtered, the colors keep the precision of premultiplied 8-bit pixels, and an 8-bit
/// RGBA image is premultiplied in place.
pub fn resized(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
if (w, h) == (img.width(), img.height()) {
return img;
}
let f = match how {
Resample::Average => return averaged(&img, w, h),
Resample::Filter(f) => f,
};
if f == FilterType::Nearest || opaque(&img) {
return img.resize_exact(w, h, f);
}
let mut rgba = img.into_rgba8();
for p in rgba.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = times_alpha(*c, *a);
}
}
let mut out = image::imageops::resize(&rgba, w, h, f);
for p in out.pixels_mut() {
let [r, g, b, a] = &mut p.0;
for c in [r, g, b] {
*c = over_alpha(*c, *a);
}
}
DynamicImage::ImageRgba8(out)
}
/// [`resized`] to the largest size that fits `w` × `h` pixels and keeps `img`'s proportions, the
/// size `image`'s own `resize` and `thumbnail` pick.
pub fn fitted(img: DynamicImage, w: u32, h: u32, how: Resample) -> DynamicImage {
let (nw, nh) = fit_size(img.width(), img.height(), w, h);
resized(img, nw, nh, how)
}
/// `img` scaled to `w` × `h` pixels, each new pixel the mean of the old pixels it covers, each old
/// pixel counted by the area of it covered and its color weighted by its alpha. `img` is read one
/// row at a time, so besides the result this takes one row of 8-bit RGBA at most. An image
/// without clear pixels is scaled as `image`'s thumbnail scales it.
pub fn averaged(img: &DynamicImage, w: u32, h: u32) -> DynamicImage {
let (sw, sh) = (img.width(), img.height());
if opaque(img) || w == 0 || h == 0 || sw == 0 || sh == 0 {
return img.thumbnail_exact(w, h);
}
// Per new pixel of the row being made: red, green and blue times alpha, alpha (all times the
// area covered), and the area covered.
let mut sums = vec![([0f64; 4], 0f64); w as usize];
let mut out = Vec::with_capacity(w as usize * h as usize * 4);
for ty in 0..h {
for (y, wy) in covered(ty, sh, h) {
let row = rgba_row(img, y as u32);
for ((s, area), tx) in sums.iter_mut().zip(0..w) {
for (x, wx) in covered(tx, sw, w) {
let Some(p) = row.get(x * 4..x * 4 + 4) else { continue };
let k = wx * wy;
let a = f64::from(p[3]) * k;
s[0] += f64::from(p[0]) * a;
s[1] += f64::from(p[1]) * a;
s[2] += f64::from(p[2]) * a;
s[3] += a;
*area += k;
}
}
}
let byte = |v: f64| v.round().clamp(0.0, 255.0) as u8;
for (s, area) in &mut sums {
out.extend(if s[3] <= 0.0 { [0; 4] } else { [byte(s[0] / s[3]), byte(s[1] / s[3]), byte(s[2] / s[3]), byte(s[3] / *area)] });
(*s, *area) = ([0.0; 4], 0.0);
}
}
RgbaImage::from_raw(w, h, out).map_or_else(|| img.thumbnail_exact(w, h), DynamicImage::ImageRgba8)
}
/// Row `y` of `img` as 8-bit RGBA: borrowed from an 8-bit RGBA image, converted from others.
fn rgba_row(img: &DynamicImage, y: u32) -> std::borrow::Cow<'_, [u8]> {
let n = img.width() as usize * 4;
match img {
DynamicImage::ImageRgba8(b) => std::borrow::Cow::Borrowed(b.as_raw().get(y as usize * n..(y as usize + 1) * n).unwrap_or_default()),
other => std::borrow::Cow::Owned(other.crop_imm(0, y, other.width(), 1).into_rgba8().into_raw()),
}
}
/// The old pixels that new pixel `t` of `tn` covers along a side of `n` old pixels, each with the
/// length of it covered (in old pixels), worked out as they are read so that nothing is stored.
fn covered(t: u32, n: u32, tn: u32) -> impl Iterator<Item = (usize, f64)> {
let scale = f64::from(n) / f64::from(tn);
let (a, b) = (f64::from(t) * scale, (f64::from(t) + 1.0) * scale);
let (first, end) = (a.floor() as u32, (b.ceil() as u32).min(n));
(first..end.max(first + 1).min(n)).filter_map(move |i| {
let len = b.min(f64::from(i) + 1.0) - a.max(f64::from(i));
(len > 0.0).then_some((i as usize, len))
})
}
/// Each 4-channel pixel of `px` with all four channels multiplied by its value in `alpha` (one
/// sample a pixel, 0 to 255): ink amounts or colors made ready for scaling beside a separate alpha
/// channel. Pixels past the end of `alpha` are left as they are.
pub fn premultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = times_alpha(*c, a);
}
}
}
/// [`premultiply`] undone after scaling: each 4-channel pixel of `px` divided by its value in the
/// scaled `alpha`, and 0 where that is 0.
pub fn unpremultiply(px: &mut [u8], alpha: &[u8]) {
for (p, &a) in px.as_chunks_mut::<4>().0.iter_mut().zip(alpha) {
for c in p {
*c = over_alpha(*c, a);
}
}
}
/// Does `img` have no alpha channel, or is every pixel of it opaque?
fn opaque(img: &DynamicImage) -> bool {
match img {
DynamicImage::ImageRgba8(b) => b.pixels().all(|p| p[3] == u8::MAX),
DynamicImage::ImageLumaA8(b) => b.pixels().all(|p| p[1] == u8::MAX),
DynamicImage::ImageRgba16(b) => b.pixels().all(|p| p[3] == u16::MAX),
DynamicImage::ImageLumaA16(b) => b.pixels().all(|p| p[1] == u16::MAX),
DynamicImage::ImageRgba32F(b) => b.pixels().all(|p| p[3] >= 1.0),
other => !other.color().has_alpha(),
}
}
/// Channel `c` times alpha `a`, both 0 to 255.
fn times_alpha(c: u8, a: u8) -> u8 {
((u16::from(c) * u16::from(a) + 127) / 255) as u8
}
/// Premultiplied channel `c` divided by alpha `a` (0 when `a` is 0).
fn over_alpha(c: u8, a: u8) -> u8 {
if a == 0 {
return 0;
}
let a = u32::from(a);
((u32::from(c) * 255 + a / 2) / a).min(255) as u8
}
/// The largest size of at most `nw` × `nh` with the proportions of `w` × `h`, at least a pixel a
/// side.
pub fn fit_size(w: u32, h: u32, nw: u32, nh: u32) -> (u32, u32) {
if w == 0 || h == 0 {
return (nw.max(1), nh.max(1));
}
let ratio = (f64::from(nw) / f64::from(w)).min(f64::from(nh) / f64::from(h));
let side = |n: u32| ((f64::from(n) * ratio).round() as u32).max(1);
(side(w), side(h))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 4 × 2 image whose left half is opaque red and whose right half is clear black.
fn half_clear() -> DynamicImage {
DynamicImage::ImageRgba8(RgbaImage::from_fn(4, 2, |x, _| if x < 2 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) }))
}
/// Is the color of `p`, premultiplied by its alpha, within a step of `rgb` premultiplied by the
/// same alpha (the precision of premultiplied 8-bit pixels)?
fn close(p: [u8; 4], rgb: [u8; 3]) -> bool {
p[..3].iter().zip(rgb).all(|(&c, want)| times_alpha(c, p[3]).abs_diff(times_alpha(want, p[3])) <= 1)
}
#[test]
fn averaging_keeps_the_color_of_the_opaque_pixels() {
let p = resized(half_clear(), 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0;
assert!(close(p, [200, 30, 30]) && p[3].abs_diff(128) <= 1, "{p:?}");
}
/// Three pixels averaged into two: each new pixel takes one old pixel whole and half of the
/// clear one in the middle.
#[test]
fn averaging_counts_the_part_of_a_pixel_covered() {
let img = RgbaImage::from_fn(3, 1, |x, _| if x == 1 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([200, 30, 30, 255]) });
let out = averaged(&DynamicImage::ImageRgba8(img), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 30, 30, 170], [200, 30, 30, 170]].concat());
// Gray with alpha is read the same way.
let gray = image::GrayAlphaImage::from_fn(3, 1, |x, _| image::LumaA(if x == 1 { [0, 0] } else { [200, 255] }));
let out = averaged(&DynamicImage::ImageLumaA8(gray), 2, 1).into_rgba8();
assert_eq!(out.into_raw(), [[200, 200, 200, 170], [200, 200, 200, 170]].concat());
}
#[test]
fn filtering_keeps_the_color_of_the_opaque_pixels() {
for f in [FilterType::Triangle, FilterType::CatmullRom, FilterType::Lanczos3] {
let out = resized(half_clear(), 2, 1, Resample::Filter(f)).into_rgba8();
for x in 0..2 {
let p = out.get_pixel(x, 0).0;
assert!(p[3] == 0 || close(p, [200, 30, 30]), "{f:?} pixel {x}: {p:?}");
}
}
}
#[test]
fn fitted_keeps_proportions() {
let img = DynamicImage::ImageRgba8(RgbaImage::new(400, 100));
let out = fitted(img, 64, 64, Resample::Average);
assert_eq!((out.width(), out.height()), (64, 16));
}
#[test]
fn opaque_and_alpha_free_images_scale_as_image_scales_them() {
let rgb = DynamicImage::ImageRgb8(image::RgbImage::from_fn(5, 3, |x, y| image::Rgb([x as u8 * 40, y as u8 * 60, 7])));
let ours = resized(rgb.clone(), 2, 2, Resample::Filter(FilterType::Triangle));
assert_eq!(ours, rgb.resize_exact(2, 2, FilterType::Triangle));
let opaque = DynamicImage::ImageRgba8(rgb.to_rgba8());
assert_eq!(resized(opaque.clone(), 2, 2, Resample::Average), opaque.thumbnail_exact(2, 2));
}
#[test]
fn a_wholly_clear_result_is_transparent_black() {
let img = DynamicImage::ImageRgba8(RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 0])));
assert_eq!(resized(img, 1, 1, Resample::Average).into_rgba8().get_pixel(0, 0).0, [0, 0, 0, 0]);
}
#[test]
fn premultiply_and_unpremultiply_scale_beside_a_separate_alpha() {
// Two pixels of inks, the second clear: averaged, the first one's inks remain.
let mut px = vec![40, 80, 120, 160, 0, 0, 0, 0];
premultiply(&mut px, &[255, 0]);
let img = RgbaImage::from_raw(2, 1, px).unwrap();
let mut out = image::imageops::thumbnail(&img, 1, 1).into_raw();
let alpha = image::imageops::thumbnail(&image::GrayImage::from_raw(2, 1, vec![255, 0]).unwrap(), 1, 1).into_raw();
unpremultiply(&mut out, &alpha);
let want = [40, 80, 120, 160];
assert!(out.iter().zip(want).all(|(&c, w)| times_alpha(c, alpha[0]).abs_diff(times_alpha(w, alpha[0])) <= 1), "{out:?} {alpha:?}");
}
}
+57 -5
View File
@@ -20,6 +20,8 @@ pub enum StoredRoot {
GraphDesign(usize),
/// Object `art` of pattern swatch `pattern` of [`Document::patterns`].
Pattern { pattern: usize, art: usize },
/// Root `index` of [`Document::mounted_art`].
Mounted(usize),
}
/// Where a stored object is: its root and, inside opacity-mask art, the object that mask belongs
@@ -170,10 +172,12 @@ impl Document {
.iter()
.enumerate()
.flat_map(|(p, def)| def.art.iter().enumerate().map(move |(a, n)| (n, StoredRoot::Pattern { pattern: p, art: a })));
symbols.chain(designs).chain(patterns)
let mounted = self.mounted_art.iter().enumerate().map(|(i, (n, _))| (n, StoredRoot::Mounted(i)));
symbols.chain(designs).chain(patterns).chain(mounted)
}
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns.
/// Every root of stored art: the layers, then the art of symbols, graph designs and patterns,
/// then [`Document::mounted_art`].
fn stored_roots(&self) -> impl Iterator<Item = (&Arc<Node>, StoredRoot)> {
self.layers.iter().enumerate().map(|(i, l)| (l, StoredRoot::Layer(i))).chain(self.definition_roots())
}
@@ -185,12 +189,13 @@ impl Document {
StoredRoot::Symbol(i) => self.symbols.get_mut(i).map(|s| &mut s.art),
StoredRoot::GraphDesign(i) => self.graph_designs.get_mut(i).map(|g| &mut g.art),
StoredRoot::Pattern { pattern, art } => self.patterns.get_mut(pattern)?.art.get_mut(art),
StoredRoot::Mounted(i) => self.mounted_art.get_mut(i).map(|(n, _)| n),
}
}
/// Visit every stored object with its place: the layer tree with the opacity-mask art of its
/// objects, then the art of symbols, graph designs and pattern swatches (their definitions,
/// once each, never the copies instances and tiles draw).
/// once each, never the copies instances and tiles draw), then [`Document::mounted_art`].
pub fn visit_stored<'a>(&'a self, mut f: impl FnMut(&'a Node, StoredPlace)) {
self.visit_stored_arcs(|n, place| f(n, place));
}
@@ -238,6 +243,29 @@ impl Document {
/// visited before them (the layer tree's own objects first) a new id, so every stored object
/// can be named by its id. Returns how many changed; the id counter then stands above them.
pub(crate) fn renumber_stored_duplicates(&mut self) -> usize {
self.renumber_duplicates_in(|_| true)
}
/// Raises the id counter above the ids of [`Document::mounted_art`]'s objects, then gives those
/// objects whose id is 0, past the id range, or already taken by an object visited before them
/// (every other stored object first) a new id, as [`Self::renumber_stored_duplicates`] gives
/// them. Returns how many changed.
pub fn number_mounted_art(&mut self) -> usize {
let mut max = 0;
for (i, (root, _)) in self.mounted_art.iter().enumerate() {
visit(root, StoredPlace { root: StoredRoot::Mounted(i), mask_of: None }, &mut |n, _| {
if n.id.0 < MAX_NEXT_ID {
max = max.max(n.id.0);
}
});
}
self.raise_next_id(max.saturating_add(1));
self.renumber_duplicates_in(|r| matches!(r, StoredRoot::Mounted(_)))
}
/// [`Self::renumber_stored_duplicates`] for the roots `pick` holds for only; the objects of the
/// others still count as taken.
fn renumber_duplicates_in(&mut self, pick: impl Fn(StoredRoot) -> bool) -> usize {
let mut seen: HashSet<NodeId> = HashSet::new();
for l in &self.layers {
l.walk(&mut |n| {
@@ -250,9 +278,9 @@ impl Document {
// Per root, the visiting indices of the nodes that take a new id.
let mut fresh: Vec<(StoredRoot, HashSet<usize>)> = vec![];
for (root, r) in self.stored_roots() {
let (mut i, mut here) = (0, HashSet::new());
let (mut i, mut here, take) = (0, HashSet::new(), pick(r));
visit(root, StoredPlace { root: r, mask_of: None }, &mut |n, place| {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) {
if !place.in_layers() && (n.id.0 == 0 || n.id.0 >= MAX_NEXT_ID || !seen.insert(n.id)) && take {
here.insert(i);
}
i += 1;
@@ -355,6 +383,30 @@ mod tests {
assert_eq!(d, again);
}
/// Mounted art is found and changed by id after the other stored art, and numbering it gives
/// its objects that repeat another stored object's id, or have none, new ids above the counter,
/// leaving every other object's id and its own unique ones as they are.
#[test]
fn mounted_art_is_found_and_numbered_after_the_rest() {
let mut d = doc([12, 13, 14]);
let owner = serde_json::json!({ "kind": "brush" });
d.mounted_art = vec![(Arc::new(masked(10, rect(0))), owner.clone()), (Arc::new(rect(15)), owner)];
assert_eq!(d.stored_node(NodeId(15)).map(|(_, p)| p.root), Some(StoredRoot::Mounted(1)));
let before = d.clone();
assert_eq!(d.number_mounted_art(), 2);
let mut ids = vec![];
d.visit_stored(|n, _| ids.push(n.id.0));
let unique: HashSet<u64> = ids.iter().copied().collect();
assert_eq!(unique.len(), ids.len(), "{ids:?}");
assert_eq!(&ids[..6], &[d.layers[0].id.0, 10, 11, 12, 13, 14], "the other art keeps its ids");
assert_eq!(ids[8], 15, "a unique id is kept");
assert!(ids.iter().all(|id| *id < d.peek_next_id()), "{ids:?} {}", d.peek_next_id());
assert!(Arc::ptr_eq(&d.symbols[0].art, &before.symbols[0].art) && Arc::ptr_eq(&d.mounted_art[1].0, &before.mounted_art[1].0));
d.stored_node_mut(NodeId(15)).unwrap().name = Some("changed".into());
assert_eq!(d.mounted_art[1].0.name.as_deref(), Some("changed"));
assert_eq!(d.number_mounted_art(), 0, "a second pass changes nothing");
}
#[test]
fn renumbered_objects_on_path_keep_their_path_and_members() {
// A symbol's Objects on Path group whose path repeats the layer's object 10 and whose
+79 -3
View File
@@ -206,11 +206,13 @@ impl Document {
impl Document {
/// Visit every paint held by the art (opacity masks included), symbol definitions, pattern
/// tiles and graphic styles (fills, strokes and text runs), and the colour of every
/// gradient-mesh point as a solid paint.
/// gradient-mesh point as a solid paint. A graph's default black legend fill is left out.
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
let default_legend = default_legend_fill(m);
graph_paints(m).enumerate().filter(|(i, _)| Some(*i) != default_legend).for_each(|(_, p)| f(p));
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -404,6 +406,19 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
}
/// The place in [`graph_paints`] of the legend fill graph `n` keeps when it is the default black of a graph that picks
/// its legend labels' fill ([`crate::graph::GraphSpec::picks_legend_fill`]). Other graphs draw the kept fill as it is,
/// so it is visited and mapped.
fn default_legend_fill(n: &Node) -> Option<usize> {
let g = n.extras().graph.as_deref()?;
let l = &g.label_styles;
if l.legend.is_none() || !g.picks_legend_fill() {
return None;
}
let series: usize = g.series_paints.iter().map(|s| usize::from(s.fill.is_some()) + usize::from(s.stroke.is_some())).sum();
Some(series + 2 * (usize::from(l.values.is_some()) + usize::from(l.categories.is_some())))
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -446,11 +461,16 @@ fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
// The default black legend fill, which is not the legend labels' own, stays black.
let default_legend = default_legend_fill(n);
let graph: Vec<(usize, Paint)> =
graph_paints(n).enumerate().filter(|(i, _)| Some(*i) != default_legend).filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
// A legend fill of the labels' own stays theirs when the change makes it black.
spec.label_styles.mark_own_legend_fill();
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
@@ -720,6 +740,62 @@ mod tests {
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn a_legend_fill_mapped_to_black_stays_the_labels_own() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
label_styles: crate::graph::LabelStyles { legend: Some(crate::CharStyle { fill: red, ..Default::default() }), ..Default::default() },
..Default::default()
};
assert!(spec.label_styles.legend_fill_is_own() && !spec.label_styles.legend_fill_set, "not black, saved without the mark");
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut to_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| {
s.as_deref() == Some("Brand") && {
*c = Color::BLACK;
*s = None;
true
}
};
assert_eq!(d.map_solid_paints(&mut to_black), 2, "the rectangle's fill and the legend fill");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
assert_eq!(styles.legend.unwrap().fill, Paint::solid(Color::BLACK));
assert!(styles.legend_fill_set, "the black fill is still the labels' own");
}
#[test]
fn the_default_black_legend_fill_is_left_as_it_is() {
use crate::graph::GraphKind;
// Only a pie with Legends in Wedges picks its legend labels' fill; the other graphs draw the kept black.
for (kind, in_wedges, picks) in [(GraphKind::Pie, true, true), (GraphKind::Pie, false, false), (GraphKind::Column, true, false)] {
let (mut d, a, _) = doc();
let black = || crate::CharStyle { fill: Paint::solid(Color::BLACK), size: 11.0, ..Default::default() };
let spec = crate::graph::GraphSpec {
kind,
legend: true,
pie_legend_in_wedges: in_wedges,
series_paints: vec![crate::SeriesPaint { fill: Some(Paint::solid(Color::BLACK)), ..Default::default() }],
label_styles: crate::graph::LabelStyles { values: Some(black()), legend: Some(black()), ..Default::default() },
..Default::default()
};
let blacks = |d: &Document| {
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == Paint::solid(Color::BLACK)));
seen
};
let before = blacks(&d);
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let want = if picks { 2 } else { 3 };
assert_eq!(blacks(&d) - before, want, "{kind:?}, in wedges {in_wedges}: the series, value labels' and legend fills visited");
let mut link_black = |c: &mut Color, s: &mut Option<String>, _: &mut f32| *c == Color::BLACK && s.replace("Black".into()).is_none();
assert_eq!(d.map_solid_paints_in(&[a], &mut link_black), want, "{kind:?}, in wedges {in_wedges}");
let styles = d.node(a).unwrap().extras().graph.clone().unwrap().label_styles;
let legend = if picks { Paint::solid(Color::BLACK) } else { linked(Color::BLACK, "Black") };
assert_eq!(styles.legend.unwrap().fill, legend, "{kind:?}, in wedges {in_wedges}: linked unless the pie picks the fill");
assert_eq!(styles.values.unwrap().fill, linked(Color::BLACK, "Black"));
}
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
+36 -18
View File
@@ -463,8 +463,13 @@ impl NineSliceMap {
///
/// Strokes keep their weight, as they do for any instance.
pub fn place(&self, art: &Node, doc: &Document) -> Node {
let boxes = doc.symbol_boxes().quick();
self.place_at(art, &boxes, 0)
self.place_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::place`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn place_with(&self, art: &Node, boxes: &SymbolBoxes) -> Node {
self.place_at(art, boxes, 0)
}
/// [`Self::place`] without clip groups, for writers that do not apply clipping (DXF, WMF):
@@ -480,16 +485,25 @@ impl NineSliceMap {
/// object drawn in clip groups counts one group plus a clip path and a copy for each cell its
/// box reaches. That is never more than [`MAX_SLICE_GROWTH`] for each object of `art`.
pub fn most_placed(&self, art: &Node, doc: &Document) -> u64 {
let boxes = doc.symbol_boxes().quick();
self.most_at(art, &boxes, 0)
self.most_placed_with(art, &doc.symbol_boxes().quick())
}
/// [`Self::most_placed`] with the instances in `art` measured by `boxes`, quick boxes or boxes
/// measuring symbol art.
pub(crate) fn most_placed_with(&self, art: &Node, boxes: &SymbolBoxes) -> u64 {
self.most_at(art, boxes, 0)
}
/// The affine map that [`Self::place`] and [`Self::place_unclipped`] move object `n` by as one
/// piece, with everything in it: the map of the cell its box lies in, or of the cell at the
/// origin when it has no box. `None` when its box crosses a guide.
pub fn one_cell(&self, n: &Node, doc: &Document) -> Option<Affine> {
let boxes = doc.symbol_boxes().quick();
let Some(b) = n.geometric(Some(&boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
self.one_cell_with(n, &doc.symbol_boxes().quick())
}
/// [`Self::one_cell`] with the instances in `n` measured by `boxes`.
pub(crate) fn one_cell_with(&self, n: &Node, boxes: &SymbolBoxes) -> Option<Affine> {
let Some(b) = n.geometric(Some(boxes)).map(|b| self.natural.transform_rect_bbox(b)).filter(|b| finite(*b)) else {
return Some(self.cell_at(Point::ZERO));
};
let (cols, rows) = (self.x.cells(b.x0, b.x1), self.y.cells(b.y0, b.y1));
@@ -501,6 +515,11 @@ impl NineSliceMap {
Self { clips: false, ..*self }.most_placed(art, doc)
}
/// This map placing without clip groups, as [`Self::place_unclipped`] does.
pub(crate) fn unclipped(&self) -> Self {
Self { clips: false, ..*self }
}
/// [`Self::most_placed`] for `n` at nesting depth `depth`, following [`Self::place_at`].
fn most_at(&self, n: &Node, boxes: &SymbolBoxes, depth: u32) -> u64 {
let whole = n.count_with_masks() as u64;
@@ -671,7 +690,7 @@ impl NineSliceMap {
}
/// `n` moved by `a`, its strokes at their own weight.
fn transformed(n: &Node, a: Affine) -> Node {
pub(crate) fn transformed(n: &Node, a: Affine) -> Node {
let mut out = n.clone();
out.transform(a, false);
out
@@ -765,10 +784,7 @@ impl Document {
/// `None` when the symbol has no guides or the instance is at its natural size. The guides cut
/// the art's box with the instances in it measured by their own art.
pub fn symbol_slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.symbol_nine_slice(name)?;
let sym = self.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_boxes().quick().art_bounds(name).or_else(|| sym.art.geometric_bounds())?;
NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf)
self.symbol_boxes().quick().slice_map(name, xf)
}
/// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already
@@ -782,9 +798,10 @@ impl Document {
/// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through
/// the guides could make more than [`MAX_SYMBOL_NODES`] objects ([`NineSliceMap::most_placed`]).
pub fn place_symbol_art(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf) {
Some(m) if m.most_placed_with(art, &boxes) > MAX_SYMBOL_NODES => None,
Some(m) => Some(m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
@@ -795,8 +812,8 @@ impl Document {
pub fn edited_nine_slice(&self) -> Option<EditedNineSlice> {
let se = self.symbol_edit.as_ref()?;
let guides = self.symbol_nine_slice(&se.symbol)?;
let sym = self.symbols.iter().find(|s| s.name == se.symbol)?;
let art = self.symbol_boxes().quick().art_bounds(&se.symbol).or_else(|| sym.art.geometric_bounds())?;
let boxes = self.symbol_boxes().quick();
let art = boxes.art_bounds(&se.symbol).or_else(|| boxes.symbol_art(&se.symbol)?.geometric_bounds())?;
let natural = self.symbol_natural_xf(&se.symbol);
let b = natural.transform_rect_bbox(art);
if !finite(b) || b.width() <= 1e-9 || b.height() <= 1e-9 || natural.determinant().abs() < 1e-18 {
@@ -811,8 +828,9 @@ impl Document {
/// [`Self::place_symbol_art`] for writers that do not apply clipping
/// ([`NineSliceMap::place_unclipped`]).
pub fn place_symbol_art_unclipped(&self, name: &str, art: &Node, xf: Affine) -> Option<Node> {
match self.symbol_slice_map(name, xf) {
Some(m) => (m.most_placed_unclipped(art, self) <= MAX_SYMBOL_NODES).then(|| m.place_unclipped(art, self)),
let boxes = self.symbol_boxes().quick();
match boxes.slice_map(name, xf).map(|m| m.unclipped()) {
Some(m) => (m.most_placed_with(art, &boxes) <= MAX_SYMBOL_NODES).then(|| m.place_with(art, &boxes)),
None => Some(transformed(art, xf)),
}
}
+143 -34
View File
@@ -2,13 +2,14 @@
//! the document and measures it once, and an instance's bounds are its art's box placed by the
//! instance's transform ([`Node::geometric_bounds_with`]).
use std::cell::{Cell, RefCell};
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, Node, NodeKind, SYMBOL_HALF};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -26,6 +27,9 @@ const MAX_REACHES: usize = 4096;
/// A symbol's name and the bits of the linear part of a transform that places its art.
type Placing = (String, [u64; 4]);
/// Each symbol name of a document → the index of the first symbol of that name.
pub(crate) type SymbolNames = HashMap<String, usize>;
/// A symbol's art measured in symbol space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ArtBox {
@@ -51,6 +55,10 @@ pub(crate) struct ArtBox {
/// symbols change.
pub struct SymbolBoxes<'a> {
doc: &'a Document,
/// Each symbol name of the document → the index of the first symbol of that name (the one a
/// name finds), made the first time a name is looked up ([`Self::symbol_art`]) or given by
/// [`Self::with_names`].
names: OnceCell<Arc<SymbolNames>>,
/// The art boxes measured so far, by symbol name (`None` for a symbol whose instances are
/// measured by [`SYMBOL_SQUARE`]).
measured: RefCell<HashMap<String, Option<ArtBox>>>,
@@ -89,6 +97,9 @@ pub struct SymbolBoxes<'a> {
sliced_most: u64,
/// The widths [`Self::measured_width`] has measured, by kind and symbol name.
widths: RefCell<HashMap<(&'static str, String), Option<f64>>>,
/// While [`Self::consulted`] runs: the symbols whose art boxes [`Self::art`] has given outside
/// the measuring of symbol art.
consulted: RefCell<Option<HashSet<String>>>,
}
impl Document {
@@ -96,6 +107,7 @@ impl Document {
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
SymbolBoxes {
doc: self,
names: OnceCell::new(),
measured: RefCell::default(),
depths: RefCell::default(),
quick: Cell::new(false),
@@ -110,8 +122,27 @@ impl Document {
sliced_placed: Cell::new(0),
sliced_most: MAX_SYMBOL_NODES,
widths: RefCell::default(),
consulted: RefCell::default(),
}
}
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
names.entry(s.name.clone()).or_insert(i);
}
names
}
}
#[cfg(test)]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
}
impl<'a> SymbolBoxes<'a> {
@@ -120,6 +151,26 @@ impl<'a> SymbolBoxes<'a> {
self.doc
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
let _ = self.names.set(names.clone());
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
}
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -160,21 +211,37 @@ impl<'a> SymbolBoxes<'a> {
/// art boxes. Returns `None` when [`Self::depth`] is `None` and when the art has no finite
/// bounds: instances of the symbol are then measured by [`SYMBOL_SQUARE`].
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
if let Some(b) = self.measured.borrow().get(name) {
return *b;
let cached = self.measured.borrow().get(name).copied();
let b = cached.unwrap_or_else(|| {
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
});
if b.is_some()
&& let Some(seen) = self.consulted.borrow_mut().as_mut()
&& !seen.contains(name)
{
seen.insert(name.to_string());
}
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
}
/// Runs `measure`, and returns the names of the symbols whose art boxes it took from these
/// boxes, the art of symbols it measured left out: the symbols whose art the instances it
/// measured are measured by.
pub(crate) fn consulted(&self, measure: impl FnOnce()) -> HashSet<String> {
let was = self.consulted.replace(Some(HashSet::new()));
measure();
self.consulted.replace(was).unwrap_or_default()
}
/// Runs `measure` on the art of the symbol named `name`. Returns `None` when [`Self::depth`]
/// is `None`, without running it.
pub fn measure_art<R>(&self, name: &str, measure: impl FnOnce(&Arc<Node>) -> R) -> Option<R> {
self.depth(name)?;
let sym = self.doc.symbols.iter().find(|s| s.name == name)?;
let art = self.symbol_art(name)?;
self.runs.set(self.runs.get() + 1);
Some(measure(&sym.art))
Some(measure(art))
}
/// How many times [`Self::measure_art`] has run a measure on symbol art for these boxes, the
@@ -297,10 +364,9 @@ impl<'a> SymbolBoxes<'a> {
/// other symbols it reaches: the depth of each one it walks to the end, and `None` for those on
/// the way down to a symbol that holds an instance of itself or nests too deep.
fn find_depth(&self, name: &str, learned: &mut HashMap<String, Option<usize>>) -> Option<usize> {
let art = |n: &str| self.doc.symbols.iter().find(|s| s.name == n).map(|s| &s.art);
// The symbols on the way down from `name`: each with the symbols its art shows that are
// still to be walked, and the deepest nesting found under it so far.
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), shown(self.doc, art(name)?), 0)];
let mut path: Vec<(String, Vec<String>, usize)> = vec![(name.to_string(), self.shown(self.symbol_art(name)?), 0)];
loop {
let (_, todo, _) = path.last_mut()?;
let Some(next) = todo.pop() else {
@@ -330,8 +396,8 @@ impl<'a> SymbolBoxes<'a> {
// Symbols nested MAX_DEPTH deep under `name`.
None if path.len() >= MAX_DEPTH => return None,
None => {
if let Some(a) = art(&next) {
let todo = shown(self.doc, a);
if let Some(a) = self.symbol_art(&next) {
let todo = self.shown(a);
path.push((next, todo, 0));
}
}
@@ -379,9 +445,9 @@ impl<'a> SymbolBoxes<'a> {
None => {
// The most objects placing makes, the art of opacity masks included, is set aside
// while the art is placed and measured, and what placing did not make is given back.
let art = &self.doc.symbols.iter().find(|s| s.name == name)?.art;
let most = match self.doc.symbol_slice_map(name, linear) {
Some(m) => m.most_placed(art, self.doc),
let art = self.symbol_art(name)?;
let most = match self.slice_map(name, linear) {
Some(m) => self.in_art(|| m.most_placed_with(art, self)),
None => art.count_with_masks() as u64,
};
let used = self.sliced_placed.get();
@@ -398,6 +464,14 @@ impl<'a> SymbolBoxes<'a> {
v.map(|v| moved.transform_rect_bbox(v))
}
/// [`Document::symbol_slice_map`] with the guides cutting the art box these boxes measure for
/// the symbol (its geometric part, which does not depend on the mode of the boxes).
pub(crate) fn slice_map(&self, name: &str, xf: Affine) -> Option<NineSliceMap> {
let guides = self.doc.symbol_nine_slice(name)?;
let art = self.art_bounds(name).or_else(|| self.symbol_art(name)?.geometric_bounds())?;
NineSliceMap::new(guides, art, self.doc.symbol_natural_xf(name), xf)
}
/// The box [`Self::placed_visual_within`] returns outside quick boxes.
fn place_and_measure(&self, name: &str, xf: Affine, most: u64) -> Option<Rect> {
self.place_and_count(name, xf, most).and_then(|(v, _)| v)
@@ -407,10 +481,10 @@ impl<'a> SymbolBoxes<'a> {
/// opacity masks included. `None` when the art is not placed.
fn place_and_count(&self, name: &str, xf: Affine, most: u64) -> Option<(Option<Rect>, u64)> {
self.measure_art(name, |art| {
let art = match self.doc.symbol_slice_map(name, xf) {
Some(m) if m.most_placed(art, self.doc) > most => return None,
Some(m) => m.place(art, self.doc),
None => self.doc.place_symbol_art(name, art, xf)?,
let art = match self.slice_map(name, xf) {
Some(m) if self.in_art(|| m.most_placed_with(art, self)) > most => return None,
Some(m) => self.in_art(|| m.place_with(art, self)),
None => transformed(art, xf),
};
Some((self.in_art(|| art.visual(Some(self))), art.count_with_masks() as u64))
})
@@ -431,11 +505,28 @@ impl<'a> SymbolBoxes<'a> {
fn in_art<R>(&self, f: impl FnOnce() -> R) -> R {
let pad = self.brush_art.replace(false);
let strokes = self.art_strokes.replace(true);
let consulted = self.consulted.take();
let r = self.quickly(f);
self.brush_art.set(pad);
self.art_strokes.set(strokes);
*self.consulted.borrow_mut() = consulted;
r
}
/// The names of the symbols of the document that the instances in `art` show, each once.
fn shown(&self, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& self.symbol_art(symbol).is_some()
{
names.push(symbol.clone());
}
});
names
}
}
/// Records every symbol on `path` in `learned` as one whose instances are measured by
@@ -447,21 +538,6 @@ fn give_up(path: &[(String, Vec<String>, usize)], learned: &mut HashMap<String,
None
}
/// The names of the symbols of `doc` that the instances in `art` show, each once.
fn shown(doc: &Document, art: &Node) -> Vec<String> {
let mut seen = HashSet::new();
let mut names = vec![];
art.walk(&mut |n| {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& seen.insert(symbol.as_str())
&& doc.symbols.iter().any(|s| s.name == *symbol)
{
names.push(symbol.clone());
}
});
names
}
/// Measures symbol art `art`, with the instances in it measured by `symbols`.
fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite());
@@ -630,6 +706,39 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
// scaled 2 times across, each shown by 200 instances scaled by different amounts.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let dot = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Dot {i}"), vec![dot]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
d.set_symbol_nine_slice("Holder", Some(crate::SymbolNineSlice::default()));
let scaled = |d: &mut Document, name: &str| -> Vec<Node> {
(1..=200).map(|i| instance(d, name, Affine::scale_non_uniform(1.0 + f64::from(i) / 100.0, 1.5))).collect()
};
let (panels, holders) = (scaled(&mut d, "Panel"), scaled(&mut d, "Holder"));
// What each instance measures in boxes of its own.
let exact: Vec<_> = panels.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes())).collect();
let quick: Vec<_> = holders.iter().map(|n| n.visual_bounds_with(&d.symbol_boxes().quick())).collect();
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
assert_eq!(panels.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), exact);
let s = d.symbol_boxes().quick();
assert_eq!(holders.iter().map(|n| n.visual_bounds_with(&s)).collect::<Vec<_>>(), quick);
// Each set of boxes reads the list once to find symbols by name.
let symbols = d.symbols.len();
assert!(read() - before <= 2 * symbols, "{} symbols read", read() - before);
}
#[test]
fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() {
let mut d = Document::new(200.0, 200.0);
+307 -7
View File
@@ -17,7 +17,8 @@
//! object of its own, a stroke a path stroked by it alone (brushed strokes their brush art, made by
//! the caller).
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use vectorcraft_doc::color::Paint;
@@ -26,7 +27,7 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
use crate::distort::{transform_move, transform_offsets};
use crate::group::{has_own_paint, paints};
use crate::reshape::{as_art, clipping_text_outline, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
use crate::reshape::{as_art, clipping_text_outline, dressed, 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_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape,
@@ -114,13 +115,181 @@ thread_local! {
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
/// placed art ([`placed_symbol_art`]).
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
/// The objects in the baked art of the instances that [`bake_node`] has replaced by their
/// placed art for one export ([`placed_symbol_art`]), counted against [`Placing::most_nodes`].
static PLACED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// The objects in the baked art of the instances that [`bake_node`] baked for one export and
/// then left as they are ([`placed_fits`] refused the art), counted with [`PLACED_NODES`]
/// against [`Placing::most_nodes`] before more art is baked. Never given back.
static DROPPED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// How deep the object [`bake_node`] is baking sits in the tree it returns: a top-level layer
/// is 1 deep.
static LEVEL: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };
/// Whether [`bake_node`] is baking inside an object the export does not write ([`unwritten`]),
/// where no instance is placed.
static UNWRITTEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// `f` run for an object one level deeper ([`LEVEL`]) than the one being baked.
fn one_deeper<T>(f: impl FnOnce() -> T) -> T {
LEVEL.with(|c| c.set(c.get() + 1));
let out = f();
LEVEL.with(|c| c.set(c.get().saturating_sub(1)));
out
}
/// The symbols whose instances [`bake_document_placing_symbols`] replaces by their placed art, and
/// how that art is placed through 9-slice guides.
struct Placing {
/// The names of the symbols whose art draws something that baking changes, directly or through
/// the instances of other such symbols in it ([`drawn_symbols`]).
symbols: HashSet<String>,
/// Whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
/// ([`Document::place_symbol_art_unclipped`]).
clip_slices: bool,
/// Most objects the baked art of all placed instances may hold together:
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] for an export.
most_nodes: u64,
/// How deep the document's symbols and patterns draw, for the instances and pattern paints
/// left in placed art.
heights: vectorcraft_doc::depth::DrawnHeights,
/// The hidden layers and layers that do not print that the export writes.
layers: WrittenLayers,
}
/// The layers an exporter writes besides the shown, printing ones
/// ([`bake_document_placing_symbols`]). Template layers are never written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WrittenLayers {
/// Hidden layers (written turned off, as PDF layers and DXF write them).
pub hidden: bool,
/// Layers that do not print.
pub non_printing: bool,
}
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
/// that does not print when the export leaves those out ([`WrittenLayers`]).
fn unwritten(n: &Node) -> bool {
PLACING.with(|p| {
p.borrow().as_ref().is_some_and(|p| match n.kind {
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
_ => !n.visible,
})
})
}
/// Can `baked`, the baked art of a placed instance, take the instance's place [`LEVEL`] deep,
/// when the art placed for the export so far holds `spent` objects and the art baked for
/// instances left as they are holds `dropped` ([`DROPPED_NODES`])? `Some` with the
/// objects placed then, when its objects (opacity masks' art included) fit with those within
/// [`Placing::most_nodes`] and nothing in it, the symbols and patterns it uses included, draws
/// deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`].
fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option<u64> {
PLACING.with(|p| {
let p = p.borrow();
let p = p.as_ref()?;
let spent = spent.saturating_add(baked.count_with_masks() as u64);
let deepest = p.heights.deepest(baked, LEVEL.with(|c| c.get()));
(spent.saturating_add(dropped) <= p.most_nodes && deepest <= vectorcraft_doc::depth::MAX_DRAWN_DEPTH).then_some(spent)
})
}
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
/// holds an instance of one of them at any depth.
fn drawn_symbols(d: &Document) -> HashSet<String> {
let mut out: HashSet<String> = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
if out.is_empty() {
return out;
}
let uses: Vec<(&str, Vec<String>)> = d
.symbols
.iter()
.filter(|s| !out.contains(&s.name))
.map(|s| {
let mut names = vec![];
s.art.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
names.push(symbol.clone());
}
});
(s.name.as_str(), names)
})
.collect();
loop {
let before = out.len();
for (name, names) in &uses {
if !out.contains(*name) && names.iter().any(|x| out.contains(x)) {
out.insert((*name).to_string());
}
}
if out.len() == before {
return out;
}
}
}
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
fn holds_placed_symbol(n: &Node) -> bool {
fn walk(n: &Node, symbols: &HashSet<String>) -> bool {
!unwritten(n)
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
}
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
}
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
/// places, as the art it draws: the symbol's art with the instance's own appearance changes and
/// its stain ([`vectorcraft_doc::symbol_overrides::instance_art`]), placed by the instance as the exporters
/// place it, in a group with the instance's id, name, visibility, transparency, opacity mask,
/// raster effects and attributes (its URL among them). The art is placed before its effects are baked, as the canvas draws it, so an
/// instance that scales its art does not scale what its effects do. `None` for other objects,
/// for instances the export does not write ([`unwritten`], hidden or inside such an object), for
/// instances nested [`vectorcraft_doc::depth::MAX_DEPTH`] deep in such art, and when the art
/// as placed, before its effects are baked, would already take the art placed for the export,
/// with the art baked for instances left as they are ([`DROPPED_NODES`]), past
/// [`Placing::most_nodes`]; those instances stay as they are. `Some` with the objects in the art
/// as placed, before its effects are baked. [`bake_node`] checks the baked art with
/// [`placed_fits`].
fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
let (clip, most_nodes) = PLACING.with(|p| p.borrow().as_ref().filter(|p| p.symbols.contains(symbol)).map(|p| (p.clip_slices, p.most_nodes)))?;
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || UNWRITTEN.with(|c| c.get()) || unwritten(n) {
return None;
}
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
let most = match d.symbol_slice_map(symbol, *xf) {
Some(m) if clip => m.most_placed(&art, d),
Some(m) => m.most_placed_unclipped(&art, d),
None => art.count_with_masks() as u64,
};
if PLACED_NODES.with(|c| c.get()).saturating_add(DROPPED_NODES.with(|c| c.get())).saturating_add(most) > most_nodes {
return None;
}
let placed = if clip { d.place_symbol_art(symbol, &art, *xf) } else { d.place_symbol_art_unclipped(symbol, &art, *xf) }?;
let mut g = dressed(Node::group(n.id, vec![Arc::new(placed)]), n);
g.extras_mut().attrs = n.extras().attrs.clone();
Some((g, most))
}
/// `n` with its geometry effects evaluated (`None` = unchanged).
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
// Inside an object the export leaves out, effects are baked but no instance is placed.
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
UNWRITTEN.with(|c| c.set(true));
let out = bake_node(d, n);
UNWRITTEN.with(|c| c.set(false));
return out;
}
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
// A ruler guide draws nothing and stays as it is, last in its layer.
if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
return None;
}
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
@@ -181,6 +350,26 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
}
return Some(baked.unwrap_or(m));
}
// Symbol instances whose art draws live effects, when the caller asks for them: the art
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
// where the instance is, it is dropped with the art placed for the instances inside it, and
// the instance stays as it is. While the art bakes, its objects before baking are held in
// the budget, so the instances inside it are placed only within what is left; art baked and
// then dropped still counts against the budget for the instances after it.
if let Some((m, most)) = placed_symbol_art(d, n) {
let spent = PLACED_NODES.with(|c| c.get());
PLACED_NODES.with(|c| c.set(spent.saturating_add(most)));
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
let baked = bake_node(d, &m);
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
let baked = baked.unwrap_or(m);
if let Some(now) = placed_fits(&baked, spent, DROPPED_NODES.with(|c| c.get())) {
PLACED_NODES.with(|c| c.set(now));
return Some(baked);
}
PLACED_NODES.with(|c| c.set(spent));
DROPPED_NODES.with(|c| c.set(c.get().saturating_add(baked.count_with_masks() as u64)));
}
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
// patterns: each copy an object of its own, so its gradient fits it rather than spanning
// every copy and its strokes and patterns can differ from the others'.
@@ -201,6 +390,9 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
{
return bake_leaf(d, n);
}
if let Some(m) = clip_group_with_type_clip(d, n) {
return Some(m);
}
let mut m = n.clone();
// A clipping path takes the geometry effects in it as the canvas clips by it, those of a
// compound path's paths before the compound path's own ([`crate::clip::with_clip_effects_applied`]);
@@ -211,11 +403,11 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
.enumerate()
.map(|(i, c)| match (i < clip).then(|| crate::clip::with_clip_effects_applied(c)).flatten() {
Some(a) => {
let mut a = bake_node(d, &a).unwrap_or(a);
let mut a = one_deeper(|| bake_node(d, &a)).unwrap_or(a);
fresh_ids(d, &mut a, &mut std::collections::HashSet::new());
Arc::new(a)
}
None => bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()),
None => one_deeper(|| bake_node(d, c)).map(Arc::new).unwrap_or_else(|| c.clone()),
})
.collect();
if let Some(ch) = m.children_mut() {
@@ -226,6 +418,62 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
bake_leaf(d, n)
}
/// Clip group or clipping layer `n` whose clipping path is type with geometry effects (its own, its
/// fills' or strokes', or a perspective), baked as the canvas draws it: the type becomes a
/// clipping path of the region the canvas clips to ([`crate::clip_outline`]), its fills (with their
/// effects baked) paint behind the clipped art inside the clip, and its strokes paint over it
/// outside the clip, in a group that `n` becomes with its clip group inside ([`Node::clip_paint`]).
/// The other members are baked as usual. `None` for other objects and when the type has nothing to
/// clip by.
fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
let (first, rest) = n.children()?.split_first()?;
if !n.clips()
|| !matches!(first.kind, NodeKind::Text(_))
|| !(has_geometry(&first.appearance.effects) || first.projection().is_some() || has_item_geometry(first))
{
return None;
}
let (bp, rule) = crate::clip_outline(first)?;
let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
(*r, *clipping) = (rule, true);
}
clip.name = first.name.clone();
clip.visible = first.visible;
let paint = first.clip_paint();
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
// then given ids of their own.
let mut seen = std::collections::HashSet::from([n.id, first.id]);
let mut art = |d: &mut Document, part: Option<Node>| {
part.map(|p| {
let mut a = bake_node(d, &p).unwrap_or(p);
fresh_ids(d, &mut a, &mut seen);
Arc::new(a)
})
};
let fill = art(d, paint.fill);
let stroke = art(d, paint.stroke);
let members: Vec<Arc<Node>> =
std::iter::once(Arc::new(clip)).chain(fill).chain(rest.iter().map(|c| bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()))).collect();
let mut m = n.clone();
let Some(stroke) = stroke else {
if let Some(ch) = m.children_mut() {
*ch = members;
}
return Some(m);
};
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
match &mut m.kind {
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
*children = vec![Arc::new(inner), stroke];
*clip = false;
}
_ => return None,
}
Some(m)
}
/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the
/// pieces copied from the source keep the source's ids until then). The pieces are baked with the
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id.
@@ -236,7 +484,7 @@ fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
.into_iter()
.map(|c| {
let c = Arc::unwrap_or_clone(c);
let mut c = bake_node(d, &c).unwrap_or(c);
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
fresh_ids(d, &mut c, &mut seen);
Arc::new(c)
})
@@ -713,8 +961,60 @@ fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes:
/// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when
/// there is nothing to do (export it as is).
pub fn bake_document(doc: &Document) -> Option<Document> {
bake(doc, None)
}
/// [`bake_document`], and every symbol instance whose symbol's art draws something baking changes
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
/// symbols' own art is left as it is.
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
}
/// Restores what [`bake`] changes in the thread's baking state when it ends.
struct Restore(Option<Rc<Placing>>, u64, u64, usize, bool);
impl Drop for Restore {
fn drop(&mut self) {
PLACING.with(|p| *p.borrow_mut() = self.0.take());
PLACED_NODES.with(|c| c.set(self.1));
DROPPED_NODES.with(|c| c.set(self.2));
LEVEL.with(|c| c.set(self.3));
UNWRITTEN.with(|c| c.set(self.4));
}
}
/// [`bake_document`], or with `placing` [`bake_document_placing_symbols`] with that `clip_slices`,
/// [`Placing::most_nodes`] and [`Placing::layers`].
fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<Document> {
let placed = doc.with_placed_art();
if !placed.layers.iter().any(|l| needs_bake(l)) {
let placing = placing
.map(|(clip_slices, most_nodes, layers)| (drawn_symbols(&placed), clip_slices, most_nodes, layers))
.filter(|p| !p.0.is_empty())
.map(|(symbols, clip_slices, most_nodes, layers)| Placing {
symbols,
clip_slices,
most_nodes,
heights: vectorcraft_doc::depth::DrawnHeights::of(&placed),
layers,
});
// A bake inside another one (of art an effect makes) places symbols only when it asks to.
let _restore = Restore(
PLACING.with(|p| p.replace(placing.map(Rc::new))),
PLACED_NODES.with(|c| c.replace(0)),
DROPPED_NODES.with(|c| c.replace(0)),
LEVEL.with(|c| c.replace(1)),
UNWRITTEN.with(|c| c.replace(false)),
);
if !placed.layers.iter().any(|l| needs_bake(l) || holds_placed_symbol(l)) {
return match placed {
std::borrow::Cow::Owned(d) => Some(d),
std::borrow::Cow::Borrowed(_) => None,
+393 -1
View File
@@ -2,7 +2,7 @@ use super::*;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
use vectorcraft_geom::{Point, Rect, shapes};
use vectorcraft_geom::{Point, Rect, Shape, shapes};
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
fn skip_without_craft_fonts() -> bool {
@@ -813,6 +813,56 @@ fn type_in_a_clipping_group_with_a_fill_of_its_own_keeps_its_effect() {
assert!(b.y0 > 330.0 && b.y1 < 370.0, "{b:?}");
}
#[test]
fn clipping_type_whose_fill_has_a_geometry_effect_clips_by_its_plain_outlines() {
if skip_without_craft_fonts() {
return;
}
let near = |a: Rect, b: Rect, tol: f64| [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|v| v.abs() < tol);
for stroke in [Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0))] {
// Type that clips a square, with a Transform effect on its own fill.
let mut t = type_node(60);
t.appearance = Appearance::basic(Paint::solid(Color::BLACK), stroke.clone(), 1.0).into();
for item in &mut t.appearance.items {
if let AppearanceItem::Fill(f) = item {
f.effects.push(fx("distort.transform", json!({"moveH": 300})));
}
}
let square = Node::path(NodeId(61), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let clip = Node::new(NodeId(62), NodeKind::Group { children: vec![Arc::new(t.clone()), Arc::new(square)], clip: true });
let canvas = crate::clip_outline(&t).map(|(bp, _)| bp.bounding_box()).unwrap();
assert!(canvas.x1 < 100.0, "the canvas clips by the plain outlines: {canvas:?}");
let d = bake_document(&doc_with(clip)).unwrap();
let baked = d.node(NodeId(62)).unwrap();
// With a stroke, the clip group sits in a group with the stroke over it, outside the clip.
let group = match baked.kind {
NodeKind::Group { clip: true, .. } => {
assert!(stroke.is_none(), "{baked:?}");
baked
}
_ => {
let ch = baked.children().unwrap();
assert_eq!(ch.len(), 2, "{baked:?}");
let strokes = ch[1].appearance.items.iter().all(|i| matches!(i, AppearanceItem::Stroke(_)));
assert!(matches!(ch[1].kind, NodeKind::Text(_)) && strokes, "the type with only its stroke: {:?}", ch[1]);
&ch[0]
}
};
let ch = group.children().unwrap();
assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }) && ch.len() == 3, "{group:?}");
// The export clips by the outlines the canvas clips by.
assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0]);
let b = crate::clip_outline(&ch[0]).map(|(bp, _)| bp.bounding_box()).unwrap();
assert!(near(b, canvas, 1e-6), "canvas {canvas:?}, export {b:?}");
// The fills (the characters' and the moved one) paint behind the square, inside the clip.
let fill = ch[1].geometric_bounds().unwrap();
assert!((fill.x0 - canvas.x0).abs() < 1e-6 && fill.x1 > canvas.x1 + 250.0, "{fill:?}");
assert_eq!(ch[2].id, NodeId(61));
let mut ids = std::collections::HashSet::new();
baked.walk(&mut |n| assert!(ids.insert(n.id), "duplicate id {}", n.id));
}
}
#[test]
fn type_with_its_own_transform_effect_copies_stays_type() {
if skip_without_craft_fonts() {
@@ -1065,3 +1115,345 @@ fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() {
// Three squares of their own, not one path spanning all three.
assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]);
}
/// A 10 × 10 square at (10, 40), with id `id`, that a Transform effect moves 100 pt right.
fn moved_square(id: u64) -> Node {
let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art());
n.appearance.effects.push(fx("distort.transform", json!({"moveH": 100.0})));
n
}
fn instance(id: u64, symbol: &str, xf: vectorcraft_geom::Affine) -> Node {
Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
}
fn add_symbol(d: &mut Document, name: &str, art: Node) {
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
fn bounds(d: &Document, id: u64) -> Rect {
d.node(NodeId(id)).and_then(|n| n.geometric_bounds()).unwrap_or_else(|| panic!("node {id} has bounds"))
}
fn near_rect(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
}
/// Each instance draws its symbol's art with the art's effects applied where the instance places
/// it: an instance that doubles the art's size moves it the effect's 100 pt, as the canvas draws
/// it, not 200 pt. Plain baking leaves the instances and the symbols' art as they are.
#[test]
fn placing_symbols_bakes_their_art_where_each_instance_places_it() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)) * Affine::scale(2.0))).unwrap();
add_symbol(&mut d, "S", moved_square(800));
assert!(bake_document(&d).is_none(), "nothing in the layers needs baking");
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
assert!(matches!(out.node(NodeId(900)).unwrap().kind, NodeKind::Group { .. }));
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 40.0, 120.0, 50.0)), "{:?}", bounds(&out, 900));
assert!(near_rect(bounds(&out, 901), Rect::new(120.0, 180.0, 140.0, 200.0)), "{:?}", bounds(&out, 901));
assert_eq!(out.symbols[0].art.appearance.effects.len(), 1, "the symbol's art keeps its effect");
}
/// An instance of a symbol whose art holds an instance of another symbol with effects draws that
/// art with its effects too.
#[test]
fn placing_symbols_reaches_the_art_of_nested_instances() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
add_symbol(&mut d, "Inner", moved_square(800));
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::translate((0.0, 100.0))))]));
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
}
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
/// ends.
#[test]
fn placing_a_symbol_that_holds_itself_stops() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "Loop", Affine::IDENTITY));
add_symbol(
&mut d,
"Loop",
Node::group(NodeId(801), vec![Arc::new(moved_square(800)), Arc::new(instance(802, "Loop", Affine::translate((0.0, 1.0))))]),
);
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
let mut lefts = vec![];
out.node(NodeId(900)).unwrap().walk(&mut |n| lefts.extend(n.path_data().and_then(|p| p.bounds()).map(|b| b.x0)));
assert!(lefts.len() > 1 && lefts.iter().all(|x| (x - 110.0).abs() < 1e-6), "{lefts:?}");
let mut depth = 0;
let mut n = out.node(NodeId(900)).unwrap();
while let Some(next) = n.children().and_then(|ch| ch.last()) {
n = next;
depth += 1;
}
assert!(depth <= 3 * (vectorcraft_doc::depth::MAX_DEPTH + 1), "{depth}");
}
/// A dynamic symbol instance's own paint for an object of the art applies before the object's
/// effects are baked: a fill whose own Transform effect makes the square a group of pieces still
/// paints in the instance's red, and its sibling keeps the symbol's paint.
#[test]
fn placing_symbols_keeps_dynamic_instances_changes() {
use vectorcraft_geom::Affine;
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let mut square = Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art());
if let Some(AppearanceItem::Fill(f)) = square.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
f.effects.push(fx("distort.transform", json!({"moveH": 100.0})));
}
let sibling = Node::path(NodeId(801), shapes::rectangle(Rect::new(10.0, 60.0, 20.0, 70.0)), Appearance::default_art());
let mut inst = instance(900, "D", Affine::IDENTITY);
inst.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(red.clone()), ..Default::default() }];
let mut d = doc_with(inst);
add_symbol(&mut d, "D", Node::group(NodeId(802), vec![Arc::new(square), Arc::new(sibling)]));
d.symbols[0].dynamic = true;
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
let mut fills = vec![];
out.node(NodeId(900)).unwrap().walk(&mut |n| {
if n.path_data().is_some()
&& let Some(b) = n.geometric_bounds()
{
fills.push((b.x0.round(), b.y0.round(), n.appearance.fill_paint()));
}
});
assert!(fills.contains(&(110.0, 40.0, red)), "{fills:?}");
assert!(fills.contains(&(10.0, 60.0, Paint::solid(Color::WHITE))), "{fills:?}");
}
/// An instance whose fill stains its symbol's art places the art in its stained colors, with the
/// art's effects applied after the stain: a Transform moves the stained square and an Invert
/// inverts the stained color.
#[test]
fn placing_symbols_keeps_the_instances_stain() {
use vectorcraft_geom::Affine;
let blue = Color::rgb8(30, 90, 220);
let mut inst = instance(900, "Mark", Affine::IDENTITY);
inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
inst.appearance.items.retain(|i| i.is_fill());
if let AppearanceItem::Fill(f) = &mut inst.appearance.items[0] {
f.opacity = 0.5;
}
let square =
Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0));
let stained = vectorcraft_doc::symbol_overrides::instance_art(&square, &inst).appearance.fill_paint().color().unwrap();
assert_ne!(stained.to_hex(), blue.to_hex());
let [r, g, b] = stained.to_rgb();
let inverted = Color::rgb(1.0 - r, 1.0 - g, 1.0 - b);
for (id, params, want) in [("distort.transform", json!({"moveH": 100.0}), stained), (crate::addons::color::INVERT, json!({}), inverted)] {
let mut art = square.clone();
art.appearance.effects.push(fx(id, params));
let mut d = doc_with(inst.clone());
add_symbol(&mut d, "Mark", art);
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
assert!(!is_instance(&out, 900), "{id}: the instance is placed");
let mut fills = vec![];
out.node(NodeId(900)).unwrap().walk(&mut |n| {
if n.path_data().is_some() {
fills.extend(n.appearance.fill_paint().color().map(|c| c.to_hex()));
}
});
assert_eq!(fills, [want.to_hex()], "{id}");
}
}
/// Every layer written, as DXF writes them (template layers are never written).
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
fn is_instance(d: &Document, id: u64) -> bool {
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
}
/// The art placed for an export is counted as baked: the copies an effect makes count, so an
/// instance whose baked art passes what is left of the budget stays an instance, and the budget
/// holds the baked art of the instances placed, exactly.
#[test]
fn placing_symbols_counts_the_baked_art() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)))).unwrap();
add_symbol(&mut d, "S", gradient_copies(800));
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
let each = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
assert!(each > 2, "the instance's group, and the copies as objects of their own: {each}");
assert_eq!(all.node(NodeId(901)).map(|n| n.count_with_masks() as u64), Some(each));
let fits = bake(&d, Some((true, 2 * each, ALL))).unwrap();
assert!(!is_instance(&fits, 900) && !is_instance(&fits, 901));
let short = bake(&d, Some((true, 2 * each - 1, ALL))).unwrap();
assert_eq!(usize::from(is_instance(&short, 900)) + usize::from(is_instance(&short, 901)), 1, "one instance stays as it is");
}
/// The baked art of an instance placed inside another's art is counted once: a budget of exactly
/// the outer instance's baked art places both.
#[test]
fn placing_symbols_counts_nested_art_once() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
add_symbol(&mut d, "Inner", gradient_copies(800));
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::IDENTITY))]));
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
let total = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
let exact = bake(&d, Some((true, total, ALL))).unwrap();
assert!(!is_instance(&exact, 900) && !is_instance(&exact, 802), "both are placed within {total}");
let short = bake(&d, Some((true, total - 1, ALL))).unwrap();
assert!(is_instance(&short, 900), "the outer instance stays as it is");
}
/// While an instance's art bakes, the art's own objects are held in the budget: an instance
/// nested in it whose art does not fit in what is left stays as it is, and the outer instance is
/// placed around it.
#[test]
fn placing_symbols_holds_the_outer_art_while_it_bakes() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
add_symbol(&mut d, "Inner", Node::group(NodeId(803), vec![Arc::new(gradient_copies(800))]));
let mut art: Vec<Arc<Node>> = (0..5)
.map(|i| Arc::new(Node::path(NodeId(810 + i), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())))
.collect();
art.push(Arc::new(instance(802, "Inner", Affine::IDENTITY)));
let outer = Node::group(NodeId(801), art);
// The outer instance's group around its art, with the inner instance left as it is.
let around = 1 + outer.count_with_masks() as u64;
add_symbol(&mut d, "Outer", outer);
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
let inner = all.node(NodeId(802)).map_or(0, |n| n.count_with_masks() as u64);
assert!(inner > 2 && inner <= around, "the inner art alone fits: {inner} <= {around}");
let out = bake(&d, Some((true, around, ALL))).unwrap();
assert!(!is_instance(&out, 900) && is_instance(&out, 802), "the outer instance is placed around the inner one");
}
/// Art baked for an instance and then left out, because it passes the budget, still counts: an
/// instance after it whose art would fit in the budget alone stays as it is, and a budget with
/// room for both places both.
#[test]
fn placing_symbols_counts_the_art_it_drops() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(901, "Small", Affine::IDENTITY));
let layer = d.layers[0].id;
d.insert(Some(layer), 0, instance(900, "Big", Affine::IDENTITY)).unwrap();
add_symbol(&mut d, "Big", gradient_copies(800));
add_symbol(&mut d, "Small", moved_square(810));
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
let count = |id: u64| all.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64);
let (big, small) = (count(900), count(901));
assert!(small < big, "{small} < {big}");
let short = bake(&d, Some((true, big - 1, ALL))).unwrap();
assert!(is_instance(&short, 900), "the big art passes {}", big - 1);
assert!(is_instance(&short, 901), "the big art's {big} objects count, so the small art does not fit");
let both = bake(&d, Some((true, big + small, ALL))).unwrap();
assert!(!is_instance(&both, 900) && !is_instance(&both, 901));
}
/// Instances the export does not write are not placed and do not count against the budget: with
/// room for one instance's baked art, hidden instances, an instance in a hidden group, one on a
/// template layer, one on a layer that does not print and one on a hidden layer (when the export
/// leaves those layers out) come first and stay as they are, and the visible instance after them
/// is placed. An export that writes those layers places their instances first.
#[test]
fn placing_symbols_skips_instances_the_export_leaves_out() {
use vectorcraft_geom::Affine;
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
add_symbol(&mut d, "S", gradient_copies(800));
let each = bake(&d, Some((true, u64::MAX, ALL))).unwrap().node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
let layer = d.layers[0].id;
let mut hidden = instance(901, "S", Affine::IDENTITY);
hidden.visible = false;
let mut group = Node::group(NodeId(902), vec![Arc::new(instance(903, "S", Affine::IDENTITY))]);
group.visible = false;
for (i, n) in [hidden, group].into_iter().enumerate() {
d.insert(Some(layer), i, n).unwrap();
}
let mut left_out = vec![];
for (id, template, printable, visible) in [(910, true, true, true), (920, false, false, true), (930, false, true, false)] {
let mut l = Node::layer(NodeId(id), &format!("L{id}"), vectorcraft_doc::LayerColor::Preset(0));
if let NodeKind::Layer { template: t, printable: p, .. } = &mut l.kind {
*t = template;
*p = printable;
}
l.visible = visible;
if let Some(ch) = l.children_mut() {
ch.push(Arc::new(instance(id + 1, "S", Affine::IDENTITY)));
}
left_out.push(Arc::new(l));
}
d.layers.splice(0..0, left_out);
let out = bake(&d, Some((true, each, WrittenLayers::default()))).unwrap();
assert!(!is_instance(&out, 900), "the visible instance is placed within {each}");
for id in [901, 903, 911, 921, 931] {
assert!(is_instance(&out, id), "{id} stays as it is");
}
// An export that writes the layers that do not print, or the hidden layers, places that
// layer's instance first; the template layer's instance is never placed.
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
let out = bake(&d, Some((true, each, layers))).unwrap();
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
}
}
/// `leaf` in `levels` groups, with ids from `id` up.
fn in_groups(id: u64, levels: u64, leaf: Node) -> Node {
(0..levels).fold(leaf, |n, i| Node::group(NodeId(id + i), vec![Arc::new(n)]))
}
/// Placed art is drawn no deeper than the document may draw: an instance whose art's effects add
/// a level past it stays an instance, and the instances around it are placed.
#[test]
fn placing_symbols_keeps_the_baked_art_within_the_drawn_depth() {
use vectorcraft_doc::depth::{DrawnHeights, MAX_DRAWN_DEPTH};
use vectorcraft_geom::Affine;
// The instance on the layer is 2 deep; A to D each hold the next 31 objects down, and E's
// square is 2 deep in its art: 2 + 4 × 31 + 2 = MAX_DRAWN_DEPTH.
let mut d = doc_with(instance(900, "A", Affine::IDENTITY));
for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() {
let base = 1000 * (i as u64 + 1);
add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY)));
}
add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100)));
assert!(!d.too_deep(None));
assert_eq!(DrawnHeights::of(&d).deepest(&d.layers[0], 1), MAX_DRAWN_DEPTH);
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
// E's square becomes a group of copies, a level past the cap: E's instance stays.
assert!(is_instance(&out, 4100), "E's instance stays as it is");
assert!(!is_instance(&out, 900) && !is_instance(&out, 3100), "A to D are placed");
assert!(DrawnHeights::of(&out).deepest(&out.layers[0], 1) <= MAX_DRAWN_DEPTH);
// Without the chain above it, E's art is placed.
let mut shallow = doc_with(instance(900, "E", Affine::IDENTITY));
add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100)));
assert!(!is_instance(&bake_document_placing_symbols(&shallow, true, ALL).unwrap(), 900));
}
/// Art baked for an instance and then left out because it draws too deep still counts when the
/// baked art of a later instance is checked: that art fits before its effects add copies, but
/// not once they do.
#[test]
fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
use vectorcraft_geom::Affine;
// The chain of placing_symbols_keeps_the_baked_art_within_the_drawn_depth, then F, whose
// square becomes a group of copies once baked.
let mut d = doc_with(instance(900, "A", Affine::IDENTITY));
for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() {
let base = 1000 * (i as u64 + 1);
add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY)));
}
add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100)));
add_symbol(&mut d, "F", gradient_copies(6000));
let layer = d.layers[0].id;
d.insert(Some(layer), 1, instance(901, "F", Affine::IDENTITY)).unwrap();
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
assert!(is_instance(&all, 4100) && !is_instance(&all, 900) && !is_instance(&all, 901));
let count = |d: &Document, id: u64| d.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64);
let (a, f) = (count(&all, 900), count(&all, 901));
// E's baked art, as placed where nothing above it draws deep.
let mut shallow = doc_with(instance(4100, "E", Affine::IDENTITY));
add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100)));
let e = count(&bake(&shallow, Some((true, u64::MAX, ALL))).unwrap(), 4100);
assert!(f > 2, "F's copies are objects of their own: {f}");
let short = bake(&d, Some((true, a + e + f - 1, ALL))).unwrap();
assert!(!is_instance(&short, 900) && is_instance(&short, 4100), "A to D are placed, E is not");
assert!(is_instance(&short, 901), "E's dropped {e} objects count, so F's baked {f} do not fit");
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
}
+23 -8
View File
@@ -12,7 +12,7 @@ use vectorcraft_geom::{BezPath, FillRule, PathData};
/// fills and strokes: the region is then the union of the paths they give, as an export bakes them.
/// `None` when there is nothing to clip by (the clipped art is then hidden).
pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
match clip_effects_applied(clip, true) {
match clip_effects_applied(clip, true, || true) {
Some(m) => m.clip_outline(Some(&outline_text), &unite),
None => clip.clip_outline(Some(&outline_text), &unite),
}
@@ -31,14 +31,26 @@ pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
/// geometry effects of its own fills and strokes live instead. `None` when nothing in it has a
/// geometry effect. Effects on the clip group or around it then reshape the result, after its own.
pub(crate) fn with_clip_effects_applied(n: &Node) -> Option<Node> {
let paint = n.clip_paint();
clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none())
with_clip_effects_applied_while(n, || true)
}
/// [`with_clip_effects_applied`]; with `items` unset (a clipping path that paints, and the paths of
/// a compound path, which draw with the compound path's fills and strokes), the geometry effects of
/// `n`'s own fills and strokes are left out.
fn clip_effects_applied(n: &Node, items: bool) -> Option<Node> {
/// [`with_clip_effects_applied`] that calls `take` before it visits each member of a group, layer
/// or compound path in `n`, at every depth: once `take` returns `false`, that member and the
/// members after it are not visited. The members of a group or layer that are not visited stay as
/// they are, with their effects. A compound path with geometry effects of its own still becomes a
/// path of its reshaped geometry. In a clipping path that does not paint, one whose fills or
/// strokes have geometry effects still becomes a group of one path per fill and stroke. In both
/// cases the paths in it that are not visited go
/// into that geometry as they are, and their own effects are not applied.
pub(crate) fn with_clip_effects_applied_while(n: &Node, take: fn() -> bool) -> Option<Node> {
let paint = n.clip_paint();
clip_effects_applied(n, paint.fill.is_none() && paint.stroke.is_none(), take)
}
/// [`with_clip_effects_applied_while`]; with `items` unset (a clipping path that paints, and the
/// paths of a compound path, which draw with the compound path's fills and strokes), the geometry
/// effects of `n`'s own fills and strokes are left out.
fn clip_effects_applied(n: &Node, items: bool, take: fn() -> bool) -> Option<Node> {
let mut m: Option<Node> = None;
let members: &[std::sync::Arc<Node>] = match &n.kind {
NodeKind::Group { children, clip: true } => children.get(..1).unwrap_or_default(),
@@ -53,7 +65,10 @@ fn clip_effects_applied(n: &Node, items: bool) -> Option<Node> {
// The paths of a compound path draw with the compound path's fills and strokes, and stay paths.
let compound = matches!(n.kind, NodeKind::Compound { .. });
for (i, c) in members.iter().enumerate().skip(skip).filter(|(_, c)| all || c.visible) {
if let Some(r) = clip_effects_applied(c, items && !compound)
if !take() {
break;
}
if let Some(r) = clip_effects_applied(c, items && !compound, take)
&& let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
{
*slot = std::sync::Arc::new(r);
+90 -29
View File
@@ -741,35 +741,93 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
Some(g)
}
/// Whether a sublayer among the members of `n`, or among its groups' members, holds a ruler guide.
fn sublayer_guides(n: &Node) -> bool {
n.children().is_some_and(|ch| ch.iter().any(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))))
/// The members of a container that [`take_held_guides`] visits, by index, each with the same for
/// its own members. A ruler guide's entry is empty; a container's is not.
#[derive(Default)]
struct HeldGuides(Vec<(usize, HeldGuides)>);
/// The members of `n` holding or leading to the ruler guides of sublayers, found by looking at each
/// member at every depth once: the ruler guides (`is_guide`) of `n` when it is a layer, each
/// sublayer holding one directly or in its sublayers, and each member of another kind with such a
/// sublayer among its members or its groups' members. With them, whether `n` is a layer holding a
/// ruler guide directly or in its sublayers. The other members of a layer holding none are not
/// looked into, unless the layer is the one whose sublayers are gathered (`top`).
fn held_guides(n: &Node, top: bool, is_guide: &impl Fn(&Node) -> bool) -> (bool, HeldGuides) {
let layer = n.is_layer();
let (mut holds, mut held, mut other) = (false, vec![], vec![]);
for (i, c) in n.children().into_iter().flatten().enumerate() {
if is_guide(c) {
if layer {
holds = true;
held.push((i, HeldGuides::default()));
}
} else if c.is_layer() {
let (sub_holds, inner) = held_guides(c, false, is_guide);
if sub_holds {
holds = true;
held.push((i, inner));
}
} else {
other.push((i, c));
}
}
if !layer || holds || top {
for (i, c) in other {
let (_, inner) = held_guides(c, false, is_guide);
if !inner.0.is_empty() {
held.push((i, inner));
}
}
held.sort_unstable_by_key(|(i, _)| *i);
}
(layer && holds, HeldGuides(held))
}
/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`:
/// those of `n` first, in order, then those of each member in turn. A guide taken from a hidden or
/// locked container, or from one inside such a container, is hidden or locked itself. Only the
/// containers in `held` are copied, and only those are visited.
fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec<Arc<Node>>, hidden: bool, locked: bool) {
let Some(ch) = n.children_mut() else { return };
let (mut own, mut deeper) = (vec![], vec![]);
for (i, inner) in held.0 {
if inner.0.is_empty() {
own.push(i);
continue;
}
let Some(c) = ch.get_mut(i) else { continue };
let c = Arc::make_mut(c);
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
take_held_guides(c, inner, &mut deeper, hidden, locked);
}
if !own.is_empty() {
let mut own = own.into_iter().peekable();
for (i, mut c) in std::mem::take(ch).into_iter().enumerate() {
if own.next_if_eq(&i).is_none() {
ch.push(c);
continue;
}
if hidden || locked {
let g = Arc::make_mut(&mut c);
g.visible &= !hidden;
g.locked |= locked;
}
out.push(c);
}
}
out.append(&mut deeper);
}
/// Move the ruler guides of the sublayers among the members of `n`, and among its groups'
/// members, to `out`, in order. A guide taken from a hidden or locked sublayer, or from one inside
/// such a sublayer or group, is hidden or locked itself. Only containers holding one are copied.
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, locked: bool) {
let Some(ch) = n.children_mut() else { return };
for c in ch.iter_mut().filter(|c| c.holds_ruler_guides() || (!c.is_layer() && sublayer_guides(c))) {
let c = Arc::make_mut(c);
let (hidden, locked) = (hidden || !c.visible, locked || c.locked);
if c.is_layer()
&& let Some(lc) = c.children_mut()
{
let (taken, art): (Vec<_>, Vec<_>) = std::mem::take(lc).into_iter().partition(|g| g.is_ruler_guide());
*lc = art;
out.extend(taken.into_iter().map(|mut g| {
if hidden || locked {
let g = Arc::make_mut(&mut g);
g.visible &= !hidden;
g.locked |= locked;
}
g
}));
}
take_sublayer_guides(c, out, hidden, locked);
}
/// members, to `out`, in order: a sublayer's own guides, then those of its members. A guide taken
/// from a hidden or locked sublayer, or from one inside such a sublayer or group, is hidden or
/// locked itself. Each member at every depth is looked at once at most (`is_guide`), and only
/// containers holding one are copied.
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl Fn(&Node) -> bool) {
let (_, mut held) = held_guides(n, true, is_guide);
// The ruler guides of `n` itself stay where they are.
held.0.retain(|(_, inner)| !inner.0.is_empty());
take_held_guides(n, held, out, false, false);
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
@@ -797,7 +855,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
// So do its sublayers' guides, which would otherwise go with the art the effects replace or
// copy: they stay on this layer, hidden and locked as their sublayers were.
if m.is_layer() && (pathfinder || !fx.is_empty()) {
take_sublayer_guides(&mut m, &mut guides, false, false);
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
}
if pathfinder {
let hook = |c: &Node| crate::outline_object(doc, c);
@@ -846,7 +904,10 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
/// draw. A clip group's clipping path only takes the geometry effects in it into its geometry
/// ([`crate::clip::with_clip_effects_applied`]). Images, symbol instances and the other objects
/// ([`crate::clip::with_clip_effects_applied_while`]), and the members of a clipping group or
/// compound path count toward the limit below. A group or layer in a clipping path that has
/// geometry effects of its own is walked twice, once for its members' effects and once for its
/// own, and its members count each time. Images, symbol instances and the other objects
/// that `own_effects_art` leaves alone stay as they are, and so does a group or layer with a 3D
/// effect with everything in it. Calls nested in one another, through the
/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members
@@ -859,7 +920,7 @@ pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) {
// The clipping path's own geometry effects shape it before the effects around it do.
if clip == 1
&& let Some(first) = ch.first_mut()
&& let Some(applied) = crate::clip::with_clip_effects_applied(first)
&& let Some(applied) = crate::clip::with_clip_effects_applied_while(first, DrawnFrame::take_member)
{
*first = Arc::new(applied);
}
+132
View File
@@ -849,6 +849,53 @@ fn nested_groups_with_effects_count_toward_the_depth_limit() {
assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect");
}
/// The members of a clipping path count toward the member limit: with room for two more members,
/// the third member of a clipping group keeps its own effect as it is.
#[test]
fn clipping_path_members_past_the_member_limit_stay_as_they_are() {
let member = |id: u64| {
let mut m = with_effect(square_at_100(), offset_10());
m.id = NodeId(id);
Arc::new(m)
};
let clipping = Node::group(NodeId(20), vec![member(2), member(3), member(4)]);
let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true });
// An enclosing call that has visited all the members it may but two.
let _outer = DrawnFrame::enter().unwrap();
DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 2)));
members_as_drawn(None, &mut clipped);
let clipping = clipped.children().unwrap()[0].clone();
let effects: Vec<usize> = clipping.children().unwrap().iter().map(|m| crate::reshape::geometry_effects(m).len()).collect();
assert_eq!(effects, [0, 0, 1], "the first two members take their Offset Path, the third keeps it");
let widths: Vec<f64> = clipping.children().unwrap().iter().map(|m| m.geometric_bounds().unwrap().width()).collect();
assert!((widths[0] - 120.0).abs() < 0.5 && (widths[1] - 120.0).abs() < 0.5 && (widths[2] - 100.0).abs() < 0.5, "{widths:?}");
}
/// A compound clipping path with an effect of its own takes that effect when the member limit is
/// reached among its paths: with room for one more member, the first path (at 100 to 200) takes
/// its Offset Path, the second (at 300 to 400) goes in as it is, and the compound path's Offset
/// Path reshapes both, to 80 to 220 and 290 to 410.
#[test]
fn a_compound_clipping_path_takes_its_own_effect_at_the_member_limit() {
let member = |id: u64, x: f64| {
let path = Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 100.0, x + 100.0, 200.0)), black());
Arc::new(with_effect(path, offset_10()))
};
let kind = NodeKind::Compound { children: vec![member(2, 100.0), member(3, 300.0)], rule: FillRule::NonZero };
let clipping = with_effect(Node::new(NodeId(20), kind), offset_10());
let mut clipped = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clipping), Arc::new(square_at_100())], clip: true });
// An enclosing call that has visited all the members it may but one.
let _outer = DrawnFrame::enter().unwrap();
DRAWN.with(|d| d.set((1, crate::SYMBOL_ART_MAX_NODES - 1)));
members_as_drawn(None, &mut clipped);
let clipping = clipped.children().unwrap()[0].clone();
assert!(crate::reshape::geometry_effects(&clipping).is_empty(), "the compound path's Offset Path is in its geometry");
let subpaths = clipping.path_data().unwrap().subpaths.clone();
let bounds: Vec<(f64, f64)> = subpaths.into_iter().map(|sp| PathData::single(sp).bounds().unwrap()).map(|b| (b.x0, b.x1)).collect();
let near = |(a, b): (f64, f64), (x0, x1): (f64, f64)| (a - x0).abs() < 0.5 && (b - x1).abs() < 0.5;
assert!(bounds.len() == 2 && near(bounds[0], (80.0, 220.0)) && near(bounds[1], (290.0, 410.0)), "{bounds:?}");
}
/// An image or a symbol instance that a group's Transform effect moves takes the placed gradients
/// of its own fills along, as a path does, and each copy takes them as many times as it takes the
/// transform.
@@ -1760,6 +1807,91 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked()
}
}
/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks
/// at each member at every depth once at most, and takes the same guides, in the same order and
/// state, as a layer's effects keep.
#[test]
fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
use std::cell::Cell;
use vectorcraft_doc::LayerColor;
const CHAIN: u64 = 6;
let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: true, pos: id as f64, artboard: None }));
let layer = |id, children: Vec<Arc<Node>>| {
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
if let Some(ch) = l.children_mut() {
*ch = children;
}
l
};
// Sublayers nested CHAIN deep, each holding the next before its own art and guide. The second
// is hidden and the fourth locked.
let first_guide = guide(201);
let mut chain = layer(100 + CHAIN, vec![sq(300 + CHAIN, 0.0, Color::BLACK), guide(200 + CHAIN)]);
for depth in (1..CHAIN).rev() {
let own = if depth == 1 { first_guide.clone() } else { guide(200 + depth) };
chain = layer(100 + depth, vec![Arc::new(chain), sq(300 + depth, 0.0, Color::BLACK), own]);
(chain.visible, chain.locked) = (depth != 2, depth == 4);
}
let second_guide = chain.children().and_then(|c| c[0].children()).map(|c| c[2].clone()).unwrap();
// A sublayer inside five nested groups, the third of them locked.
let mut groups = layer(450, vec![guide(250), sq(350, 0.0, Color::BLACK)]);
for depth in (1..=5).rev() {
groups = Node::group(NodeId(400 + depth), vec![Arc::new(groups)]);
groups.locked = depth == 3;
}
let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)]));
// A sublayer with no guide: the art in its group is not looked at.
let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]);
let quiet = Arc::new(layer(600, vec![Arc::new(quiet)]));
let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]);
fn members(n: &Node) -> usize {
n.children().into_iter().flatten().map(|c| 1 + members(c)).sum()
}
let expected: Vec<_> = (1..=CHAIN).map(|depth| (NodeId(200 + depth), depth < 2, depth >= 4)).chain([(NodeId(250), true, true)]).collect();
let state = |g: &[Arc<Node>]| g.iter().map(|g| (g.id, g.visible, g.locked)).collect::<Vec<_>>();
let mut m = root.clone();
let looked = Cell::new(0_usize);
let is_guide = |n: &Node| {
looked.set(looked.get() + 1);
n.is_ruler_guide()
};
let mut taken = vec![];
take_sublayer_guides(&mut m, &mut taken, &is_guide);
assert_eq!(looked.get(), members(&root) - 2, "each member is looked at once, none in the quiet sublayer's group");
assert_eq!(state(&taken), expected, "a sublayer's own guides, then its sublayers', each once");
assert!(Arc::ptr_eq(&taken[0], &first_guide), "a guide with nothing to change is not copied");
assert!(!Arc::ptr_eq(&taken[1], &second_guide), "a guide made hidden is copied");
assert!(second_guide.visible, "the guide as it was stays as it was");
let ch = m.children().unwrap();
assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied");
assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied");
assert!(ch[5].is_ruler_guide(), "the layer's own guide stays where it is");
let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::<Vec<_>>();
assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order");
assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides");
fn found(n: &Node, out: &mut Vec<NodeId>) {
for c in n.children().into_iter().flatten() {
if c.is_ruler_guide() {
out.push(c.id);
}
found(c, out);
}
}
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
root.appearance.effects = vec![Effect { id: effect.into(), params, visible: true }];
let art = evaluate_container(None, &root).unwrap();
let ch = art.children().unwrap();
let tail = &ch[ch.len() - expected.len() - 1..];
assert_eq!(tail[0].id, NodeId(20), "{effect}: the layer's own guide comes first");
assert_eq!(state(&tail[1..]), expected, "{effect}: then the sublayers' guides");
let mut all = vec![];
found(&art, &mut all);
assert_eq!(all.len(), expected.len() + 1, "{effect}: each guide once");
}
}
/// A group's own Fill + Offset Path below its contents follows the outline of a clip group among
/// its members, its clipping path, not the clipped art it hides outside that path (#7289).
#[test]
+6 -3
View File
@@ -68,7 +68,10 @@ pub use adjust::{
ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment,
is_channel,
};
pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake};
pub use bake::{
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
fresh_ids, needs_bake,
};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
@@ -81,8 +84,8 @@ pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text,
reshape,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
outline_text, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+148 -27
View File
@@ -136,8 +136,86 @@ pub(crate) fn facet_art(
composed_art(id, path, paint, Ramp::Rgb(light), seam)
}
/// Composite smooth solid-fill facets with one clip and three channel groups per surface.
/// Black channel backdrops keep shared edges opaque before the final coverage is applied.
/// The width of the seam stroke of a facet's underlay: a round stroke that reaches 1 pt past each
/// edge, over the pixels that the antialiased edges of two neighboring facets each cover only in
/// part at 1:1. A clip to the surface's outline removes what it paints past the surface.
pub(crate) const UNDERLAY_SEAM: f64 = 2.0;
/// The area facet `path` and its round seam stroke `seam` wide paint together: the stroke's outer
/// contours and the facet, all wound one way with a positive area. The stroke's inner contours,
/// wound the other way, are left out: the facet covers them, and contours that cancel each other
/// leave partial coverage where a union of footprints meets at a pixel.
pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcraft_geom::BezPath {
use kurbo::{PathEl, Shape};
let stroke = kurbo::stroke(path.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05);
let sign = if stroke.area() < 0.0 { -1.0 } else { 1.0 };
let mut footprint = vectorcraft_geom::BezPath::new();
let mut contour = vectorcraft_geom::BezPath::new();
for el in stroke.elements().iter().chain(std::iter::once(&PathEl::MoveTo(kurbo::Point::ZERO))) {
if matches!(el, PathEl::MoveTo(_)) && !contour.elements().is_empty() {
if contour.area() * sign >= 0.0 {
footprint.extend(contour.iter());
}
contour = vectorcraft_geom::BezPath::new();
}
contour.push(*el);
}
let mut boundary = path.clone();
if boundary.area() * sign < 0.0 {
boundary = boundary.reverse_subpaths();
}
footprint.extend(boundary.iter());
if sign < 0.0 { footprint.reverse_subpaths() } else { footprint }
}
/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same
/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets'
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
/// in a clip of its footprint, neither with an opacity mask.
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
let mut outline = vectorcraft_geom::BezPath::new();
let mut underlay = Vec::with_capacity(faces.len());
for face in faces {
if face.extras().mask.is_some() {
return None;
}
match &face.kind {
NodeKind::Path { clipping: false, .. } => {
let path = face.path_data()?.to_bezpath();
let mut seam = None;
let mut grown = (**face).clone();
for item in &mut grown.appearance.items {
if let AppearanceItem::Stroke(s) = item {
seam = Some(seam.map_or(s.width, |w: f64| w.max(s.width)));
s.width = UNDERLAY_SEAM;
}
}
outline.extend(footprint(&path, seam?).iter());
underlay.push(Arc::new(grown));
}
NodeKind::Group { children, clip: true } if children.len() == 2 => {
let clip = children.first()?.path_data()?.to_bezpath();
let wider = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&clip, UNDERLAY_SEAM)), Appearance::default());
let colors = children.get(1)?.clone();
outline.extend(clip.iter());
underlay.push(Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(wider), colors], clip: true })));
}
_ => return None,
}
}
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default());
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a
/// shared edge is opaque in that channel's own light before the channels are screened together;
/// the black backdrop shows only outside the surface, which the clip removes.
pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node {
use kurbo::Shape;
use std::sync::Arc;
@@ -167,20 +245,36 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
if let Some(value) = color.get_mut(channel) {
*value = 1.0;
}
let paints: Vec<Paint> = facets
.iter()
.map(|face| {
if let Some(ramp) = face.rgb_gradient {
smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE)
} else {
Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel])))
}
})
.collect();
let draw = |seam: fn(&vectorcraft_three_d::Facet) -> f64| -> Vec<Arc<Node>> {
facets
.iter()
.zip(&paints)
.map(|(face, paint)| {
let edge = seam_stroke(paint.clone(), seam(face));
Arc::new(Node::path(
id,
face.path(),
Appearance {
items: vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(edge)],
..Default::default()
},
))
})
.collect()
};
let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))];
children.extend(facets.iter().map(|face| {
let paint = if let Some(ramp) = face.rgb_gradient {
smooth_paint(vectorcraft_three_d::LightGradient { diffuse: ramp.channels[channel], ambient: 0.0, color }, Color::WHITE)
} else {
Paint::solid(shade(Color::WHITE, color.map(|c| c * face.illumination[channel])))
};
let edge = seam_stroke(paint.clone(), (face.thickness() / 2.0).clamp(0.05, 0.75));
Arc::new(Node::path(
id,
face.path(),
Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint)), AppearanceItem::Stroke(edge)], ..Default::default() },
))
}));
children.extend(draw(|_| UNDERLAY_SEAM));
children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75)));
let mut group = Node::group(id, children);
group.isolate = true;
group.blend = BlendMode::Screen;
@@ -228,24 +322,25 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option<Paint>) {
}
fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node {
use kurbo::Shape;
use std::sync::Arc;
use vectorcraft_doc::color::BlendMode;
use vectorcraft_doc::{Appearance, Node, NodeKind, OpacityMask};
use vectorcraft_geom::{Rect, shapes};
let (base, mask) = opaque_paint(paint);
// Clip once to the union of this single-contour face and its round seam stroke.
// Align their winding so the nonzero fill adds coverage instead of cancelling it.
let mut boundary = path.to_bezpath();
let mut footprint = kurbo::stroke(boundary.iter(), &kurbo::Stroke::new(seam).with_join(kurbo::Join::Round), &kurbo::StrokeOpts::default(), 0.05);
if boundary.area() * footprint.area() < 0.0 {
boundary = boundary.reverse_subpaths();
// An unplaced gradient (and a freeform gradient without points) stays fitted to the face's
// bounds grown by 1 pt, not to the larger cover below.
let mut paint = paint.clone();
if let Paint::Gradient(g) = &mut paint {
g.pin(path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0));
}
footprint.extend(boundary.iter());
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint), Appearance::default());
let (base, mask) = opaque_paint(&paint);
// Clip once to the union of this single-contour face and its round seam stroke.
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&footprint(&path.to_bezpath(), seam)), Appearance::default());
// Opaque rectangles cover the complete seam stroke, without separately antialiasing
// either ramp. Opaque sources need only vector clipping, not full-frame opacity masks.
let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
// either ramp. Opaque sources need only vector clipping, not full-frame opacity masks. They
// reach at least half a point past the seam stroke grown for an underlay ([`sealed`]), so
// their own edges stay outside either clip.
let margin = seam.max(1.0) + UNDERLAY_SEAM / 2.0;
let bounds = path.bounds().unwrap_or(Rect::ZERO).inflate(margin, margin);
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
let mut illumination = match light {
Ramp::Single(light) => cover(smooth_paint(light, Color::WHITE)),
@@ -380,4 +475,30 @@ mod tests {
assert_eq!(point.color.to_rgb(), [1.0, 0.25, 0.25]);
assert_eq!(shaded.swatch, None, "a changed freeform point detaches the gradient swatch");
}
/// Under colored light, a face's unplaced source gradient is fitted to the face's bounds grown by
/// 1 pt, whatever the size of the cover rectangle that draws it; a placed one keeps its placement.
#[test]
fn composed_faces_fit_unplaced_gradients_to_the_face_not_the_cover() {
use vectorcraft_doc::NodeKind;
use vectorcraft_geom::{Rect, shapes};
use vectorcraft_three_d::{RgbGradient, ShadeGradient};
let face = shapes::rectangle(Rect::new(10.0, 20.0, 50.0, 40.0));
let ramp = |b| ShadeGradient { start: Point::new(10.0, 20.0), end: Point::new(50.0, 20.0), brightness: [b, 1.0] };
let light = RgbGradient { channels: [ramp(0.2), ramp(0.5), ramp(0.8)] };
let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)];
let unplaced = GradientPaint { gradient: Gradient::new(GradientKind::Linear, stops), geom: None, angle: 0.0, swatch: None, freeform: None };
let placed = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(80.0, 0.0), aspect: 1.0, focal: None };
let fitted = unplaced.resolve(Rect::new(9.0, 19.0, 51.0, 41.0));
for (geom, expected) in [(None, fitted), (Some(placed), placed)] {
let paint = Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }));
for seam in [0.05, 0.75] {
let art = facet_art(vectorcraft_doc::NodeId(1), &face, &paint, light, seam);
let NodeKind::Group { children, clip: true } = &art.kind else { panic!("a clipped composite") };
let base = &children[1].children().unwrap()[0];
let Paint::Gradient(g) = base.appearance.items[0].paint() else { panic!("the source gradient") };
assert_eq!(g.geom, Some(expected), "seam {seam}");
}
}
}
}
+127 -5
View File
@@ -107,11 +107,44 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`]), or whose
/// live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn, baked and
/// expanded through that art ([`reshape`]).
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
/// baked and expanded through that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n)
has_gradient_copies(n) || has_layered_copies(n) || has_transform_options(n) || has_painted_effects(n) || copied_raster_at(n).is_some()
}
/// Where the own effects of `n`, a path or compound path, split so that each copy of a Transform
/// effect carries the raster effects listed before that effect ([`copied_raster_art`]): the index
/// of the last visible Transform effect that makes copies, when a visible raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it and every other
/// visible effect before it is a geometry effect or such a raster effect. `None` otherwise, and for
/// a path with a linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect
/// plug-in that paints what it returns, or a fill or stroke that paints with geometry effects of
/// its own.
pub(crate) fn copied_raster_at(n: &Node) -> Option<usize> {
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
return None;
}
let effects = &n.appearance.effects;
// Checked first: this runs for every object drawn.
if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
return None;
}
let t = effects.iter().rposition(|e| {
e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0
})?;
let before = effects.get(..t)?;
let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id));
let excluded = n.extras().mask.as_ref().is_some_and(|m| m.linked)
|| crate::has_solid(n)
|| crate::has_revolve(n)
|| crate::has_crop_marks(n)
|| crate::addons::halftone::has_halftone(n)
|| has_painted_effects(n)
|| n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()));
(carried && !excluded).then_some(t)
}
/// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id,
@@ -797,6 +830,9 @@ fn as_art_opts(
nodes: &SymbolNodes,
apart: bool,
) -> Option<Node> {
if let Some(t) = copied_raster_at(n) {
return Some(dressed_keeping_effects(copied_raster_art(paint_doc, n, t, apart), n));
}
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
@@ -868,7 +904,7 @@ fn as_art_opts(
/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and
/// remaining (raster) effects.
fn dressed(mut art: Node, n: &Node) -> Node {
pub(crate) fn dressed(mut art: Node, n: &Node) -> Node {
art.name = n.name.clone();
art.visible = n.visible;
art.opacity = n.opacity;
@@ -882,6 +918,89 @@ fn dressed(mut art: Node, n: &Node) -> Node {
art
}
/// [`dressed`] that keeps the effects of `art`.
fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
let effects = std::mem::take(&mut art.appearance.effects);
let mut art = dressed(art, n);
art.appearance.effects = effects;
art
}
/// The art of path or compound path `n` whose own effects split at `t` ([`copied_raster_at`]): the
/// art the effects before the Transform effect at `t` make of `n`, with their raster effects, then
/// copied by that Transform effect, each copy an object of its own carrying those raster effects
/// moved, turned, reflected and scaled with it ([`follow_art`]), and then reshaped by the geometry
/// effects after it. The art keeps `n`'s id and carries the raster effects from `t` on, without
/// `n`'s name, visibility, transparency and opacity mask. The copies stop where [`copy_art`]'s do,
/// each with its raster effects. With `apart`, the Transform effects before `t` make each copy an
/// object of its own ([`copy_leaf`]).
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool) -> Node {
let (before, rest) = n.appearance.effects.split_at(t);
let mut source = n.clone();
source.appearance.effects = before.to_vec();
let piece = match copied_raster_at(&source) {
Some(at) => copied_raster_art(doc, &source, at, apart),
None => {
let mut art = one_piece(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
if apart {
hoist_copies(&mut art);
}
transform_items(&mut art, doc);
let mut ran = source.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
}
art.appearance.effects = crate::raster::without_geometry(&ran);
art
}
};
let mut art = Node::group(n.id, vec![Arc::new(piece)]);
if let (Some(e), Some(bounds)) = (rest.first(), art.geometric_bounds()) {
let params = merged_params(&e.id, &e.params);
let (m, copies) = crate::distort::transform_map(bounds, &params, n.id.0);
let options = crate::distort::TransformOptions::of(&params);
// The raster effects follow the copies below; Scale Strokes & Effects scales the others.
let mut scaling = copy_scaling(options);
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
let max = Budget::EFFECTS.at_least(art_cost(&art));
copy_art(&mut art, m, copies, scaling, max);
if let Some(children) = art.children_mut() {
// The original is last, and each copy above it is mapped once more by `m`.
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
let mut a = Affine::IDENTITY;
let none = HashSet::new();
for (k, c) in children.iter_mut().rev().enumerate() {
if k > 0 {
a *= step;
follow_art(Arc::make_mut(c), a, &none, Some(&none), None, 0);
}
// Each copy is the piece in a group of its own: the piece takes its place.
if let Some([one]) = c.children().map(Vec::as_slice) {
*c = one.clone();
}
}
}
}
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
let mut ran = n.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
}
art.appearance.effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default());
art
}
/// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect
/// on for a path whose copies each carry the raster effects listed before it ([`copied_raster_at`]).
pub fn outer_effects(n: &Node) -> &[Effect] {
match copied_raster_at(n) {
Some(t) => n.appearance.effects.get(t..).unwrap_or_default(),
None => &n.appearance.effects,
}
}
/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one
/// piece that `n`'s own geometry effects reshape.
fn one_piece(n: &Node) -> Node {
@@ -909,6 +1028,9 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
{
return None;
}
if let Some(t) = copied_raster_at(n) {
return Some(dressed_keeping_effects(copied_raster_art(doc, n, t, false), n));
}
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
// One element: its pieces never knock each other out.
return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art });
+24 -15
View File
@@ -8,6 +8,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, N
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use crate::solids::wireframe::WireFace;
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
@@ -662,11 +663,18 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
/// 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())
/// each member, about one shared axis. With the effect on the object, group or layer, also the
/// shadow drawn behind them. The swatches and patterns named by a live-effect plug-in after a fill's
/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas
/// draws around it ([`surface`]).
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<crate::solids::wireframe::FacesAndShadow, String> {
let faces = |path: &PathData, b: Rect, fx: &Effect, options: Revolve| -> Result<Vec<WireFace>, String> {
if fx.id == CLASSIC_REVOLVE {
let p = merged_params(&fx.id, &fx.params);
let facets = vectorcraft_three_d::revolve_facets(path, b, options)?;
return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect());
}
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
};
if is_container(n) {
let index = n
@@ -675,27 +683,28 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
.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 Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], 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)?);
out.extend(faces(&s.path, b, fx, options)?);
}
return Ok(out);
return Ok((out, group_shadow(n.id, fx, &shapes, b, options)?));
}
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 Some(fx) = n.appearance.effects.get(index) else { return Ok((vec![], 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 paints = solid_paints(n);
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
return faces(&path, b, fx_options(fx));
let surface = faces(&path, b, fx, fx_options(fx))?;
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx))?;
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
@@ -705,11 +714,11 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
{
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))?;
let surface = faces(&p, b, fx, fx_options(fx))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
Ok((out, vec![]))
}
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
+116 -20
View File
@@ -575,10 +575,8 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
.into_iter()
.map(|face| {
// Adjacent facets, antialiased on their own, would leave hairline seams: a narrow
// stroke of the same paint closes them. No wider than the facet is thick, though: seen
// at a grazing angle a facet can be thinner than the stroke, and its stroke would then
// paint over its neighbours.
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
// stroke of the same paint closes them ([`seam_width`]).
let seam = seam_width(&face);
if let Some(g) = face.rgb_gradient
&& (paint.color().is_some() || matches!(paint, Paint::Gradient(_)))
{
@@ -608,6 +606,13 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// The width of the stroke of a facet's own paint that closes the seams between `face` and its
/// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than
/// the stroke, and its stroke would then paint over its neighbors.
pub(crate) fn seam_width(face: &Facet) -> f64 {
(face.thickness() / 2.0).clamp(0.05, 0.75)
}
/// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it
/// whole: a solid color under colored lights with smooth shading?
fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool {
@@ -630,11 +635,26 @@ fn paint_ref(item: &AppearanceItem) -> &Paint {
}
}
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for
/// each face).
/// Are `facets` drawn over an underlay of themselves ([`crate::lighting::sealed`],
/// [`crate::lighting::solid_surface`])? Under colored lights, when any facet takes a smooth light
/// ramp.
fn underlaid(facets: &[Facet], colored: bool) -> bool {
colored && facets.iter().any(|f| f.rgb_gradient.is_some())
}
/// The most paint copies `surface` makes for one facet ([`facet_copies`]).
const MAX_FACET_COPIES: usize = 12;
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), twice that when
/// the facets lie over an underlay of themselves, and [`MAX_FACET_COPIES`] when colored lights also
/// give each facet derived paints in three channels (`lighting::solid_surface`).
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 })
let per_facet = match (underlaid(facets, colored), paint.color().is_some()) {
(true, true) => MAX_FACET_COPIES,
(true, false) => 4,
(false, _) => 2,
};
facets.len().saturating_mul(per_facet)
}
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
@@ -827,14 +847,14 @@ fn rects_overlap(a: Rect, b: Rect) -> bool {
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies
/// of the costliest stroke's paint.
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as
/// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint.
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
let per_face = items
.filter(|item| matches!(item, AppearanceItem::Stroke(_)))
.map(|item| {
let mut copies = 0usize;
crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item));
crate::revolve::paint_copies_add(&mut copies, MAX_FACET_COPIES, paint_ref(item));
copies
})
.max()
@@ -1349,13 +1369,19 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
let art = surfaces_for(doc, n, fx, shapes)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? {
Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)),
None => vec![],
};
let shadow = shadow_for(n.id, fx, shapes).ok()?;
Some((shadow, art))
}
/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`:
/// none with the shadow off, and an error when it is past the limits.
pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<Vec<Arc<Node>>, String> {
Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? {
Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)),
None => vec![],
})
}
/// What the shadow of the solids [`surfaces_for`] builds for effect `id` with parameters `p` on
/// `shapes` is cast from, on one plane: the faces of every solid, the shadow's settings and the
/// faces of each solid of visible art with its member's scopes and ink. `None` with the shadow
@@ -1688,6 +1714,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let split =
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
// Which surfaces lie over an underlay of their facets, in one order or whole
// ([`in_one_order`], [`underlaid_surface`]).
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
@@ -1723,19 +1753,37 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
run.push(s);
}
let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none());
let range = first..first + run.len();
if ordered(member) && flat {
let scopes = run.first().map_or(&[][..], |s| s.2);
out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed)))));
let seals = seals.get(range).unwrap_or_default();
out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed, seals)))));
} else {
out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts));
let run = run.into_iter().zip(range).map(|((_, s, scopes, _), k)| (scopes, Arc::new(underlaid_surface(n.id, s, seal(k..k + 1)))));
out.extend(with_graphics(run.collect(), first, &arts));
}
}
return Some(masked(n.id, out));
}
if !opaque || !surfaces.iter().all(plain) {
let surfaces =
surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect();
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))])
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))])
}
/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when
/// `seal`, keeping the surface's opacity, blend mode and opacity mask.
fn underlaid_surface(id: NodeId, surface: Node, seal: bool) -> Node {
let NodeKind::Group { children, clip: false } = &surface.kind else { return surface };
let Some(mut out) = seal.then(|| crate::lighting::sealed(id, children)).flatten() else { return surface };
out.opacity = surface.opacity;
out.blend = surface.blend;
if let Some(mask) = surface.extras().mask.clone() {
out.extras_mut().mask = Some(mask);
}
out
}
/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in
@@ -1743,7 +1791,16 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops
/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[(usize, PlanarFace, Arc<Node>)], sealed: bool) -> Vec<Arc<Node>> {
/// The faces of the surfaces that `seals` marks lie over underlays of themselves
/// ([`underlaid_runs`], [`underlaid_surface`]).
fn in_one_order(
id: NodeId,
surfaces: Vec<BuiltSurface<'_>>,
first: usize,
arts: &[(usize, PlanarFace, Arc<Node>)],
sealed: bool,
seals: &[bool],
) -> Vec<Arc<Node>> {
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect();
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
@@ -1782,7 +1839,46 @@ fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts:
(masks.len(), art)
}));
}
if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() }
let takes_underlay = |surface: usize| seals.get(surface) == Some(&true);
if masks.iter().any(Option::is_some) {
// The faces of a surface without a mask are sealed run by run before the masked surfaces'
// faces go in runs of their own, each holding one surface's faces, sealed with its mask.
let unmasked = underlaid_runs(id, drawn, |s| takes_underlay(s) && masks.get(s).is_some_and(Option::is_none));
return in_runs(id, unmasked, &masks)
.into_iter()
.map(|run| match &run.kind {
NodeKind::Group { clip: false, .. } if seals.iter().any(|s| *s) && run.extras().mask.is_some() => {
Arc::new(underlaid_surface(id, (*run).clone(), true))
}
_ => run,
})
.collect();
}
underlaid_runs(id, drawn, takes_underlay).into_iter().map(|(_, face)| face).collect()
}
/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive
/// faces of one surface that `seal` takes lies over an underlay of its own faces, clipped to their
/// outline ([`crate::lighting::sealed`]), so no underlay reaches under another surface's faces or a
/// graphic drawn between them. A sealed run keeps its surface's index.
fn underlaid_runs(id: NodeId, faces: Vec<(usize, Arc<Node>)>, seal: impl Fn(usize) -> bool) -> Vec<(usize, Arc<Node>)> {
let mut out = Vec::with_capacity(faces.len());
let mut run: Vec<Arc<Node>> = vec![];
let mut faces = faces.into_iter().peekable();
while let Some((surface, face)) = faces.next() {
run.push(face);
if faces.peek().is_some_and(|(next, _)| *next == surface) {
continue;
}
match seal(surface).then(|| crate::lighting::sealed(id, &run)).flatten() {
Some(sealed) => {
out.push((surface, Arc::new(sealed)));
run.clear();
}
None => out.extend(run.drain(..).map(|face| (surface, face))),
}
}
out
}
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
+7 -1
View File
@@ -192,6 +192,12 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
Color::rgb(r, g, b)
}
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
/// Wireframe, else the seam between faces.
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
if classic_shading(p).surface == ClassicSurface::Wireframe { WIRE } else { super::seam_width(face) }
}
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by
@@ -213,7 +219,7 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
}
let (tone, spec) = shading.tone(face.normal, &lights);
// A narrow stroke of the face's own paint closes the hairline seams between faces.
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
let seam = super::seam_width(&face);
let items = match paint.color() {
// Unshaded (No Shading, no shading color, or a face in full light) with no
// highlight: the paint itself, its color space and swatch kept.
+133 -11
View File
@@ -535,14 +535,53 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
assert_eq!(drawn(&solid, Some(colored)).0, 1);
}
/// The faces `run` stands for: a run of faces over an underlay of themselves ([`crate::lighting::sealed`]:
/// a clip and a group of the underlay's copies followed by the faces) gives its faces, any other
/// node gives itself.
fn unsealed(run: &Arc<Node>) -> Vec<Arc<Node>> {
if let NodeKind::Group { clip: true, children } = &run.kind
&& let [clip, inner] = children.as_slice()
&& matches!(clip.kind, NodeKind::Path { .. })
&& let NodeKind::Group { clip: false, children: kids } = &inner.kind
&& !kids.is_empty()
&& kids.len() % 2 == 0
{
let (under, faces) = kids.split_at(kids.len() / 2);
let underlay = |k: &Arc<Node>| match &k.kind {
NodeKind::Group { clip, .. } => *clip,
_ => k.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.width == crate::lighting::UNDERLAY_SEAM)),
};
if under.first().is_some_and(underlay) {
return faces.to_vec();
}
}
vec![run.clone()]
}
/// The bounds of every face under `n`, a sealed run's faces one by one ([`unsealed`]).
fn face_bounds_under(n: &Arc<Node>, out: &mut Vec<Rect>) {
let faces = unsealed(n);
if faces.len() != 1 || !Arc::ptr_eq(&faces[0], n) {
out.extend(faces.iter().map(|f| drawn_face_bounds(f)));
return;
}
if let NodeKind::Group { clip: true, .. } = &n.kind {
out.push(drawn_face_bounds(n));
}
for child in n.children().into_iter().flatten() {
face_bounds_under(child, out);
}
}
/// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite
/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt.
/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 2 pt (a
/// point past the seam and half the underlay's seam).
fn drawn_face_bounds(f: &Node) -> Rect {
match &f.kind {
NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(),
NodeKind::Group { clip: true, children } => {
let cover = &children[1].children().unwrap()[0];
cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0)
cover.path_data().and_then(PathData::bounds).unwrap().inflate(-2.0, -2.0)
}
_ => panic!("a face is a path or a clipped composite"),
}
@@ -587,7 +626,7 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() {
let art = solid_art(&with).unwrap();
let surfaces = art.children().unwrap();
assert_eq!(surfaces.len(), 1, "{what}: one order");
let faces = surfaces[0].children().unwrap();
let faces: Vec<Arc<Node>> = surfaces[0].children().unwrap().iter().flat_map(unsealed).collect();
assert_eq!(faces.len(), parts.len(), "{what}: one face per facet");
for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() {
let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap());
@@ -616,11 +655,9 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() {
g.appearance.effects.push(fx(id, params.clone()));
let bounds = |art: &Node| {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { clip: true, .. } = &n.kind {
out.push(drawn_face_bounds(n));
}
});
for child in art.children().into_iter().flatten() {
face_bounds_under(child, &mut out);
}
out
};
let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap());
@@ -637,6 +674,89 @@ fn colored_solid_fills_and_strokes_share_face_depth_order() {
assert!(whole_misdrawn > 0, "whole surfaces show farther faces");
}
/// Under a colored light, the faces of an Inflate in gradients, in one order, lie over underlays
/// run by run: each run of consecutive faces of one surface (the fill's or the dashed stroke's)
/// over an underlay of its own faces, so no underlay reaches under the other surface's faces.
#[test]
fn a_colored_inflate_in_gradients_lies_over_underlays_of_each_surfaces_runs() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let gradient = |c: Color| {
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
GradientKind::Linear,
vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)],
))))
};
let mut n = stroked(&letter_c());
for item in &mut n.appearance.items {
match item {
AppearanceItem::Fill(f) => f.paint = gradient(RED),
AppearanceItem::Stroke(s) => {
s.paint = gradient(BLUE);
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
}
}
}
let p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60});
let cut = drawn_parts(&n, INFLATE, &p).len();
let mut lit = p.clone();
lit["lights"] = json!([{"color": "#ff8080"}]);
n.appearance.effects.push(fx(INFLATE, lit));
// Which surface a face belongs to, by the first stop of its paint (a composed face's own paint,
// or a path face's shaded one): red for the fill's, blue for the stroke's.
fn surface_of(face: &Node) -> Option<Color> {
let item = match &face.kind {
NodeKind::Path { .. } => face.appearance.items.first()?,
_ => face.children()?.get(1)?.children()?.first()?.appearance.items.first()?,
};
let Paint::Gradient(g) = item.paint() else { return None };
let [r, _, b] = g.gradient.stops.first()?.color.to_rgb();
Some(if r > b { RED } else { BLUE })
}
// The faces in `order`, and the surface of each run over an underlay, looking into the groups
// that carry a surface's opacity mask.
fn runs(order: &[Arc<Node>], faces: &mut usize, surfaces: &mut Vec<Color>) {
for child in order {
let NodeKind::Group { children, clip } = &child.kind else {
assert!(surface_of(child).is_some(), "a face");
*faces += 1;
continue;
};
if !clip {
assert!(child.extras().mask.is_some(), "a masked run");
runs(children, faces, surfaces);
continue;
}
// A composed face isolates its colors; a run's faces are not isolated together.
if children[1].isolate {
assert!(surface_of(child).is_some(), "a composed face");
*faces += 1;
continue;
}
let stack = children[1].children().unwrap();
let (under, own) = stack.split_at(stack.len() / 2);
assert_eq!(under.len(), own.len(), "one underlay face for each face");
let colors: Vec<_> = own.iter().map(|f| surface_of(f).unwrap()).collect();
assert!(colors.iter().all(|c| *c == colors[0]), "a run holds one surface's faces");
surfaces.push(colors[0]);
*faces += own.len();
}
}
let (mut faces, mut surfaces) = (0, vec![]);
runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces);
assert!(faces >= cut, "{faces} faces, {cut} under a white light, whose cells are not triangulated");
assert!(surfaces.contains(&RED) && surfaces.contains(&BLUE), "{surfaces:?}");
// With transparent stops in the fill's gradient, the fill's faces go in masked runs; the
// stroke's faces, without a mask, still lie over underlays of their own runs.
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_)))
&& let Paint::Gradient(g) = &mut f.paint
{
g.gradient.stops.iter_mut().for_each(|s| s.opacity = 0.5);
}
let (mut faces, mut surfaces) = (0, vec![]);
runs(solid_art(&n).unwrap().children().unwrap()[0].children().unwrap(), &mut faces, &mut surfaces);
assert!(faces >= cut && surfaces.contains(&RED) && surfaces.contains(&BLUE), "{faces} faces, {surfaces:?}");
}
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
/// overlap is cut along the line where their depths meet, into the piece in front of the wall and
/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke
@@ -724,7 +844,7 @@ fn cutting_stays_within_the_face_limit_and_the_paint_allowance() {
let items = stroked(&letter_c()).appearance.items.clone();
let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap();
let mut one = 0usize;
crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke));
crate::revolve::paint_copies_add(&mut one, MAX_FACET_COPIES, paint_ref(stroke));
let max = crate::revolve::MAX_PAINT_COPIES;
assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one));
assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0);
@@ -1595,12 +1715,14 @@ fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
assert_eq!(one[0], paint, "the paint");
// The composite: its paint cover, then each channel's black backdrop and the face's ramp.
let all_fills = fills(&batch);
let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect();
let mut ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect();
// Each channel's ramp is drawn twice, in the underlay and in the facet itself.
ramps.dedup();
assert_eq!(all_fills.first(), Some(&paint));
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0).collect();
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0 && *w != crate::lighting::UNDERLAY_SEAM).collect();
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
+71 -25
View File
@@ -4,13 +4,13 @@ use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId};
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
use vectorcraft_three_d::Facet;
use super::{
Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of, members, object_profile, region,
reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of,
members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds,
};
use crate::{GeomContext, is_geometry};
@@ -53,8 +53,8 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<Path
// 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 (faces, shadow) = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces: Vec<PathData> = after_geometry(doc, n, faces, shadow, revolve).into_iter().map(|f| f.path).collect();
let wire = edges(&faces)?;
if wire.is_empty() {
return Err(format!("{label} draws no faces for this object"));
@@ -63,44 +63,86 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<Path
}
/// `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> {
/// ([`reshaped_beside`]): its first visible Revolve when `revolve` is set, else its first visible
/// Extrude & Bevel, Inflate or Rotate. The effects measure the faces together with `shadow`, the
/// shadow the canvas draws behind them, as they measure the drawn art.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<WireFace>, shadow: Vec<Arc<Node>>, revolve: bool) -> Vec<WireFace> {
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) })
reshaped_beside(faces, shadow, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
}
/// One face of a drawn 3D surface: its outline and the width of the stroke the canvas draws around
/// it (the seam between faces, or a wire edge), which a later Outline Stroke outlines.
pub(crate) struct WireFace {
pub(crate) path: PathData,
pub(crate) stroke: f64,
}
/// `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> {
/// to one budget of anchors together. Each face is filled and carries its round-joined stroke, as on
/// the canvas, so an Outline Stroke outlines that stroke. `ctx` gives the object's id, the seed of a
/// random Transform, and the document.
pub(crate) fn reshaped(faces: Vec<WireFace>, later: &[Effect], ctx: &GeomContext) -> Vec<WireFace> {
reshaped_beside(faces, vec![], later, ctx)
}
/// The name the faces carry through [`reshaped_beside`], which tells them from the shadow.
const FACE: &str = "face";
/// [`reshaped`] with `shadow`, the shadow drawn behind the faces, in the art the effects reshape:
/// each effect measures the faces and the shadow together, and only the faces are returned.
fn reshaped_beside(faces: Vec<WireFace>, shadow: Vec<Arc<Node>>, later: &[Effect], ctx: &GeomContext) -> Vec<WireFace> {
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());
let paint = Paint::solid(Color::BLACK);
let face = |f: WireFace| {
let items =
vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), f.stroke))];
let mut face = Node::path(id, f.path, Appearance { items, ..Default::default() });
face.name = Some(FACE.into());
Arc::new(face)
};
let mut art = Node::group(id, shadow.into_iter().chain(faces.into_iter().map(face)).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()));
face_paths(&art, false, &mut out);
out
}
/// The faces in `n` ([`FACE`]), `inside` one or not, each with the width of its stroke: a face that
/// a Transform effect copies or a live-effect plug-in cuts into pieces becomes a group with its name.
fn face_paths(n: &Node, inside: bool, out: &mut Vec<WireFace>) {
let inside = inside || n.name.as_deref() == Some(FACE);
if inside && let Some(path) = n.path_data() {
out.push(WireFace { path: path.clone(), stroke: n.appearance.stroke().map_or(0.0, |s| s.width) });
}
for c in n.children().into_iter().flatten() {
face_paths(c, inside, out);
}
}
/// The faces of a 3D effect on an object, group or layer itself, and the shadow the canvas draws
/// behind them (none with the shadow off, or with the effect on fills and strokes).
pub(crate) type FacesAndShadow = (Vec<WireFace>, Vec<Arc<Node>>);
/// 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> {
/// the solids of its members, about one shared axis. With the effect on the object, group or layer,
/// also the shadow drawn behind them. 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<FacesAndShadow, 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);
return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, 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)?;
@@ -108,7 +150,8 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, S
let (sources, paints) = solid_paint_sources(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 shapes = [Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }];
return Ok((facet_paths(fx, &shapes)?, super::shadow_for(n.id, fx, &shapes)?));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
@@ -119,24 +162,27 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, S
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
Ok((out, vec![]))
}
/// 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; past the limits of the object's solids together, the result
/// is an error, as the canvas draws the source art.
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
/// is an error, as the canvas draws the source art. Each facet carries the width of the stroke the
/// canvas draws around it.
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, 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 classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
let face = |f: &Facet| WireFace { path: f.path(), stroke: if classic { super::classic::stroke_width(f, &p) } else { super::seam_width(f) } };
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));
out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(face));
}
}
return Ok(out);
@@ -144,7 +190,7 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String>
let (parts, bounds) = solid_parts(shapes, b);
// The solids the art draws, each past the limits of the object's solids together as it is.
for f in built_solids(&fx.id, &p, &parts, bounds, vectorcraft_three_d::MAX_OBJECT_FACES) {
out.extend(f?.iter().flatten().map(Facet::path));
out.extend(f?.iter().flatten().map(face));
}
Ok(out)
}
+59 -3
View File
@@ -163,13 +163,43 @@ fn revolve_classic_and_rotate_classic_expand_too() {
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());
let faces = [square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)].map(|path| WireFace { path, stroke: 0.75 });
let out = reshaped(faces.into(), &fx, &GeomContext::of(&n));
assert_eq!(out.len(), 2);
let (a, b) = (out[0].path.bounds().unwrap(), out[1].path.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:?}");
}
/// An Outline Stroke after a 3D effect outlines the stroke each face is drawn with (the seam between
/// faces, or a Classic wire edge), not a plain 1 pt stroke: the wireframe covers the outlined faces
/// the canvas draws, in the same place.
#[test]
fn a_later_outline_stroke_outlines_the_stroke_each_face_is_drawn_with() {
let outline = || crate::new_effect("path.outlineStroke", &json!({})).unwrap();
let cases = [
(super::super::EXTRUDE, json!({})),
(super::super::CLASSIC_EXTRUDE, json!({})),
(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"})),
(super::super::INFLATE, json!({})),
(ROTATE, json!({})),
(crate::REVOLVE, json!({})),
(crate::CLASSIC_REVOLVE, json!({})),
(crate::CLASSIC_REVOLVE, json!({"surface": "wireframe"})),
];
for (id, params) in cases {
let mut n = solid_square(id, params.clone());
n.appearance.effects.push(outline());
let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id} {params}: {e}"));
let art = if crate::revolve::is_revolve(id) { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap();
let drawn = crate::group::shape_art(None, &art, None).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&drawn)));
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, "{id} {params}: {w:?} {a:?}");
}
}
}
/// 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() {
@@ -192,6 +222,32 @@ fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
}
}
/// A Transform effect after the 3D effect scales the faces about the center of the drawn art with
/// its shadow, as it scales the surfaces on the canvas.
#[test]
fn a_later_transform_measures_the_faces_with_their_shadow() {
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let scale = crate::new_effect("distort.transform", &json!({"scaleH": 50.0, "scaleV": 50.0})).unwrap();
let mut n = solid_square(id, json!({"shadow": true, "shadowDistance": 100}));
n.appearance.effects.push(scale.clone());
let wire = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
let art = if id == crate::REVOLVE { crate::revolve_art(&n) } else { super::super::solid_art(&n) }.unwrap();
let mut drawn = art.clone();
let fx: Vec<&Effect> = art.appearance.effects.iter().collect();
crate::reshape::reshape_leaves(&mut drawn, &fx, &art.appearance.effects, None);
// The shadow is the art's first member; the surfaces follow it.
let surfaces: Vec<PathData> = drawn.children().unwrap().iter().skip(1).flat_map(|c| face_paths(c)).collect();
let a = bounds(&surfaces);
for (x, y) in [(wire.x0, a.x0), (wire.y0, a.y0), (wire.x1, a.x1), (wire.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{id}: {wire:?} {a:?}");
}
// Without the shadow, the faces are scaled about their own center.
let mut alone = solid_square(id, json!({}));
alone.appearance.effects.push(scale);
assert!((bounds(&three_d_wireframe_in(None, &alone).unwrap()).x0 - wire.x0).abs() > 1.0, "{id}");
}
}
/// 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]
+95 -3
View File
@@ -584,8 +584,9 @@ fn image(id: u64, effects: Vec<Effect>) -> Node {
/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster
/// effects that a member's own Transform effect with copies holds back: they keep their value
/// through the member's effect and transform with the group's. That holds for a shadow listed
/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow
/// of a member of a nested group with such an effect, and an image's shadow.
/// before the member's copying effect (which each copy carries), one listed after it, a fill's
/// shadow under it, the shadow of a member of a nested group with such an effect, and an image's
/// shadow.
#[test]
fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let copies = || transform(json!({"moveH": 60, "copies": 1}));
@@ -605,7 +606,8 @@ fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let art = crate::evaluate_container(None, &g).unwrap();
for id in [71, 72, 73, 75, 76] {
let drawn = shadows_in(&node_in(&art, id));
assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
let wanted = if id == 71 { vec![want, want] } else { vec![want] };
assert!(near(&drawn, &wanted), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
@@ -841,3 +843,93 @@ fn copying_and_object_disabled_transforms_keep_their_existing_shadow_rules() {
assert!(close(drawn_shadow(&effects), (10.0, 5.0, 4.0)), "{t:?}: {:?}", drawn_shadow(&effects));
}
}
/// The blur of every Drop Shadow drawn on `n` and the nodes under it, in the order of
/// [`shadows_in`].
fn shadow_blurs_in(n: &Node) -> Vec<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 { blur, .. } = r {
out.push(blur);
}
}
}
});
out
}
/// How many paths `n` holds.
fn paths_in(n: &Node) -> usize {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, vectorcraft_doc::NodeKind::Path { .. })));
count
}
/// A Transform effect that makes copies gives each copy the shadow listed before it, moved, turned,
/// reflected and scaled with that copy, the last copy lowest: drawn, expanded and baked. The object
/// itself keeps the shadow as it is, and paints none around all of them. With Scale Strokes &
/// Effects on, the shadow is not scaled a second time.
#[test]
fn each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it() {
let cases = [
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "random": true}), vec![(10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
];
for (params, want, blurs) in cases {
let n = square(91, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
assert!(crate::has_transform_art(&n), "{params}");
assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}");
let random = params["random"].as_bool().unwrap_or(false);
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert_eq!(paths_in(&art), want.len(), "{params}: {how} {art:?}");
if random {
// Random scales the copy by a share of the 200 %, and its shadow with it; the object
// keeps its own.
assert_eq!(drawn.len(), want.len(), "{params}: {how} {drawn:?}");
assert!(near(&drawn[1..], &want[1..]), "{params}: {how} {drawn:?}");
continue;
}
assert!(near(&drawn, &want), "{params}: {how} {drawn:?}");
let b = shadow_blurs_in(&art);
assert!(b.len() == blurs.len() && b.iter().zip(&blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{params}: {how} blurs {b:?}");
}
}
}
/// A shadow listed after a Transform effect that makes copies paints once around all of them, and
/// one listed before it on each copy. A Transform effect that makes no copies, or has Transform
/// Objects off, leaves the object's shadows on the object.
#[test]
fn a_shadow_after_a_copying_transform_paints_once_around_the_copies() {
let n = square(92, vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)]);
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{:?}", shadows_in(&art));
assert_eq!(crate::outer_effects(&n).len(), 2);
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
let n = square(93, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
assert!(!crate::has_transform_art(&n), "{params}");
assert_eq!(crate::outer_effects(&n).len(), 2, "{params}");
}
}
/// Copies that stop at the effect budget each keep their shadow: no copy goes without one, and no
/// shadow is left without its copy.
#[test]
fn copies_past_the_budget_each_keep_their_shadow() {
let n = path_node(94, wavy(30_000), vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]);
let art = crate::reshape(None, &n, None).unwrap();
let paths = paths_in(&art);
assert!(paths > 1 && paths < 1001, "{paths}");
assert_eq!(shadows_in(&art).len(), paths);
}
+4
View File
@@ -892,6 +892,10 @@ pub use buildcmds::live_paint_gaps;
/// Control bar enable it when it changes one).
pub use brushsym::reset_transformation_changes;
/// The byte order of UTF-16 text without a byte-order mark, by Import Data Sets' rule (the Graph
/// Data window reads files by it too).
pub use variablecmds::utf16_order_without_mark;
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
/// They run as before but the command palette leaves them out (it lists the command once).
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
+12 -8
View File
@@ -21,6 +21,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_render::effects;
use super::super::appearance::series_children_in_paint_order;
use super::super::colorcmds::edit_if_changed;
use super::super::edit::selected_roots;
use super::super::graph::capture_series_object_opacity;
use super::super::menucmds::whole_or;
@@ -92,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Randomize Opacity",
["Object", "Plug-ins", "Arrange Tools"],
None,
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step; it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
has_selection,
randomize_opacity
),
@@ -397,7 +398,8 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "count": 0 }));
}
let (lo, hi) = ((min / 100.0) as f32, (max / 100.0) as f32);
s.edit("Randomize Opacity", |d, _| {
// A run that gives every object the opacity it has records no undo step.
edit_if_changed(s, "Randomize Opacity", |_, d| {
let mut changed = vec![];
for id in &ids {
let o = rng.range(lo, hi);
@@ -409,7 +411,7 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
}
}
keep_series_opacity(d, &changed);
Ok(())
Ok(((), !changed.is_empty()))
})?;
Ok(json!({ "count": ids.len() }))
}
@@ -516,16 +518,18 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
}
let wanted: Vec<(&Sorted, f64)> = rank.iter().filter_map(|i| items.get(*i)).zip(values).collect();
if apply == "opacity" {
if wanted.iter().all(|(o, v)| (o.opacity - v).abs() < 1e-6) {
// The opacity each object is given, as stored; an object whose stored opacity it already is has not changed.
let given: Vec<(NodeId, f32)> = wanted.iter().map(|(o, v)| (o.id, (v / 100.0) as f32)).collect();
let changed: Vec<NodeId> = given.iter().filter(|(id, a)| d.node(*id).is_some_and(|n| n.opacity != *a)).map(|(id, _)| *id).collect();
if changed.is_empty() {
return Ok(count);
}
s.edit("Sort Objects", |d, _| {
for (o, v) in &wanted {
if let Some(n) = d.node_mut(o.id) {
n.opacity = (v / 100.0) as f32;
for (id, a) in &given {
if let Some(n) = d.node_mut(*id) {
n.opacity = *a;
}
}
let changed: Vec<NodeId> = wanted.iter().filter(|(o, v)| (o.opacity - v).abs() >= 1e-6).map(|(o, _)| o.id).collect();
keep_series_opacity(d, &changed);
Ok(())
})?;
@@ -393,6 +393,25 @@ fn randomize_opacity_takes_ids_and_leaves_the_rest() {
assert_eq!((opacity(&s, g), opacity(&s, a), opacity(&s, b)), (0.2, 1.0, 1.0));
}
#[test]
fn randomize_opacity_records_no_undo_step_when_no_opacity_changes() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 5.0, 5.0);
let b = rect(&mut s, 10.0, 0.0, 5.0, 5.0);
select(&mut s, &[a, b]);
let n = steps(&s);
// Every object already has the one opacity the range allows.
let r = s.execute("addon.arrange.randomizeOpacity", &json!({"min": 100, "max": 100})).unwrap();
assert_eq!(r["count"], json!(2));
assert_eq!(steps(&s), n);
assert_eq!((opacity(&s, a), opacity(&s, b)), (1.0, 1.0));
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap();
assert_eq!(steps(&s), n + 1);
s.execute("addon.arrange.randomizeOpacity", &json!({"min": 40, "max": 40})).unwrap();
assert_eq!(steps(&s), n + 1, "the same opacities again");
assert_eq!((opacity(&s, a), opacity(&s, b)), (0.4, 0.4));
}
#[test]
fn randomize_opacity_refuses_bad_params() {
let mut s = session();
+66 -36
View File
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Text",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}",
"{by?: \"lines\"|\"paragraphs\"|\"words\"|\"glyphs\" (lines), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} each horizontal point or area type object becomes point type objects, one per line, paragraph, word or glyph, each where its characters were and with their character styles, as one undo step; spaces between pieces go, a paragraph's lines stay lines (a wrapped line ends in a line break), justified lines close up, and a paragraph broken out whole keeps its bullet (not its number; other pieces have no list markers). Type on a path, vertical type, threaded type and area type whose text doesn't fit stay as they are → {ids (the pieces, selected), skipped}",
has_selection,
break_text
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Combine Point Text",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{ids?: [id…] (default: the selection)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}",
"{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} merge one-line horizontal point type into as few objects as it can, every glyph staying where it was: pieces turned and sheared alike, as visible and as locked (their groups and layers included), whose baselines line up (within 0.4 em; the difference becomes baseline shift) join left to right, a space goes between pieces at least half a space apart, and tracking on the character before each piece keeps the spacing; each object keeps its character styles, and the leftmost piece of each run its place and paint, as one undo step → {ids (the objects made, selected), combined (pieces merged into them)}",
has_selection,
combine_text
),
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Join Point Text",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{ids?: [id…] (default: the selection)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}",
"{ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} join one-line horizontal point type into one point type object, as one undo step: pieces turned and sheared like the top-left one, and as visible and as locked (their groups and layers included), are read as lines (baselines within 0.4 em of each other), top to bottom, each line's pieces left to right with a space between them; each line becomes a paragraph, left aligned, and keeps the distance between baselines as its leading. The text keeps its character styles; the object takes the top-left piece's place and paint, and the other pieces go → {id (selected), joined (pieces merged into it), lines}",
has_selection,
join_text
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Breaks",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{kind: \"line\"|\"paragraph\", ids?: [id…]} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
has_selection,
remove_breaks
),
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Alignment, Keep Position",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}",
"{align: \"left\"|\"center\"|\"right\", ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} align every paragraph of each horizontal point type object so, moving the object so its longest line stays where it is (one line: the text doesn't move), as one undo step → {ids (the objects changed)}",
has_selection,
align_in_place
),
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Text Transform",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}",
"{scale?: bool (false: the horizontal scale stays; true: it goes too, the object's and every character's), ids?: [id…] (default: the selection; the type they name is taken locked or hidden too)} take the rotation, shear and reflection off each point type object, its size and the centre of its text staying, as one undo step → {ids (the objects changed)}",
has_selection,
reset_transform
),
@@ -123,8 +123,17 @@ fn editing_text(s: &Session) -> std::result::Result<(), String> {
}
}
/// The type objects under `roots` (inside groups and layers, not live art) that can be edited.
fn texts_under(d: &Document, roots: &[NodeId]) -> Result<Vec<NodeId>> {
/// The type objects a command acts on: those under the objects `ids` names, locked and hidden ones
/// included, else those under the selection that can be edited ([`texts_under`]).
fn target_texts(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
let named = p.get("ids").is_some_and(|v| !v.is_null());
texts_under(&s.doc()?.doc, &checked_ids_or_selection(s, p, command)?, named)
}
/// The type objects under `roots` (inside groups and layers, not live art). When `named`, every one
/// not on a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer)
/// included; else only those that can be edited.
fn texts_under(d: &Document, roots: &[NodeId], named: bool) -> Result<Vec<NodeId>> {
fn visit(n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Text(_) => out.push(n.id),
@@ -134,8 +143,13 @@ fn texts_under(d: &Document, roots: &[NodeId]) -> Result<Vec<NodeId>> {
}
let mut out = vec![];
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
let editable = d.editable();
out.retain(|id| editable(*id));
if named {
let locks = d.locked_artboards();
out.retain(|id| !locks.holds_id(*id));
} else {
let editable = d.editable();
out.retain(|id| editable(*id));
}
out.dedup();
if out.len() > MAX_TEXTS {
return Err(EngineError::Other("Too many type objects to change at once".into()));
@@ -376,7 +390,9 @@ fn replace_with_pieces(s: &mut Session, label: &str, items: Vec<(NodeId, Node, V
places.push((id, nodes));
}
d.insert_beside(places, true)?;
sel.set(made.iter().copied());
// Pieces of locked or hidden type stay unselected.
let editable = d.editable();
sel.set(made.iter().copied().filter(|id| editable(*id)));
Ok(made.iter().map(|i| i.0).collect())
})
}
@@ -396,7 +412,7 @@ fn break_text(s: &mut Session, p: &Value) -> Result<Value> {
};
let d = &s.doc()?.doc;
let (mut items, mut skipped, mut count) = (vec![], vec![], 0);
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
let ids = target_texts(s, p, C)?;
let threads = thread_index(d);
for id in ids {
let (Some(src), Some(node)) = (Source::of(d, id, threads.contains_key(&id)), d.node(id)) else {
@@ -450,6 +466,9 @@ fn split_text(s: &mut Session, _: &Value) -> Result<Value> {
struct Piece {
id: NodeId,
t: TextObject,
/// Whether the object and every group and layer above it are visible, and whether they are all
/// unlocked.
state: (bool, bool),
/// The object's turn and shear (`xf` without its move).
turn: [f64; 4],
/// Where its first character's glyph starts on its baseline, in that frame.
@@ -487,13 +506,19 @@ impl Piece {
if !(at.x.is_finite() && at.y.is_finite() && size > 0.0) {
return None;
}
Some((Self { id, t, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node))
let state = d.ancestry(id)?.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), n| (v && n.visible, u && !n.locked));
Some((Self { id, t, state, turn: [a, b, c, dd], at, end: at.x + end, size, pens }, node))
}
/// Whether `o` is turned and sheared alike.
fn turned_like(&self, o: &Piece) -> bool {
self.turn.iter().zip(&o.turn).all(|(x, y)| (x - y).abs() <= 1e-6 * x.abs().max(y.abs()).max(1.0))
}
/// Whether `o` is turned and sheared alike and has the same `state`.
fn joins(&self, o: &Piece) -> bool {
self.turned_like(o) && self.state == o.state
}
}
/// Whether two objects look alike apart from their text (paint, opacity, blending, effects).
@@ -595,15 +620,14 @@ fn merge(chain: &[&Piece]) -> std::result::Result<TextObject, usize> {
fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.combineText";
let d = &s.doc()?.doc;
let mut pieces: Vec<(Piece, &Node)> =
texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id)).collect();
// Lines: pieces turned alike and looking alike, by baseline, then left to right.
let mut pieces: Vec<(Piece, &Node)> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id)).collect();
// Lines: pieces turned alike, as visible and as locked and looking alike, by baseline, then left
// to right.
pieces.sort_by(|x, y| x.0.at.y.total_cmp(&y.0.at.y).then(x.0.at.x.total_cmp(&y.0.at.x)));
let mut lines: Vec<Vec<(&Piece, &Node)>> = vec![];
for (piece, node) in &pieces {
let fits = |l: &Vec<(&Piece, &Node)>| {
l.first()
.is_some_and(|(f, n)| f.turned_like(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))
l.first().is_some_and(|(f, n)| f.joins(piece) && same_look(n, node) && (f.at.y - piece.at.y).abs() <= SAME_LINE * f.size.min(piece.size))
};
match lines.iter_mut().find(|l| fits(l)) {
Some(l) => l.push((piece, node)),
@@ -672,7 +696,8 @@ fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
gone.extend(others);
}
d.remove_many(&gone)?;
sel.set(ids.iter().map(|i| NodeId(*i)));
let editable = d.editable();
sel.set(ids.iter().map(|i| NodeId(*i)).filter(|id| editable(*id)));
Ok(())
})?;
Ok(json!({ "ids": ids, "combined": combined }))
@@ -681,15 +706,15 @@ fn combine_text(s: &mut Session, p: &Value) -> Result<Value> {
fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "addon.cleanup.joinText";
let d = &s.doc()?.doc;
let pieces: Vec<Piece> =
texts_under(d, &checked_ids_or_selection(s, p, C)?)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect();
// The piece top-left on the page sets the turn; the others turned like it are read in that frame.
let pieces: Vec<Piece> = target_texts(s, p, C)?.into_iter().filter_map(|id| Piece::of(d, id).map(|p| p.0)).collect();
// The piece top-left on the page sets the turn; the others turned like it, and as visible and as
// locked, are read in that frame.
let on_page = |p: &Piece| Affine::new([p.turn[0], p.turn[1], p.turn[2], p.turn[3], 0.0, 0.0]) * p.at;
let first = pieces.iter().min_by(|x, y| {
let (a, b) = (on_page(x), on_page(y));
a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x))
});
let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| p.turned_like(f)).collect()).unwrap_or_default();
let mut kept: Vec<&Piece> = first.map(|f| pieces.iter().filter(|p| f.joins(p)).collect()).unwrap_or_default();
kept.sort_by(|x, y| x.at.y.total_cmp(&y.at.y).then(x.at.x.total_cmp(&y.at.x)));
// Lines, top to bottom, by baseline; each line's pieces left to right.
let mut lines: Vec<Vec<&Piece>> = vec![];
@@ -751,7 +776,7 @@ fn join_text(s: &mut Session, p: &Value) -> Result<Value> {
n.kind = NodeKind::Text(Box::new(m));
}
d.remove_many(&gone)?;
sel.set([id]);
sel.set([id].into_iter().filter(|id| d.is_editable(*id)));
Ok(())
})?;
Ok(json!({ "id": id.0, "joined": joined, "lines": count }))
@@ -797,8 +822,8 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
/// comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
/// (each frame when `all`) comes with its own breaks, at its own bytes.
fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> {
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
// The breaks in story order, handed to the frames in one pass.
@@ -811,7 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(us
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
own.push((at - start, space));
}
if d.is_editable(id) {
if all || d.is_editable(id) {
out.push((id, own));
}
start = end;
@@ -834,31 +859,38 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
let d = &s.doc()?.doc;
// Each type object with the breaks that go from it.
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false),
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
.into_iter()
.filter(|(id, ..)| d.is_editable(*id))
.filter_map(|(id, a, b)| Some((id, break_cuts(&text_of(d, id)?.plain_text(), a, b, brk))))
.collect(),
None => {
let ids = texts_under(d, &checked_ids_or_selection(s, p, C)?)?;
let ids = target_texts(s, p, C)?;
// A threaded story whose frames are all among them is read as one text, once.
let named: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let threads = thread_index(d);
let mut done = std::collections::HashSet::new();
// The threads already found not to be a story whose frames are all among them: their
// other frames are read one at a time without going through the thread again.
let mut partial = std::collections::HashSet::new();
let mut out: Vec<(NodeId, Vec<(usize, bool)>)> = vec![];
for &id in &ids {
if !done.insert(id) {
continue;
}
let story = match threads.get(&id).and_then(|&i| d.text_threads.get(i)) {
Some(thread) => crate::cmd::threads::story_in(d, thread, id),
let thread = threads.get(&id).copied();
let story = match thread.filter(|i| !partial.contains(i)).and_then(|i| d.text_threads.get(i)) {
Some(frames) => crate::cmd::threads::story_in(d, frames, id),
None => vec![],
};
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
done.extend(story.iter().copied());
out.extend(story_cuts(d, &story, brk));
// Every frame is among them, so each one keeps its breaks.
out.extend(story_cuts(d, &story, brk, true));
} else if let Some(t) = text_of(d, id) {
// `id` is type, so the story of its thread is the same for each of its frames.
partial.extend(thread);
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
}
}
@@ -891,10 +923,8 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
/// Horizontal point type among the objects `p` names.
fn point_texts(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids: Vec<NodeId> = texts_under(d, &checked_ids_or_selection(s, p, cmd)?)?
.into_iter()
.filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point)))
.collect();
let ids: Vec<NodeId> =
target_texts(s, p, cmd)?.into_iter().filter(|id| text_of(d, *id).is_some_and(|t| matches!(t.kind, TextKind::Point))).collect();
if ids.is_empty() {
return Err(EngineError::Other("Select point type".into()));
}
@@ -379,6 +379,228 @@ fn remove_breaks_reads_the_threads_once() {
}
}
/// Remove Breaks reads each named frame of a story that is not all named on its own, in the order
/// named and each once, as one undo step, and goes through that story's frames once for all of them.
#[test]
fn remove_breaks_goes_through_a_partly_named_story_once() {
for (kind, brk) in [("line", '\u{2028}'), ("paragraph", '\n')] {
let mut s = session();
let a = text(&mut s, json!({"x": 10, "y": 20, "text": "a\u{2028}b\n".repeat(40), "size": 12, "area": {"width": 150, "height": 60}}));
let mut roots = vec![a];
for i in 0..4 {
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 100 + 70 * i, "width": 150, "height": 60})).unwrap();
roots.push(NodeId(r["id"].as_u64().unwrap()));
}
select(&mut s, &roots);
s.execute("text.thread.create", &json!({})).unwrap();
let f = s.doc().unwrap().doc.text_threads[0].clone();
assert_eq!(f.len(), 5);
let named = [f[4], f[1], f[3]];
let breaks: Vec<usize> = named.iter().map(|id| obj(&s, *id).plain_text().matches(brk).count()).collect();
assert!(breaks.iter().all(|n| *n > 0), "{kind}: each named frame holds breaks: {breaks:?}");
let before = doc_json(&s);
let steps = undo_steps(&s);
let builds = crate::cmd::threads::story_builds();
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": kind, "ids": [f[4].0, f[1].0, f[4].0, f[3].0]})).unwrap();
assert_eq!(crate::cmd::threads::story_builds() - builds, 1, "{kind}: the story's frames are gone through once");
assert_eq!(r["removed"].as_u64(), Some(breaks.iter().sum::<usize>() as u64), "{kind}");
assert_eq!(ids(&r), named, "{kind}");
assert_eq!(undo_steps(&s), steps + 1, "{kind}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(doc_json(&s), before, "{kind}");
}
}
/// Lock `id` (`locked`), else hide it, as an undo step of its own.
fn lock_or_hide(s: &mut Session, id: NodeId, locked: bool) {
s.edit("Lock or Hide", |d, _| {
let n = d.node_mut(id).unwrap();
if locked {
n.locked = true;
} else {
n.visible = false;
}
Ok(())
})
.unwrap();
}
/// Remove Breaks takes the locked and hidden type that `ids` names, and the locked member of a
/// group it names, as one undo step; from the selection it takes only type that can be edited, and
/// nothing changed makes no undo step.
#[test]
fn remove_breaks_named_locked_and_hidden_type() {
let mut s = session();
let locked = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12}));
let hidden = text(&mut s, json!({"x": 40, "y": 120, "text": "c\nd", "size": 12}));
let grouped = text(&mut s, json!({"x": 40, "y": 180, "text": "e\nf", "size": 12}));
let free = text(&mut s, json!({"x": 40, "y": 240, "text": "g\nh", "size": 12}));
select(&mut s, &[grouped, free]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
lock_or_hide(&mut s, locked, true);
lock_or_hide(&mut s, hidden, false);
lock_or_hide(&mut s, grouped, true);
select(&mut s, &[locked, hidden]);
let steps = undo_steps(&s);
assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"}))), "No paragraph breaks to remove");
assert_eq!(undo_steps(&s), steps, "the selected locked and hidden type stays as it is");
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0, hidden.0, group.0]})).unwrap();
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(r["removed"], 4);
for (id, now) in [(locked, "a b"), (hidden, "c d"), (grouped, "e f"), (free, "g h")] {
assert_eq!(obj(&s, id).plain_text(), now);
}
assert_eq!(other(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [locked.0]}))), "No paragraph breaks to remove");
assert_eq!(undo_steps(&s), steps + 1, "nothing changed, no undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(obj(&s, locked).plain_text(), "a\nb");
}
/// A threaded story whose frames `ids` all names is read as one text even when a frame is locked.
#[test]
fn remove_breaks_named_story_with_a_locked_frame() {
let mut s = session();
let (a, b) = threaded(&mut s, "one\ntwo");
lock_or_hide(&mut s, a, true);
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [a.0, b.0]})).unwrap();
assert_eq!(r["removed"], 1);
assert_eq!(obj(&s, a).plain_text(), "one two");
}
/// Type on a locked artboard stays as it is even when `ids` names it, with no undo step.
#[test]
fn remove_breaks_named_type_on_a_locked_artboard() {
let mut s = session();
let on_board = text(&mut s, json!({"x": 40, "y": 60, "text": "a\nb", "size": 12}));
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph", "ids": [on_board.0]}));
assert_eq!(other(r), "No paragraph breaks to remove");
assert_eq!(undo_steps(&s), steps);
assert_eq!(obj(&s, on_board).plain_text(), "a\nb");
}
/// Break Text, Combine and Join Point Text, Set Alignment, Keep Position and Reset Text Transform
/// act on the locked and hidden type that `ids` names (type in a locked layer included), each as
/// one undo step, and leave it as it is when it is only selected.
#[test]
fn named_locked_and_hidden_type() {
let mut s = session();
let words = text(&mut s, json!({"x": 40, "y": 100, "text": "Two words", "size": 14}));
lock_or_hide(&mut s, words, true);
select(&mut s, &[words]);
assert!(s.execute("addon.cleanup.breakText", &json!({"by": "words"})).is_err());
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.breakText", &json!({"by": "words", "ids": [words.0]})).unwrap();
assert_eq!((ids(&r).len(), undo_steps(&s)), (2, steps + 1));
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked pieces stay unselected");
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
lock_or_hide(&mut s, a, false);
lock_or_hide(&mut s, b, false);
select(&mut s, &[a, b]);
assert!(s.execute("addon.cleanup.combineText", &json!({})).is_err());
let r = s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).unwrap();
assert_eq!(ids(&r), [a]);
assert_eq!(obj(&s, a).plain_text(), "Left Right");
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden object stays unselected");
let mut s = session();
let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20}));
let second = text(&mut s, json!({"x": 50, "y": 130, "text": "Second", "size": 20}));
let layer = s.doc().unwrap().doc.layers[0].id;
lock_or_hide(&mut s, layer, true);
select(&mut s, &[first, second]);
assert!(s.execute("addon.cleanup.joinText", &json!({})).is_err());
let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, second.0]})).unwrap();
assert_eq!(r["id"].as_u64(), Some(first.0));
assert_eq!(obj(&s, first).plain_text(), "First\nSecond");
assert!(s.doc().unwrap().selection.objects.is_empty(), "the object in the locked layer stays unselected");
let mut s = session();
let lines = text(&mut s, json!({"x": 50, "y": 100, "text": "a\nlonger line", "size": 20}));
lock_or_hide(&mut s, lines, false);
select(&mut s, &[lines]);
assert!(s.execute("addon.cleanup.alignInPlace", &json!({"align": "center"})).is_err());
s.execute("addon.cleanup.alignInPlace", &json!({"align": "center", "ids": [lines.0]})).unwrap();
assert!(obj(&s, lines).para_styles().all(|p| p.justify == Justify::Center));
let mut s = session();
let turned = text(&mut s, json!({"x": 300, "y": 200, "text": "Turned", "size": 18, "rotation": 30}));
lock_or_hide(&mut s, turned, true);
select(&mut s, &[turned]);
assert!(s.execute("addon.cleanup.resetTextTransform", &json!({})).is_err());
let steps = undo_steps(&s);
s.execute("addon.cleanup.resetTextTransform", &json!({"ids": [turned.0]})).unwrap();
assert_eq!(undo_steps(&s), steps + 1);
let [_, b, c, _, _, _] = obj(&s, turned).xf.as_coeffs();
assert!(b.abs() < 1e-9 && c.abs() < 1e-9, "the rotation is gone");
}
/// Combine Point Text joins named pieces only with pieces as visible and as locked, a group's lock
/// included: a visible piece and a hidden one beside it, or a free piece and one in a locked group,
/// stay as they are, with no undo step.
#[test]
fn combine_keeps_hidden_and_locked_pieces_apart() {
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
lock_or_hide(&mut s, b, false);
let steps = undo_steps(&s);
assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, b.0]})).is_err());
assert_eq!(undo_steps(&s), steps);
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into()));
let d = &s.doc().unwrap().doc;
assert!(d.is_visible(a) && !d.is_visible(b), "the visible text stays shown and the hidden text stays hidden");
let mut s = session();
let a = text(&mut s, json!({"x": 50, "y": 100, "text": "Left", "size": 20}));
let b = text(&mut s, json!({"x": 110, "y": 100, "text": "Right", "size": 20}));
select(&mut s, &[b]);
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
lock_or_hide(&mut s, group, true);
let steps = undo_steps(&s);
assert!(s.execute("addon.cleanup.combineText", &json!({"ids": [a.0, group.0]})).is_err());
assert_eq!(undo_steps(&s), steps);
assert_eq!((obj(&s, a).plain_text(), obj(&s, b).plain_text()), ("Left".into(), "Right".into()));
}
/// Join Point Text joins only the named pieces as visible and as locked as the top-left one: a
/// hidden piece between two visible lines stays as it is, hidden, and a hidden top-left piece
/// with only a visible one below it joins nothing, with no undo step.
#[test]
fn join_keeps_a_hidden_piece_apart() {
let mut s = session();
let first = text(&mut s, json!({"x": 50, "y": 100, "text": "First", "size": 20}));
let hidden = text(&mut s, json!({"x": 50, "y": 130, "text": "Hidden", "size": 20}));
let third = text(&mut s, json!({"x": 50, "y": 160, "text": "Third", "size": 20}));
lock_or_hide(&mut s, hidden, false);
let steps = undo_steps(&s);
let r = s.execute("addon.cleanup.joinText", &json!({"ids": [first.0, hidden.0, third.0]})).unwrap();
assert_eq!((r["id"].as_u64(), r["joined"].as_u64(), undo_steps(&s)), (Some(first.0), Some(2), steps + 1));
assert_eq!(obj(&s, first).plain_text(), "First\nThird");
assert_eq!(obj(&s, hidden).plain_text(), "Hidden");
let d = &s.doc().unwrap().doc;
assert!(d.is_visible(first) && !d.is_visible(hidden), "the visible text stays shown and the hidden text stays hidden");
assert!(d.node(third).is_none());
let mut s = session();
let top = text(&mut s, json!({"x": 50, "y": 100, "text": "Top", "size": 20}));
let below = text(&mut s, json!({"x": 50, "y": 130, "text": "Below", "size": 20}));
lock_or_hide(&mut s, top, false);
let steps = undo_steps(&s);
assert!(s.execute("addon.cleanup.joinText", &json!({"ids": [top.0, below.0]})).is_err());
assert_eq!(undo_steps(&s), steps);
assert_eq!((obj(&s, top).plain_text(), obj(&s, below).plain_text()), ("Top".into(), "Below".into()));
assert!(s.doc().unwrap().doc.is_visible(below));
}
#[test]
fn split_at_the_cursor_and_around_a_selection() {
for (anchor, caret, want) in [(6, 6, &["Split", "here please"][..]), (6, 10, &["Split", "here", "please"][..])] {
+2 -1
View File
@@ -320,7 +320,8 @@ fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Optio
/// After an edit from `before` (`None`: everything is new, as after a document's links are read):
/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph
/// designs, patterns and the original of the pattern being edited, opacity mask art included)
/// designs, patterns, the original of the pattern being edited and the art of the stored brushes
/// while it is set on the document, opacity mask art included)
/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the
/// art that changed since `before` is looked at.
pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) {
+5 -11
View File
@@ -6,8 +6,8 @@ use vectorcraft_doc::Scaling;
use vectorcraft_geom::{Rect, Vec2};
use super::object::choice;
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
use super::panelcmds::{artboard_at, artboards_art, locked_and_hidden, named_or_selected, note_artboards, on_board};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, index, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
@@ -63,13 +63,7 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
check_switches(p, &["patterns"], cmd)?;
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
let indices = named_or_selected(s, p, cmd)?;
let given = |key: &str| -> Result<Option<usize>> {
match p.get(key).filter(|v| !v.is_null()) {
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
None => Ok(None),
}
};
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
let (named, recorded) = (artboard_at(&s.doc()?.doc, p, "artboard", cmd)?, artboard_at(&s.doc()?.doc, p, "activeArtboard", cmd)?);
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
note_artboards(s, p, &indices);
@@ -78,8 +72,8 @@ fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
(false, _) => None,
(true, Some(i)) => Some(i),
(true, None) => {
let active = s.tool_options_of("artboard")["active"].clone();
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
let active = s.tool_options_of("artboard")["active"].as_u64().map(index);
Some(active.map_or_else(|| Err(EngineError::Other("no such artboard".into())), |i| on_board(&s.doc()?.doc, i))?)
}
};
if let Some(i) = reference.filter(|_| named.is_none()) {
+1 -1
View File
@@ -180,7 +180,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paintbrush",
[],
None,
"{…params as path.freehand, brush} paint a freehand stroke with a brush → {id}",
"{…params as path.freehand, brush?: name} paint a freehand stroke with a brush; without `brush` (or with null) the plain path is drawn; a `brush` that names no brush in the document, or a `style` other than \"pencil\" or \"brush\", is an error and nothing is drawn → {id}",
has_doc,
brush_freehand
),
+14 -1
View File
@@ -729,8 +729,21 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&out) }))
}
/// Paints a `path.freehand` stroke with the brush `brush` names. A `brush` left out or null draws
/// the plain path; a `brush` that is not a string or names no brush in the document, and a `style`
/// other than "pencil" or "brush", is an error before anything is drawn.
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
const C: &str = "brush.freehand";
let name = match crate::cmd::text_param(p, "brush", C)? {
None => None,
Some(n) if brush::find(&s.doc()?.doc, n).is_some() => Some(n.to_string()),
Some(n) => return Err(bad(C, format!("no brush named `{n}`"))),
};
match p.get("style") {
None | Some(Value::Null) => {}
Some(v) if matches!(v.as_str(), Some("pencil" | "brush")) => {}
Some(v) => return Err(bad(C, format!("`style` must be \"pencil\" or \"brush\", not {v}"))),
}
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
let r = crate::cmd::run_checked(s, spec, p)?;
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
+1 -1
View File
@@ -135,7 +135,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Info",
[],
None,
"{group, id?: object id (default: the selection)} → {faces: [{id, fill, bounds}], edges: [{id, stroke, width}], sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
"{group?|id?: Live Paint group id (one required; id is read when group is left out)} → {faces: [{id, fill (top fill), bounds, appearance: [row…]}], edges: [{id, stroke (top stroke), width (top stroke's), appearance: [row…]}], where a row is {index (in the part's fill and stroke stack, bottom first), kind: \"fill\"|\"stroke\", paint, opacity: 0..1, visible, width?: pt (strokes only), drawn (the part is shown with opacity above 0, and the row is shown, has paint and opacity above 0, a stroke also width above 0)}, sources, gapOptions: {detect, size: \"small\"|\"medium\"|\"large\"|pt, points, color: #rrggbb} (as livePaint.gapOptions sets them), gaps: [[x0,y0,x1,y1]…] (as livePaint.gapOptions returns them)}",
has_doc,
lp_info
),
+49 -5
View File
@@ -1,7 +1,8 @@
use super::{
Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, PathData, Point, Rect,
Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, json,
number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
switch_or,
};
/// `options` as stored on a Live Paint group: none for the defaults.
@@ -524,6 +525,37 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "edge": edge.0 }))
}
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
/// row is `drawn` when the part is shown with an opacity above 0 and the row is shown, has paint
/// and has an opacity above 0 (a stroke also a weight above 0): the rule of [`draws`], row by row.
fn appearance_rows(n: &Node) -> Vec<Value> {
let part_shown = n.visible && n.opacity > 0.0;
n.appearance
.items
.iter()
.enumerate()
.map(|(i, item)| {
let shown = part_shown && item.visible() && !item.paint().is_none() && item.opacity() > 0.0;
let mut row = json!({
"index": i,
"kind": item.kind_name(),
"paint": item.paint().label(),
"opacity": item.opacity(),
"visible": item.visible(),
});
let drawn = match item {
AppearanceItem::Fill(_) => shown,
AppearanceItem::Stroke(st) => {
row["width"] = json!(st.width);
shown && st.width > 0.0
}
};
row["drawn"] = json!(drawn);
row
})
.collect()
}
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
let g = match object_param(p, "group", "livePaint.info")? {
Some(g) => g,
@@ -535,12 +567,24 @@ pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|f| {
let bb = f.geometric_bounds().unwrap_or(Rect::ZERO);
json!({ "id": f.id.0, "fill": f.appearance.fill_paint().label(), "bounds": [bb.x0, bb.y0, bb.x1, bb.y1] })
json!({
"id": f.id.0,
"fill": f.appearance.fill_paint().label(),
"bounds": [bb.x0, bb.y0, bb.x1, bb.y1],
"appearance": appearance_rows(f),
})
})
.collect();
let edges: Vec<Value> = b::edges(n)
.iter()
.map(|e| json!({ "id": e.id.0, "stroke": e.appearance.stroke_paint().label(), "width": e.appearance.stroke_width() }))
.map(|e| {
json!({
"id": e.id.0,
"stroke": e.appearance.stroke_paint().label(),
"width": e.appearance.stroke_width(),
"appearance": appearance_rows(e),
})
})
.collect();
let sources = b::sources(n).and_then(|g| g.children()).map(|c| c.len()).unwrap_or(0);
let options = n.gap_options();
+12 -8
View File
@@ -526,12 +526,15 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
.collect())
}
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
/// for the command's own.
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
/// ([`TraceRun`]) stands in for the command's own in the same document.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
/// document never stands in for one in another, however alike their images and settings.
doc: u64,
target: NodeId,
image: Box<ImageObject>,
/// The settings traced with, as JSON.
@@ -600,7 +603,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
@@ -612,8 +615,9 @@ pub struct Traced {
}
impl Traced {
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]), which
/// applies it as one undo step instead of tracing again. Any other trace drops it.
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
/// document it was made in, which applies it as one undo step instead of tracing again. Any
/// other trace drops it, a trace in another document included.
pub fn hand_in(self, s: &mut Session) {
s.trace_hand_off = Some(self);
}
@@ -686,7 +690,7 @@ impl TraceRun {
}
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now?
/// now, in the document it was prepared in?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
+34 -3
View File
@@ -9,7 +9,8 @@
//! ([`use_front_profiles`]): when they are assigned, when the working settings change, and when the
//! document comes to the front or its assignment comes back (an open, a switch, a close, a revert,
//! an undo or a rollback, [`Session::sync_front_profiles`]); the working spaces stay as Edit → Color
//! Settings set them.
//! Settings set them. A document drawn while another is in front draws through its own profiles
//! ([`doc_cms`]).
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -236,6 +237,9 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
} else if proof_targets(&info.name) {
// A new file of the CMYK profile View → Proof Setup targets: redraw.
touch_all(s);
} else {
// Documents behind the front one draw through their own profiles: those assigned it redraw.
touch_assigned(s, &info.name);
}
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
}
@@ -266,9 +270,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
if proof_targets(&info.name) {
touch_all(s);
}
// Documents behind the front one draw through their own profiles: those assigned it redraw.
touch_assigned(s, &info.name);
Ok(json!({"removed": info.name}))
}
/// Redraw the open documents assigned the profile `name`.
fn touch_assigned(s: &mut Session, name: &str) {
for d in &mut s.docs {
let (rgb, cmyk) = doc_profiles(&d.doc);
if [rgb, cmyk].iter().any(|n| n.as_deref() == Some(name)) {
d.revision += 1;
}
}
}
/// 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)
@@ -285,6 +301,14 @@ pub fn doc_profiles(d: &vectorcraft_doc::Document) -> (Option<String>, Option<St
(get(&d.color_profiles.rgb), get(&d.color_profiles.cmyk))
}
/// The color-management context the document draws through: the working settings with its
/// assigned profiles in place of the working spaces, whether or not it is in front
/// ([`cms::for_document`]).
pub fn doc_cms(d: &vectorcraft_doc::Document) -> Arc<cms::Cms> {
let (rgb, cmyk) = doc_profiles(d);
cms::for_document(rgb.as_deref(), cmyk.as_deref())
}
fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.assignProfile";
let (mut rgb, mut cmyk) = doc_profiles(&s.doc()?.doc);
@@ -662,8 +686,15 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color
}
}
let styles = &mut g.label_styles;
for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() {
map_paint_colors(&mut st.fill, f);
// A legend fill of the labels' own stays theirs when `f` makes it black. The default black legend fill stays black,
// so the labels on dark pie wedges are still drawn white.
styles.mark_own_legend_fill();
let own = styles.legend_fill_is_own();
for (st, fill) in [(&mut styles.values, true), (&mut styles.categories, true), (&mut styles.legend, own)] {
let Some(st) = st else { continue };
if fill {
map_paint_colors(&mut st.fill, f);
}
map_paint_colors(&mut st.stroke, f);
}
for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() {
+14 -5
View File
@@ -671,10 +671,11 @@ fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
}
/// Type a document replaced in the back sets in a composite font that only the front document
/// defines is measured in that font while the front one is registered, and again, as missing, when
/// the replaced document comes to the front.
/// defines is measured as missing, though the front one is registered, also when the replaced
/// document defines no composite font, and still as missing when it comes to the front.
#[test]
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing() {
let db = vectorcraft_text::FontDb::global();
let mut s = session();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
@@ -682,8 +683,16 @@ fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
let back = text_in(&s, 0, id);
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
assert_eq!(back.cached_bounds, Some(expected));
assert!(s.documents()[0].doc.composite_fonts.is_empty());
let in_front = vectorcraft_text::layout(db, &back).bounds;
// The same type set in a family nothing defines.
let mut nowhere = back.clone();
for r in &mut nowhere.runs {
r.style.font_family = "No Such Family CF Lacked".into();
}
let missing = vectorcraft_text::layout(db, &nowhere).bounds;
assert!((in_front.width() - missing.width()).abs() > 1e-6, "the front document's font draws otherwise");
assert_eq!(back.cached_bounds, Some(missing));
assert!(s.set_active(0));
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
let actual = text(&s, id);
+2 -2
View File
@@ -26,7 +26,7 @@ pub use perspective::perspective_click;
use perspective::{
attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release,
};
pub(crate) use perspective::{finish_edit_text, grid_of, perspective_rewrite, silent, store_grid, transform_again};
pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -107,7 +107,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Perspective Grid Preset",
[],
None,
"{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached)",
"{kind: 1|2|3 (its normal view) | name: a preset (see perspective.presets.list)} reset the grid to the preset fitted to the first artboard (and show it; attached objects stay attached). No undo step when the document already holds that grid; when only whether it shows or its active plane differs, those are set without one",
has_doc,
super::perspgrid::grid_preset
),
@@ -18,7 +18,7 @@ pub(crate) fn store_grid(d: &mut Document, g: &PerspectiveGrid) {
/// Whether `d` holds `g` as [`store_grid`] writes it (with `attached` cleared): then storing `g`
/// leaves `d` as it is.
fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool {
let mut g = g.clone();
g.attached.clear();
serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v))
+2 -2
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
has_doc,
freehand
),
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag → {ids, before, after}",
"{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}",
has_selection,
smooth_region
),
+22 -5
View File
@@ -217,11 +217,18 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
}
None => None,
};
// An extending stroke that ends within four Fidelities of the path's other end closes it:
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
// `closed`, when given, says whether the stroke closes the path: the Pencil and the
// Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release.
// Left out, an extending stroke that ends within four Fidelities of the path's other end
// closes it: at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
if closing && let Some(l) = pts.last_mut() {
let near_first = pts.last().is_some_and(|p| p.distance(first) <= close_tol);
let wants_close = if p.get("closed").is_some_and(|v| !v.is_null()) { closed } else { near_first };
let closing = connect.is_none() && sp.anchors.len() >= 2 && wants_close;
// A stroke ending near the other end ends on it; one ending farther away closes with a
// straight segment back to it.
let ends_on_first = closing && near_first;
if ends_on_first && let Some(l) = pts.last_mut() {
*l = first;
}
if let Some((_, _, y, _)) = &connect
@@ -238,13 +245,23 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
add.remove(0);
}
sp.anchors.extend(add);
if closing
if ends_on_first
&& sp.anchors.len() > 2
&& let Some(l) = sp.anchors.pop()
&& let Some(a0) = sp.anchors.first_mut()
{
a0.h_in = l.h_in;
sp.closed = true;
} else if closing && !ends_on_first && sp.anchors.len() > 2 {
// Closed from away from the other end: a straight segment back to it, whatever
// handles the open ends carried.
sp.closed = true;
if let Some(l) = sp.anchors.last_mut() {
l.h_out = l.p;
}
if let Some(f) = sp.anchors.first_mut() {
f.h_in = f.p;
}
}
for a in &mut sp.anchors {
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
+556 -10
View File
@@ -13,9 +13,237 @@ use super::{
/// of path within the reach on either side of it. VectorCraft's own value.
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach
/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a
/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value,
/// the same on every drag and at any Fidelity.
const SMOOTH_CORNER_DEG: f64 = 57.5;
/// Most pieces a curved segment is cut into evenly, and most more pieces near each of its ends, to
/// measure lengths along it in [`smooth_corners`].
const CORNER_PIECES: usize = 64;
/// The control polygon's length of `c`, which is at least its length.
fn polygon_len(c: CubicBez) -> f64 {
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
}
/// The places (0 to 1, in order, without 0 and with 1) on the curved segment `c` that
/// [`smooth_corners`] measures it at: up to [`CORNER_PIECES`] evenly spaced, and near each end, over
/// a stretch at least three times `reach` long where the segment is that long, up to as many more
/// that are no more than `reach` / 8 apart along the control polygon, and as many again in each
/// stretch twice as long after it until the pieces reach three times `reach`. The turns over `reach` and
/// twice `reach` from an anchor are then measured along the curve however long the segment is.
fn corner_places(c: CubicBez, reach: f64) -> Vec<f64> {
let piece = reach / 8.0;
let pieces = |len: f64| if piece > 0.0 { (len / piece).ceil().clamp(1.0, CORNER_PIECES as f64) as usize } else { 1 };
let k = pieces(polygon_len(c)).max(4);
let mut places: Vec<f64> = (1..=k).map(|j| j as f64 / k as f64).collect();
if piece > 0.0 {
for from_start in [true, false] {
// The stretch from the end: halved until its control polygon is at most six reaches long.
let first = 1.0 / k as f64;
let mut t = first;
let part = |t: f64| if from_start { c.subsegment(0.0..t) } else { c.subsegment(1.0 - t..1.0) };
for _ in 0..60 {
if polygon_len(part(t)) <= 6.0 * reach {
break;
}
t /= 2.0;
}
let side = |u: f64| if from_start { u } else { 1.0 - u };
let m = pieces(polygon_len(part(t)));
let mut fine: Vec<f64> = (1..=m).map(|j| t * j as f64 / m as f64).collect();
// Then the stretches twice as long in turn, cut as finely, up to the first even place, until
// the pieces reach three reaches from the end, so twice the reach is measured along the curve
// where a handle that does not reach out makes the curve start more slowly than its polygon.
let mut covered = 0.0;
let mut at = c.eval(side(0.0));
for u in &fine {
let q = c.eval(side(*u));
covered += at.distance(q);
at = q;
}
let (mut from, mut levels) = (t, 0);
while covered < 3.0 * reach && from < first && levels < 60 {
let to = (2.0 * from).min(first);
let piece_len = polygon_len(if from_start { c.subsegment(from..to) } else { c.subsegment(1.0 - to..1.0 - from) });
let m = pieces(piece_len);
for j in 1..=m {
let u = from + (to - from) * j as f64 / m as f64;
let q = c.eval(side(u));
covered += at.distance(q);
at = q;
fine.push(u);
}
(from, levels) = (to, levels + 1);
}
places.extend(fine.into_iter().map(side));
}
}
places.retain(|u| *u > 0.0 && *u <= 1.0);
places.sort_by(f64::total_cmp);
places.dedup();
places
}
/// The degrees between the directions `u` and `v`, `None` when either has no length or is not a
/// number.
fn turn_between(u: kurbo::Vec2, v: kurbo::Vec2) -> Option<f64> {
let (lu, lv) = (u.hypot(), v.hypot());
if !(lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12) {
return None;
}
let deg = u.cross(v).atan2(u.dot(v)).abs().to_degrees();
deg.is_finite().then_some(deg)
}
/// Which anchors of `anchors` (a closed path when `closed`) the Smooth tool keeps as corners: those
/// where the path turns by more than [`SMOOTH_CORNER_DEG`] at the anchor itself, between the
/// direction it arrives along and the one it leaves along, and also over `reach` and over twice
/// `reach` on either side of it, between the direction from the point that far back along the path
/// to the anchor and the direction from the anchor to the point that far ahead. The points are taken
/// no farther than the ends of an open path, and no more than an eighth of the way round a closed
/// one. A jag or a bump smaller than the reach turns sharply at its anchor but not over twice the
/// reach, and an anchor in the middle of a tight curve turns over the reach but not at the anchor, so
/// neither is kept. An open path's first and last anchors are never corners.
fn smooth_corners(anchors: &[Anchor], closed: bool, reach: f64) -> Vec<bool> {
let n = anchors.len();
let mut corners = vec![false; n];
if n < 2 || (n < 3 && !closed) {
return corners;
}
// The distances on either side the turn is measured over: one reach and two, no more than an
// eighth of the way round a closed path. Over that much of a circle the path turns by 45°, so a
// loop shorter than the reach is not all corners, while a square's or a triangle's corners still are.
let mut spans = [reach, 2.0 * reach];
if closed {
let mut total = 0.0;
for i in 0..n {
total += walk(anchors, closed, (i, true), [f64::INFINITY; 2], reach, 1).1;
}
if !(total.is_finite() && total > 0.0) {
return corners;
}
spans = spans.map(|r| r.min(total / 8.0));
}
for (i, flag) in corners.iter_mut().enumerate() {
if !closed && (i == 0 || i == n - 1) {
continue;
}
let (prev, a, next) = (anchors[(i + n - 1) % n], anchors[i], anchors[(i + 1) % n]);
let arrive = [a.p - a.h_in, a.p - prev.h_out, a.p - prev.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let leave = [a.h_out - a.p, next.h_in - a.p, next.p - a.p].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
if !turn_between(arrive, leave).is_some_and(|t| t > SMOOTH_CORNER_DEG) {
continue;
}
let [Some(back_near), Some(back_far)] = walk(anchors, closed, (i, false), spans, reach, MAX_CORNER_WALK).0 else { continue };
let [Some(ahead_near), Some(ahead_far)] = walk(anchors, closed, (i, true), spans, reach, MAX_CORNER_WALK).0 else { continue };
*flag = [(back_near, ahead_near, spans[0]), (back_far, ahead_far, spans[1])]
.into_iter()
.all(|(back, ahead, r)| r <= 0.0 || turn_between(a.p - back, ahead - a.p).is_some_and(|t| t > SMOOTH_CORNER_DEG));
}
corners
}
/// Most segments [`walk`] passes from an anchor before it stops, which bounds the work for each
/// anchor on a path of very many very short segments.
const MAX_CORNER_WALK: usize = 256;
/// A walk along the path `anchors` from anchor `from.0`, ahead when `from.1` and back otherwise,
/// past no more than `segments` segments, measured along the lines between each curved segment's
/// points at [`corner_places`]. It gives the points at the distances `to` (in order, the nearer
/// first), an open path's end for one beyond the end, and `None` for one it did not reach within
/// `segments` segments, and the length it walked. Both points are `None` when it meets a length that
/// is not a number or is too large to add, and the length is then infinite.
fn walk(anchors: &[Anchor], closed: bool, from: (usize, bool), to: [f64; 2], reach: f64, segments: usize) -> ([Option<Point>; 2], f64) {
let (n, forward) = (anchors.len(), from.1);
let Some(mut here) = anchors.get(from.0).map(|a| a.p) else { return ([None; 2], 0.0) };
let (mut at, mut gone) = (from.0, 0.0);
let mut found: [Option<Point>; 2] = [None; 2];
let mut at_end = false;
'segments: for _ in 0..segments {
let next = match (forward, closed) {
(true, _) if at + 1 < n => at + 1,
(true, true) => 0,
(false, _) if at > 0 => at - 1,
(false, true) => n - 1,
_ => {
at_end = true;
break;
}
};
let (a, b) = (anchors[at], anchors[next]);
let c = if forward { CubicBez::new(a.p, a.h_out, b.h_in, b.p) } else { CubicBez::new(a.p, a.h_in, b.h_out, b.p) };
let places = if c.p1 == c.p0 && c.p2 == c.p3 { vec![1.0] } else { corner_places(c, reach) };
for u in places {
let q = if u >= 1.0 { c.p3 } else { c.eval(u) };
let d = here.distance(q);
if !(d.is_finite() && (gone + d).is_finite()) {
return ([None; 2], f64::INFINITY);
}
for (slot, &dist) in found.iter_mut().zip(&to) {
if slot.is_none() && gone + d >= dist {
let t = if d > 0.0 { ((dist - gone) / d).clamp(0.0, 1.0) } else { 1.0 };
*slot = Some(here.lerp(q, t));
}
}
gone += d;
here = q;
if found.iter().all(Option::is_some) {
break 'segments;
}
}
at = next;
}
// An open path that ends after the last segment walked ends there too.
if !closed && at == if forward { n - 1 } else { 0 } {
at_end = true;
}
(found.map(|p| p.or(at_end.then_some(here))), gone)
}
/// Whether `a` and `b` are the same anchors, to within a rounding error.
fn same_anchors(a: &[Anchor], b: &[Anchor]) -> bool {
let near = |p: Point, q: Point| p.distance(q) <= 1e-9;
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| near(x.p, y.p) && near(x.h_in, y.h_in) && near(x.h_out, y.h_out))
}
/// [`refit_run`] of the open run `anchors` cut at its anchors marked in `corners`: each part between
/// two corners is smoothed and refitted on its own, so each corner keeps its place and the direction
/// the path arrives and leaves along. `free` applies to the run's first and last anchors only.
fn refit_split(anchors: &[Anchor], corners: &[bool], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<Anchor> {
let last = anchors.len().saturating_sub(1);
let mut cuts: Vec<usize> = (1..last).filter(|&i| corners.get(i).copied().unwrap_or(false)).collect();
if cuts.is_empty() {
return refit_run(anchors, tol, sigma, free);
}
cuts.insert(0, 0);
cuts.push(last);
let mut out: Vec<Anchor> = Vec::with_capacity(anchors.len());
for w in cuts.windows(2) {
let (a, b) = (w[0], w[1]);
let part = refit_run(&anchors[a..=b], tol, sigma, [free[0] && a == 0, free[1] && b == last]);
match out.pop() {
// The corner ends one part and starts the next: it keeps its place, and takes the handle
// in from the part before and the handle out from the part after.
Some(end) => {
let mut rest = part.into_iter();
if let Some(start) = rest.next() {
out.push(Anchor::with_handles(anchors[a].p, end.h_in, start.h_out));
}
out.extend(rest);
}
None => out.extend(part),
}
}
out
}
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
/// smoothing moved it, keeping a corner only where the path turns back on itself. `free` says whether
/// smoothing moved it. The tool cuts the path at its corners first ([`smooth_corners`]), so within a
/// part the refit keeps a corner only where the path turns back on itself. `free` says whether
/// the start and the end of the stretch refitted are ends of an open path, whose direction then
/// follows the smoothed path within the reach rather than the first or last segment.
fn refit_options(tol: f64, sigma: f64, free: [bool; 2]) -> SimplifyOptions {
@@ -49,6 +277,84 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
out
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
/// instead of at a new one split in beside it.
const START_SNAP: f64 = 1e-3;
/// Distance (points) within which two points of a smoothed closed path count as equally near its
/// old start.
const START_TIE: f64 = 1e-6;
/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of
/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place
/// when there is none.
fn place_along(orig: &SubPath, p: Point) -> (usize, f64) {
let mut best: Option<(f64, usize, f64)> = None;
for j in 0..orig.anchors.len() {
let hit = orig.segment(j).nearest(p, 1e-9);
if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) {
best = Some((hit.distance_sq, j, hit.t));
}
}
best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t))
}
/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new
/// anchor split into the segment there, which leaves the outline as it is. Of points equally near
/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used,
/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point,
/// is returned as it is.
fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath {
let n = sp.anchors.len();
if !sp.closed || n < 2 {
return sp;
}
// (distance, place along `orig` once a tie needs it, segment of `sp`, parameter)
type Best = (f64, Option<(usize, f64)>, usize, f64);
let mut best: Option<Best> = None;
for i in 0..n {
let c = sp.segment(i);
let hit = c.nearest(start, 1e-9);
if !hit.distance_sq.is_finite() || !hit.t.is_finite() {
continue;
}
let d = hit.distance_sq.sqrt();
match &mut best {
None => best = Some((d, None, i, hit.t)),
Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => {
let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt)));
let place = place_along(orig, c.eval(hit.t));
if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) {
best = Some((d, Some(place), i, hit.t));
}
}
Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)),
Some(_) => {}
}
}
let Some((_, _, i, t)) = best else { return sp };
let c = sp.segment(i);
let at = c.eval(t);
let first = if at.distance(c.p0) <= START_SNAP {
i
} else if at.distance(c.p3) <= START_SNAP {
(i + 1) % n
} else {
let mid = if sp.segment_is_line(i) {
Anchor::corner(at)
} else {
let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0));
sp.anchors[i].h_out = l.p1;
sp.anchors[(i + 1) % n].h_in = r.p2;
Anchor::with_handles(at, l.p2, r.p1)
};
sp.anchors.insert(i + 1, mid);
i + 1
};
sp.anchors.rotate_left(first);
sp
}
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
@@ -226,6 +532,9 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
(out, marked)
}
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
/// that anchor's place (VectorCraft's own rule).
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
if sp.anchors.len() < 2 {
return None;
@@ -238,10 +547,33 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return None;
}
if sp.closed {
let start = sp.anchors[0].p;
let Some(k) = marked.iter().position(|m| !m) else {
// Everything is in range: smooth the whole closed path, across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next();
let corners = smooth_corners(&sp.anchors, true, radius);
let Some(c) = corners.iter().position(|c| *c) else {
// Everything is in range and nothing is a corner: smooth the whole closed path,
// across its start too.
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma, [false; 2]));
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
};
// Cut the path open at a corner, which then ends the last part as well as starting the first.
let mut open = sp.anchors.clone();
open.rotate_left(c);
let mut cut = corners;
cut.rotate_left(c);
open.push(open[0]);
cut.push(true);
let mut res = refit_split(&open, &cut, tol, sigma, [false; 2]);
if same_anchors(&res, &open) {
return None;
}
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
*r0 = Anchor::with_handles(r0.p, l.h_in, r0.h_out);
}
// The path starts where it did when the refit keeps an anchor there, and otherwise at its
// point nearest there.
return Some(start_nearest(SubPath::new(res, true), start, sp));
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
let mut open = sp.clone();
@@ -251,14 +583,20 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
open.anchors.push(open.anchors[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, false);
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open.anchors) {
return None;
}
let l = res.pop()?;
if let Some(r0) = res.first_mut() {
r0.h_in = l.h_in;
}
return Some(SubPath::new(res, true));
// With k = 0 the first anchor is out of reach and still starts the result.
let res = SubPath::new(res, true);
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
}
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma, true), false))
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
@@ -292,8 +630,10 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
/// to it stays as it was (#1512). With `open`, `anchors` are an open path, and the curve at its first
/// or last anchor turns with the smoothing when a run's refit reaches that anchor; a run's other ends,
/// and those of the open run a closed path is cut into, keep their direction.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, open: bool) -> Vec<Anchor> {
/// and those of the open run a closed path is cut into, keep their direction. Each run keeps its
/// corners ([`smooth_corners`] within `radius`, the tool's reach, measured within the run), and a run
/// whose refit changes nothing stays as it was.
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64, radius: f64, open: bool) -> Vec<Anchor> {
let n = anchors.len();
let mut runs = vec![];
let mut i = 0;
@@ -334,7 +674,11 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
}
let free = [open && lo == 0 && head.is_none(), open && hi == n - 1 && tail.is_none()];
let new = refit_run(&piece, tol, sigma, free);
let corners = smooth_corners(&piece, false, radius);
let new = refit_split(&piece, &corners, tol, sigma, free);
if same_anchors(&new, &piece) {
continue;
}
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
}
out
@@ -621,6 +965,89 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
mod tests {
use super::*;
/// A closed ring of four smooth anchors round (100, 100) with radius 50.
fn ring() -> SubPath {
let k = 0.5523 * 50.0;
let a = |x: f64, y: f64, dx: f64, dy: f64| Anchor::with_handles(Point::new(x, y), Point::new(x - dx, y - dy), Point::new(x + dx, y + dy));
SubPath::new(vec![a(150.0, 100.0, 0.0, k), a(100.0, 150.0, -k, 0.0), a(50.0, 100.0, 0.0, -k), a(100.0, 50.0, k, 0.0)], true)
}
/// A start between two anchors of a curve splits that curve there into two that trace it, and the
/// new anchor comes first.
#[test]
fn start_nearest_splits_a_curve_where_it_passes_the_start() {
let sp = ring();
let old = sp.segment(0);
let start = old.eval(0.3) + (old.eval(0.3) - Point::new(100.0, 100.0)) * 0.1;
let out = start_nearest(sp.clone(), start, &sp);
assert!(out.closed && out.anchors.len() == 5, "{out:?}");
let t = old.nearest(start, 1e-9).t;
assert!(out.anchors[0].p.distance(old.eval(t)) < 1e-9, "{out:?}");
let (head, rest) = (out.segment(4), out.segment(0));
for k in 0..=8 {
let u = f64::from(k) / 8.0;
assert!(head.eval(u).distance(old.eval(t * u)) < 1e-9);
assert!(rest.eval(u).distance(old.eval(t + (1.0 - t) * u)) < 1e-9);
}
for i in 1..4 {
assert_eq!(out.segment(i), sp.segment(i), "segment {i} stays");
}
}
/// A start within [`START_SNAP`] of an anchor starts the ring at that anchor, with no anchor added.
#[test]
fn start_nearest_starts_at_an_anchor_near_the_start() {
let sp = ring();
let out = start_nearest(sp.clone(), Point::new(50.0, 100.0 + START_SNAP / 2.0), &sp);
let mut want = sp.anchors.clone();
want.rotate_left(2);
assert_eq!(out.anchors, want);
}
/// A start on a straight side of a triangle adds a corner point there without handles, and the
/// sides stay straight.
#[test]
fn start_nearest_splits_a_line_with_a_corner_point() {
let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(50.0, 80.0)], true);
let out = start_nearest(sp.clone(), Point::new(40.0, -5.0), &sp);
let want: Vec<Point> = [(40.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)).to_vec();
assert!(out.anchors.len() == 4 && out.anchors.iter().zip(&want).all(|(a, w)| a.p.distance(*w) < 1e-9), "{out:?}");
assert!((0..4).all(|i| out.segment_is_line(i)), "{out:?}");
}
/// A ring whose last anchor lies on its first keeps its first anchor first, and gets no third
/// anchor at that place.
#[test]
fn start_nearest_keeps_the_first_of_two_anchors_on_one_place() {
let p = [(0.0, 0.0), (100.0, 0.0), (50.0, 80.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y));
let sp = SubPath::polyline(&p, true);
assert_eq!(start_nearest(sp.clone(), p[0], &sp), sp);
}
/// Of points equally near the start, the one earliest along the path before smoothing from its
/// first anchor comes first, whatever the smoothed path's order. The center of a square is equally
/// near the middle of each side. The square before smoothing starts at (-50, -50), so the middle
/// of its first side, (0, -50), comes first, though the smoothed copy starts at (50, 50).
#[test]
fn start_nearest_breaks_a_tie_by_the_order_before_smoothing() {
let p = [(-50.0, -50.0), (50.0, -50.0), (50.0, 50.0), (-50.0, 50.0)].map(|(x, y)| Point::new(x, y));
let orig = SubPath::polyline(&p, true);
let mut sp = orig.clone();
sp.anchors.rotate_left(2);
let out = start_nearest(sp, Point::new(0.0, 0.0), &orig);
assert!(out.closed && out.anchors.len() == 5, "{out:?}");
assert!(out.anchors[0].p.distance(Point::new(0.0, -50.0)) < 1e-9, "{out:?}");
assert!(out.anchors[1].p.distance(p[1]) < 1e-9, "{out:?}");
}
/// An open path, and a start that is not a number, leave the path as it is.
#[test]
fn start_nearest_leaves_an_open_path_or_a_start_without_a_place() {
let open = SubPath { closed: false, ..ring() };
assert_eq!(start_nearest(open.clone(), Point::new(100.0, 50.0), &ring()), open);
assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring());
}
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
/// pieces than the budget it is given, and a search with none left gives one sample.
#[test]
@@ -649,4 +1076,123 @@ mod tests {
assert_eq!(drag_stretches(&one), vec![0]);
assert!((dist_to_stretches(&one, &[0], Point::new(13.0, 14.0)) - 5.0).abs() < 1e-12);
}
fn polyline(pts: &[(f64, f64)]) -> Vec<Anchor> {
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
}
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
/// are its corners, and an open path's ends never are.
#[test]
fn corners_are_found_only_where_the_path_turns_at_and_around_an_anchor() {
assert_eq!(smooth_corners(&polyline(&[(5.0, 5.0); 4]), false, 12.0), vec![false; 4]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (f64::NAN, 1.0), (10.0, 0.0)]), false, 12.0), vec![false; 3]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (1e308, 0.0), (1e308, 1e308), (-1e308, 0.0)]), true, 12.0), vec![false; 4]);
let zigzag: Vec<(f64, f64)> = (0..=100_000).map(|i| (f64::from(i), f64::from(i % 2))).collect();
assert!(!smooth_corners(&polyline(&zigzag), false, 12.0).contains(&true));
let square = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert_eq!(smooth_corners(&square, true, 12.0), vec![true; 4]);
assert_eq!(smooth_corners(&square, false, 12.0), vec![false, true, true, false]);
assert_eq!(smooth_corners(&square, false, 0.0), vec![false, true, true, false], "with no reach the turn at the anchor decides");
assert_eq!(smooth_corners(&square[..2], false, 12.0), vec![false; 2]);
}
/// A 90° bump 400 pt high cut into 1 pt segments, between two long straight segments: with a reach
/// of 10 pt its top is a corner, and with a reach of 1,000 pt, where the walk passes more segments
/// than it measures before it gets that far, its top is not one, as the path turns by about 51°
/// over that reach.
#[test]
fn a_corner_is_not_kept_where_the_reach_is_not_measured() {
let side = 400.0 * std::f64::consts::SQRT_2;
let steps = side.ceil() as usize;
let mut pts = vec![(-3000.0, 0.0)];
pts.extend((0..steps).map(|j| {
let f = j as f64 / steps as f64;
(-400.0 + 400.0 * f, 400.0 * f)
}));
pts.extend((0..=steps).map(|j| {
let f = j as f64 / steps as f64;
(400.0 * f, 400.0 - 400.0 * f)
}));
pts.push((3000.0, 0.0));
let anchors = polyline(&pts);
let top = steps + 1;
assert_eq!(anchors[top].p, Point::new(0.0, 400.0));
assert!(smooth_corners(&anchors, false, 10.0)[top]);
assert!(!smooth_corners(&anchors, false, 1000.0)[top]);
}
/// A 60° corner between two curved segments 1,000 pt long is found at a reach of 2 pt as it is
/// when each segment is cut into a thousand pieces: the turns over the reach are measured along the
/// curve near the anchor, not along a chord much longer than the reach.
#[test]
fn a_corner_between_long_curves_is_measured_along_them() {
// The curves arrive along x and leave at 60° to it, each bending away from the other.
let d = kurbo::Vec2::from_angle(-60f64.to_radians());
let side = kurbo::Vec2::new(-d.y, d.x) * 1000.0;
let v = Point::new(0.0, 0.0);
let a = Anchor::with_handles(Point::new(-1000.0, 1000.0), Point::new(-1000.0, 1000.0), Point::new(-300.0, 1000.0));
let b = Anchor::with_handles(v, Point::new(-300.0, 0.0), v + d * 300.0);
let end = v + d * 1000.0 + side;
let c = Anchor::with_handles(end, v + d * 300.0 + side, end);
let long = [a, b, c];
let fine: Vec<Anchor> = {
let sp = SubPath::new(long.to_vec(), false);
let mut pts = vec![];
for i in 0..2 {
let s = sp.segment(i);
for j in 0..1000 {
let p = s.subsegment(f64::from(j) / 1000.0..f64::from(j + 1) / 1000.0);
if j == 0 && i == 0 {
pts.push(Anchor::with_handles(p.p0, p.p0, p.p1));
} else if let Some(last) = pts.last_mut() {
*last = Anchor::with_handles(last.p, last.h_in, p.p1);
}
pts.push(Anchor::with_handles(p.p3, p.p2, p.p3));
}
}
pts
};
let at_v = |anchors: &[Anchor]| {
let corners = smooth_corners(anchors, false, 2.0);
anchors.iter().zip(corners).find(|(x, _)| x.p == v).map(|(_, c)| c)
};
assert_eq!(at_v(&fine), Some(true), "cut finely, the anchor is a corner");
assert_eq!(at_v(&long), Some(true));
}
/// A line that meets a curve leaving with no handle, turning by 58° at the anchor and by about
/// 57.53° over twice a reach of 0.02 pt: the anchor is a corner, measured either way along the path,
/// as the stretch measured finely near the anchor covers twice the reach along the curve.
#[test]
fn a_corner_next_to_a_curve_without_a_handle_is_kept() {
let at = 58f64.to_radians();
let prev = Anchor::corner(Point::new(-100.0 * at.cos(), -100.0 * at.sin()));
let v = Point::new(0.0, 0.0);
let a = Anchor::with_handles(v, v, v);
let end = Point::new(600.0, 600.0);
let next = Anchor::with_handles(end, Point::new(200.0, 0.0), end);
assert_eq!(smooth_corners(&[prev, a, next], false, 0.02), vec![false, true, false]);
let back = |x: Anchor| Anchor::with_handles(x.p, x.h_out, x.h_in);
assert_eq!(smooth_corners(&[back(next), back(a), back(prev)], false, 0.02), vec![false, true, false]);
}
/// A jagged closed path whose length is less than twice the reach: its jags are not corners,
/// while a triangle that small keeps its three.
#[test]
fn a_small_jagged_loop_has_no_corners() {
let ring: Vec<(f64, f64)> = (0..16)
.map(|i| {
let (a, r) = (f64::from(i) / 16.0 * std::f64::consts::TAU, if i % 2 == 0 { 3.0 } else { 2.0 });
(r * a.cos(), r * a.sin())
})
.collect();
let jags = polyline(&ring);
let sp = SubPath::new(jags.clone(), true);
assert!(subpath_len(&sp) < 24.0);
assert!(smooth_corners(&jags, true, 1e-6).iter().all(|c| *c), "each jag turns sharply at its anchor");
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
}
}
+23 -18
View File
@@ -808,11 +808,11 @@ fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
let created = date_param(p, "created", C)?;
let st = s.doc()?;
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
let chosen = match p.get("index") {
None | Some(Value::Null) => None,
Some(v) => {
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
let chosen = match super::index_opt(p, "index", C)? {
None => None,
Some(row) => {
let v = &p["index"];
Some(st.history.state(&st.doc, row).ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
}
};
settle_interaction(s)?;
@@ -1276,23 +1276,28 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
/// ones); `None` when none is named. A named index that is not an artboard of the document, a
/// repeated one or an empty list is an error.
/// ones); `None` when none is named. A named value that is not a whole number (null included), a
/// named index that is not an artboard of the document, a repeated one or an empty list is an
/// error; every value is checked for its form before any is checked against the artboards.
fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Vec<usize>>> {
let n = s.doc()?.doc.artboards.len();
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
let single = match p.get("artboard") {
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
None => None,
};
let listed = match p.get("artboards") {
let single = p.get("artboard").map(|v| v.as_u64().map(index).ok_or_else(|| bad(cmd, "`artboard` must be a whole number"))).transpose()?;
let entries = match p.get("artboards") {
Some(v) => {
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
let mut all = list
.iter()
.map(one)
.collect::<Option<Vec<usize>>>()
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
let all = list.iter().map(|i| i.as_u64().map(index)).collect::<Option<Vec<usize>>>();
Some(all.ok_or_else(|| bad(cmd, "`artboards` must contain whole numbers"))?)
}
None => None,
};
if single.is_some_and(|i| i >= n) {
return Err(bad(cmd, "`artboard` must be the index of an artboard of the document"));
}
let listed = match entries {
Some(mut all) => {
if all.iter().any(|i| *i >= n) {
return Err(bad(cmd, "`artboards` names an artboard the document does not have"));
}
all.sort_unstable();
if all.windows(2).any(|w| w[0] == w[1]) {
return Err(bad(cmd, "`artboards` names an artboard twice"));
+4 -1
View File
@@ -66,7 +66,10 @@ 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, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
pub use encode::{
ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, export_art_bounds,
note_texts,
};
pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
+192 -13
View File
@@ -12,6 +12,8 @@ use serde_json::json;
use super::super::{Result, Session, bad};
#[cfg(not(target_arch = "wasm32"))]
use super::super::{check_switches, find_command, switch_or, text_param};
#[cfg(not(target_arch = "wasm32"))]
use crate::EngineError;
#[cfg(target_arch = "wasm32")]
pub(super) fn action_batch(_: &mut Session, _: &Value) -> Result<Value> {
@@ -58,6 +60,10 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
if id == "command.batch" || id == "action.batch" {
return Err(bad(C, "batches cannot nest"));
}
// `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays.
if id == "prefs.import" {
return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step")));
}
if find_command(id).is_none() {
return Err(bad(
C,
@@ -213,7 +219,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
// open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a
// source file in the destination folder, other than that file's own output, or of a subfolder
// of the destination folder that holds source files.
let steps = filter_steps(run.steps, override_open, false);
let (steps, places) = filter_steps(run.steps, override_open, false);
let run = Run { steps: &steps, ..*run };
let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect();
let mut picker =
@@ -228,7 +234,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run:
let outputs = dataset_output_extensions(&run, doc, &ext);
picker.pick(&base, |stem| output_names(run.dest_folder, stem, &outputs, doc), own.as_deref())
};
match process_one_file(s, &run, path, &ext, pick) {
match process_one_file(s, &run, &places, path, &ext, pick) {
Ok(row) => processed.push(row),
Err(e) => {
failed += 1;
@@ -266,12 +272,12 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
}
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
let steps = filter_steps(run.steps, true, false);
let (steps, places) = filter_steps(run.steps, true, false);
let run = Run { steps: &steps, ..*run };
let mut processed = Vec::new();
let mut failed = 0usize;
for (name, stem) in names.iter().zip(&stems) {
match process_one_dataset(s, &run, name, stem) {
match process_one_dataset(s, &run, &places, name, stem) {
Ok(row) => processed.push(row),
Err(e) => {
failed += 1;
@@ -347,11 +353,13 @@ impl StemPicker {
}
}
/// Drop Open (and optionally Close) steps when the batch supplies the file itself.
/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that
/// stay, and the index of each in `cmds`.
#[cfg(not(target_arch = "wasm32"))]
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value> {
fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) {
cmds.iter()
.filter(|c| {
.enumerate()
.filter(|(_, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
if drop_open && matches!(id, "document.open" | "file.open") {
return false;
@@ -361,14 +369,44 @@ fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> Vec<Value>
}
true
})
.cloned()
.collect()
.map(|(i, c)| (c.clone(), i))
.unzip()
}
/// Plays `commands`, the steps of `run` with their paths rewritten, as one `command.batch`. When a
/// step fails, the error names it by its place in the caller's `commands`, from 1, counting the Open
/// steps the batch skipped (`places` gives the index there of each step of `run`):
/// ``action step 3 (`object.move`) failed: …``. Any other error, such as one about the whole batch,
/// stays as it is.
#[cfg(not(target_arch = "wasm32"))]
fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Value>) -> Result<Value> {
s.execute("command.batch", &json!({"label": run.label, "commands": commands})).map_err(|e| {
let text = e.to_string();
let Some((n, id, reason)) = batch_step_failure(&text) else { return e };
let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id);
match places.get(n) {
Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)),
_ => e,
}
})
}
/// The step number, command id and reason in the error `command.batch` gives when one of its steps
/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error.
#[cfg(not(target_arch = "wasm32"))]
fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> {
let rest = e.strip_prefix("batch step ")?;
let digits = rest.find(|c: char| !c.is_ascii_digit())?;
let n = rest[..digits].parse().ok()?;
let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?;
Some((n, id, reason))
}
#[cfg(not(target_arch = "wasm32"))]
fn process_one_file(
s: &mut Session,
run: &Run<'_>,
places: &[usize],
path: &str,
ext: &str,
stem_for: impl FnOnce(&vectorcraft_doc::Document) -> String,
@@ -376,17 +414,17 @@ fn process_one_file(
s.execute("document.open", &json!({"path": path}))?;
let stem = stem_for(&s.doc()?.doc);
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, &stem, ext);
let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?;
let batch = play_steps(s, run, places, rewritten)?;
// Folder sources open a file per pass: close after Save and Close / Folder.
finish_destination(s, run, &stem, ext, path, true)?;
Ok(json!({"path": path, "result": batch}))
}
#[cfg(not(target_arch = "wasm32"))]
fn process_one_dataset(s: &mut Session, run: &Run<'_>, name: &str, stem: &str) -> Result<Value> {
fn process_one_dataset(s: &mut Session, run: &Run<'_>, places: &[usize], name: &str, stem: &str) -> Result<Value> {
s.execute("dataset.select", &json!({"name": name}))?;
let rewritten = rewrite_paths(run.steps, run.override_save, run.override_export, run.dest_folder, stem, "vectorcraft");
let batch = s.execute("command.batch", &json!({"label": run.label, "commands": rewritten}))?;
let batch = play_steps(s, run, places, rewritten)?;
// Data sets share one open document: write each row out but leave it open for the next.
finish_destination(s, run, stem, "vectorcraft", "", false)?;
Ok(json!({"dataset": name, "result": batch}))
@@ -1454,7 +1492,8 @@ mod tests {
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");
let want =
format!("action step 1 (`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}");
@@ -2224,4 +2263,144 @@ mod tests {
.is_err()
);
}
/// The steps of the step-number tests: an Open the batch skips, a step that works, and one that
/// fails (an Align with nothing selected).
fn open_then_failing_align() -> Value {
json!([
{"command": "document.open", "params": {"path": "/no/such/file.svg"}},
{"command": "object.unlockAll", "params": {}},
{"command": "object.align", "params": {}}
])
}
/// The step a source's error names, after `action step ` and before ` failed: `.
fn named_step(r: &Value, row: usize) -> String {
let e = r["processed"][row]["error"].as_str().unwrap_or_default();
assert!(!e.contains("batch step"), "{r}");
e.strip_prefix("action step ").and_then(|e| e.split_once(" failed: ")).map(|(step, _)| step.to_string()).unwrap_or_else(|| e.to_string())
}
/// A failed step of a folder batch is named by its place in the `commands` sent, from 1, with the
/// Open step that Override Open skips counted; the reason follows unchanged.
#[test]
fn a_folder_batch_error_names_the_step_in_the_commands_sent() {
let src = tmp("step-number-src");
write_svg(&src, "a.svg", "#f00");
write_svg(&src, "b.svg", "#0f0");
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
// `command.batch` itself still numbers its steps from 0.
let reason = s
.execute(
"command.batch",
&json!({"commands": [{"command": "object.unlockAll", "params": {}}, {"command": "object.align", "params": {}}]}),
)
.unwrap_err()
.to_string();
let reason = reason.strip_prefix("batch step 1 (`object.align`) failed: ").unwrap_or_else(|| panic!("{reason}")).to_string();
for (stop, rows) in [(true, 1), (false, 2)] {
let r = s
.execute("action.batch", &json!({"folder": src.to_string_lossy(), "stopOnError": stop, "commands": open_then_failing_align()}))
.unwrap();
assert_eq!(r["failed"], rows, "{r}");
for row in 0..rows {
assert_eq!(r["processed"][row]["error"], format!("action step 3 (`object.align`) failed: {reason}"), "{r}");
}
}
}
/// With Override Open off, a recorded Open step runs, and its failure is named as the first step.
#[test]
fn a_recorded_open_that_fails_is_the_first_step() {
let src = tmp("step-number-open-src");
write_svg(&src, "a.svg", "#f00");
let mut s = Session::new();
let r = s
.execute("action.batch", &json!({"folder": src.to_string_lossy(), "overrideOpen": false, "commands": open_then_failing_align()}))
.unwrap();
assert_eq!(named_step(&r, 0), "1 (`document.open`)", "{r}");
}
/// A data set batch, which always skips Open steps, names a failed step by its place in the
/// `commands` sent for every data set it fails on.
#[test]
fn a_data_set_batch_error_names_the_step_in_the_commands_sent() {
let mut s = with_data_sets(&["Alpha", "Beta"]);
for (stop, rows) in [(true, 1), (false, 2)] {
let r = s.execute("action.batch", &json!({"source": "datasets", "stopOnError": stop, "commands": open_then_failing_align()})).unwrap();
assert_eq!(r["failed"], rows, "{r}");
for row in 0..rows {
assert_eq!(named_step(&r, row), "3 (`object.align`)", "{r}");
}
}
}
/// A recorded export that Override Export points into the destination folder keeps its place in
/// the `commands` sent when it fails.
#[test]
fn a_redirected_export_that_fails_keeps_its_place() {
let src = tmp("step-number-export-src");
write_svg(&src, "a.svg", "#f00");
let dest = tmp("step-number-export-out");
// A file where the export's folder goes, so the export cannot write its files.
std::fs::write(dest.join("a"), "taken").unwrap();
let mut s = Session::new();
let r = s
.execute(
"action.batch",
&json!({
"folder": src.to_string_lossy(),
"destinationFolder": dest.to_string_lossy(),
"commands": [
{"command": "document.open", "params": {"path": "/no/such/file.svg"}},
{"command": "object.unlockAll", "params": {}},
{"command": "document.exportForScreens", "params": {"formats": [{"format": "svg"}]}}
]
}),
)
.unwrap();
assert_eq!(r["failed"], 1, "{r}");
assert_eq!(named_step(&r, 0), "3 (`document.exportForScreens`)", "{r}");
}
/// A source file that does not open, which the batch opens itself, gives the open's own error
/// with no step number.
#[test]
fn a_source_that_does_not_open_names_no_step() {
let src = tmp("step-number-bad-src");
std::fs::write(src.join("a.svg"), "not an svg").unwrap();
let mut s = Session::new();
let r = s.execute("action.batch", &json!({"folder": src.to_string_lossy(), "commands": open_then_failing_align()})).unwrap();
assert_eq!(r["failed"], 1, "{r}");
let e = r["processed"][0]["error"].as_str().unwrap_or_default();
assert!(!e.is_empty() && !e.contains("action step") && !e.contains("batch step"), "{r}");
}
/// A `prefs.import` step, which `command.batch` does not run, is refused before any file opens.
#[test]
fn a_prefs_import_step_is_refused_before_any_file_opens() {
let src = tmp("step-number-prefs-src");
write_svg(&src, "a.svg", "#f00");
let mut s = Session::new();
let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]});
let e = s.execute("action.batch", &p).unwrap_err().to_string();
assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}");
assert!(s.active().is_none(), "no file was opened");
}
/// Only the error `command.batch` gives for a failed step is read as one.
#[test]
fn batch_step_failure_reads_only_a_step_error() {
assert_eq!(batch_step_failure("batch step 12 (`object.move`) failed: no selection"), Some((12, "object.move", "no selection")));
for e in [
"batch step (`object.move`) failed: no selection",
"batch step 99999999999999999999999 (`object.move`) failed: x",
"batch step 1 `object.move` failed: x",
"invalid parameters for `command.batch`: batches cannot nest",
"batch step 1",
] {
assert_eq!(batch_step_failure(e), None, "{e}");
}
}
}
+2 -2
View File
@@ -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; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; 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), maxEditabilit 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; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; 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 art it plots, without placed images, unpainted paths and art at 0% opacity), 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 mod Line truncated
has_doc,
export::export
),
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
[],
None,
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
always,
action_batch::action_batch
),
+140 -5
View File
@@ -2,11 +2,13 @@
//! (unknown keys are ignored, so one params object can carry the options of several formats).
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::Arc;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use vectorcraft_doc::{Artboard, Document};
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
use vectorcraft_geom::Rect;
use vectorcraft_render::AntiAlias;
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
@@ -419,13 +421,15 @@ pub(super) fn use_artboards(cmd: &str, p: &Value) -> Result<Option<bool>> {
/// With `useArtboards: false` in `p`: `doc` without its opacity-mask or symbol editing layer and
/// with one artboard, the bounds of its visible art, and `p` without the artboard choice. `None`
/// when `useArtboards` is absent, null or true. A document with no visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
/// when `useArtboards` is absent, null or true. The objects that `left_out` picks (layers or
/// objects the format leaves out, see [`hidden_nodes`]) are not measured, and a document with no
/// other visible art is refused.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value, left_out: impl Fn(&Node) -> bool) -> Result<Option<(Document, Value)>> {
if use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let doc = &*doc.without_edit_modes();
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let bounds = bounds_without(doc, &left_out).ok_or_else(|| bad(cmd, "nothing to export: the document has no visible art"))?;
let mut q = super::export::without_artboards(p);
if let Some(o) = q.as_object_mut() {
o.remove("useArtboards");
@@ -433,6 +437,107 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
Ok(Some((single_artboard(doc, bounds, "Art"), q)))
}
/// The bounds of the visible art of `doc` that a `format` file of the art's bounds draws, as
/// [`art_page`] measures it with that format's default options: for HP-GL without what a plot
/// leaves out ([`vectorcraft_cad::hpgl::write::plots_nothing`]), for other formats all of it (the
/// non-printing layers a PDF leaves out depend on options chosen after the save panel). `None`
/// when there is none, which such an export refuses.
pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
let doc = &*doc.without_edit_modes();
bounds_without(doc, &|n| format == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n))
}
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
/// an instance can paint its objects, and finds them by their places in the art.
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
// The symbols instances show (the first of each name) that aren't dynamic.
let mut names = HashSet::new();
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
// symbols included.
let mut empty: HashSet<&str> = HashSet::new();
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
empty.insert(&s.name);
}
let left_out =
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
let layers = hidden_nodes(&doc.layers, left_out);
let symbols: Vec<(usize, Arc<Node>)> = shown
.iter()
.filter(|(_, s)| !empty.contains(s.name.as_str()))
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
.collect();
if layers.is_none() && symbols.is_empty() {
return vectorcraft_render::encode::art_bounds(doc);
}
let mut d = doc.clone();
if let Some(layers) = layers {
d.layers = layers;
}
for (i, art) in symbols {
if let Some(s) = d.symbols.get_mut(i) {
s.art = art;
}
}
vectorcraft_render::encode::art_bounds(&d)
}
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
/// layer or a group holding only such objects (its clipping path among them when it clips). A
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
/// of these unless it is hidden or picked.
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
!n.visible
|| left_out(n)
|| !has_effects(n)
&& n.extras().shaper.is_none()
&& match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
_ => false,
}
}
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
/// take part in.
fn has_effects(n: &Node) -> bool {
n.appearance.effects.iter().any(|e| e.visible) || n.appearance.items.iter().any(|i| i.visible())
}
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
/// effects, fills or strokes of its own keep all they hold.
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
if has_effects(n) || n.extras().shaper.is_some() {
return None;
}
let mut changed = false;
let kept: Vec<Arc<Node>> = children
.iter()
.enumerate()
.filter_map(|(i, c)| {
if left_out(c) && !(*clip && i == 0) {
changed = true;
return None;
}
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
})
.collect();
changed.then(|| {
let mut new = (**n).clone();
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
*children = kept;
}
Arc::new(new)
})
}
/// The `rect` param of a raster export: `[x, y, width, height]` in points, y down. `None` when
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
@@ -481,6 +586,35 @@ pub(crate) fn with_single_artboard(mut d: Document, rect: Rect, name: &str) -> D
d
}
/// `nodes` with the visible objects that `left_out` picks hidden, in layers, sublayers and groups
/// that don't clip, at any depth (what an object it picks holds is not looked at); `None` when it
/// picks none of them. Clipping layers are looked in too, as their sublayers can be picked.
pub(super) fn hidden_nodes(nodes: &[Arc<Node>], left_out: &dyn Fn(&Node) -> bool) -> Option<Vec<Arc<Node>>> {
let mut out: Option<Vec<Arc<Node>>> = None;
for (i, l) in nodes.iter().enumerate() {
let new = if left_out(l) {
l.visible.then(|| {
let mut n = (**l).clone();
n.visible = false;
Arc::new(n)
})
} else {
let (NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false }) = &l.kind else { continue };
hidden_nodes(children, left_out).map(|c| {
let mut n = (**l).clone();
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut n.kind {
*children = c;
}
Arc::new(n)
})
};
if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| nodes.to_vec()).get_mut(i)?, new))) {
*slot.0 = slot.1;
}
}
out
}
fn boards<T>(r: std::result::Result<T, String>) -> Result<T> {
r.map_err(|e| bad(C, e))
}
@@ -636,8 +770,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
{
return Ok(enc);
}
let left_out = |n: &Node| f.id == "hpgl" && vectorcraft_cad::hpgl::write::plots_nothing(doc, n);
if use_artboards == Some(false)
&& let Some((art, q)) = art_page(C, doc, p)?
&& let Some((art, q)) = art_page(C, doc, p, left_out)?
{
return encode_files(&art, f, &q);
}
+3 -2
View File
@@ -550,9 +550,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// Optical Margin Alignment setting and writing direction. When that changes the direction of a
// frame of a restored document, the story flows through that frame's thread again. Threaded
// frames keep their size: Auto Size is off for them. The story is laid out in the document's
// own composite fonts.
// own composite fonts, and type naming one the document does not define flows as in a missing
// font, also when the document defines none.
let fonts = if doc.text_threads.is_empty() { Default::default() } else { doc.composite_fonts.clone() };
let lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&fonts);
let lent = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&fonts);
if !doc.text_threads.is_empty() && !restored {
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
} else if !doc.text_threads.is_empty() {
+15 -25
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CM Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all Line truncated
has_doc,
export_pdf
),
@@ -289,7 +289,7 @@ pub const EDITING_NEEDS_THE_ARTBOARDS: &str =
/// Editing on, the notes end with [`EDITING_NEEDS_THE_ARTBOARDS`]. `None` when `p` asks for the
/// artboards.
pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Vec<u8>, Vec<Note>)>> {
let Some((art, mut q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let Some((art, mut q)) = art_page(cmd, doc, p)? else { return Ok(None) };
let left_out = settings(cmd, &q)?.preserve_editing;
if left_out && let Some(o) = q.as_object_mut() {
o.insert("preserveEditing".into(), json!(false));
@@ -301,6 +301,18 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Op
Ok(Some((bytes, notes)))
}
/// [`super::encode::art_page`] of a PDF with the options in `p`: the bounds of the visible art on
/// the layers its pages draw, without the non-printing ones unless `includeNonPrinting` or
/// `createLayers` keeps them.
pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(Document, Value)>> {
if super::encode::use_artboards(cmd, p)? != Some(false) {
return Ok(None);
}
let set = settings(cmd, p)?;
let keeps = set.include_non_printing || set.create_layers;
super::encode::art_page(cmd, doc, p, |l| !keeps && matches!(l.kind, NodeKind::Layer { printable: false, .. }))
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`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";
@@ -477,29 +489,7 @@ fn thumbnails(doc: &Document, opts: &PdfOptions) -> std::result::Result<Vec<Thum
/// `layers` with the non-printing layers among them (at any depth) hidden; `None` when there are
/// none.
fn without_non_printing(layers: &[Arc<Node>]) -> Option<Vec<Arc<Node>>> {
let mut out: Option<Vec<Arc<Node>>> = None;
for (i, l) in layers.iter().enumerate() {
let NodeKind::Layer { printable, children, .. } = &l.kind else { continue };
let new = if !printable {
l.visible.then(|| {
let mut n = (**l).clone();
n.visible = false;
Arc::new(n)
})
} else {
without_non_printing(children).map(|c| {
let mut n = (**l).clone();
if let NodeKind::Layer { children, .. } = &mut n.kind {
*children = c;
}
Arc::new(n)
})
};
if let Some(slot) = new.and_then(|new| Some((out.get_or_insert_with(|| layers.to_vec()).get_mut(i)?, new))) {
*slot.0 = slot.1;
}
}
out
super::encode::hidden_nodes(layers, &|l| matches!(l.kind, NodeKind::Layer { printable: false, .. }))
}
fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
+15 -6
View File
@@ -757,8 +757,9 @@ pub const AI_EDITING_NEEDS_THE_ARTBOARDS: &str =
pub const ART_PAGE_NEEDS_PDF: &str = "pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false";
/// With `useArtboards: false` in `p`: the PDF-compatible `.ai` file of one page, the bounds of
/// `doc`'s visible art ([`super::encode::art_page`]). It carries neither the native document nor
/// the editing copy for other apps, and its notes end with [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `doc`'s visible art on the layers its pages draw ([`super::pdf::art_page`]). It carries neither
/// the native document nor the editing copy for other apps, and its notes end with
/// [`AI_EDITING_NEEDS_THE_ARTBOARDS`].
/// `pdfCompatible: false` is refused. `None` when `p` asks for the artboards or for a legacy
/// version 7 `.ai` file.
pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result<Option<Encoded>> {
@@ -768,7 +769,7 @@ pub(super) fn encode_ai_art_page(cmd: &str, f: &Format, doc: &Document, p: &Valu
if !bool_or(p, "pdfCompatible", true) {
return Err(bad(cmd, ART_PAGE_NEEDS_PDF));
}
let Some((art, q)) = super::encode::art_page(cmd, doc, p)? else { return Ok(None) };
let Some((art, q)) = super::pdf::art_page(cmd, doc, &ai_pdf_params(p, false))? else { return Ok(None) };
let mut enc = encode_ai_pages(cmd, f, &art, &q, false)?;
enc.setting_notes.push(AI_EDITING_NEEDS_THE_ARTBOARDS.to_string());
Ok(Some(enc))
@@ -784,9 +785,10 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
encode_ai_pages(cmd, f, doc, p, true)
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
/// `p` with the PDF options a `.ai` file is written with: Preserve Editing when `editing` is true,
/// layers unless a standard decides, long pages with a `UserUnit`, and `compress` as
/// `compression.compressText`.
fn ai_pdf_params(p: &Value, editing: bool) -> Value {
let mut params = if p.is_object() { p.clone() } else { json!({}) };
if let Some(o) = params.as_object_mut() {
o.insert("preserveEditing".into(), json!(editing));
@@ -805,6 +807,13 @@ fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bo
}
}
}
params
}
/// [`encode_ai`] of a `.ai` file with or without PDF content, carrying the native document and
/// the editing copy for other apps when `editing` is true, and neither otherwise.
fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bool) -> Result<Encoded> {
let params = ai_pdf_params(p, editing);
let pdf_compatible = bool_or(&params, "pdfCompatible", true);
let f = &if pdf_compatible { *f } else { without_pdf(f) };
let native_options = super::native::ai_options(cmd, f, doc, &params)?;
+60 -2
View File
@@ -424,8 +424,8 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{xa}0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n"
)
};
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a gradient fill,
// which isn't read, so it is left out rather than listed with no paint.
// Styles of one paint (`/SimpleStyle`): a red 2 pt stroke and no fill, and a fill with a gradient
// the file doesn't define, which is left out rather than listed with no paint.
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
let styles = format!(
"%AI9_BeginArtStyles\n{}{}{}{}{}%AI9_EndArtStyles\n\
@@ -465,6 +465,64 @@ fn a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles() {
assert_eq!(styles, [("Red", 1), ("Green", 2), ("Blue", 3), ("Red outline", 4)], "{r}");
}
/// A `.ai` graphic style library's styles that paint with one of the file's gradients by name (a
/// fill style's, and the fill or stroke of a style of one paint) load with that gradient at the
/// style's angle, fitted to the bounds of each object the style is applied to; one naming a gradient
/// the file doesn't define is left out.
#[test]
fn graphic_styles_in_a_ai_library_that_paint_with_a_named_gradient_load_with_it() {
let gradient =
"%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 0 1 0 2 1 6 50 0 Bs\n%_0 0 0 0 1 1 1 2 1 6 50 100 Bs\nBD\n%AI5_EndGradient\n";
let band = "/KnownStyle :\n(Sky band) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n\
0 Bb\n2 (Sky) 0 0 45 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n";
let one_paint = |name: &str, paint: &str| format!("/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n{paint}/Paint ;\n/Def ;\n");
let styles = format!(
"%AI9_BeginArtStyles\n{band}{}{}{}%AI9_EndArtStyles\n\
%AI9_BeginArtStyleList\n(Sky band)\n(Sky fill)\n(Sky outline)\n(Dusk fill)\n%AI9_EndArtStyleList\n",
one_paint("Sky fill", "0 O\n0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n"),
one_paint("Sky outline", "0 R\n0 J 0 j 2 w 10 M []0 d\n1 Bb\n2 (Sky) 0 0 90 100 1 0 0 1 0 0 1 Bg\n0 BB\n1 0 Xd\n"),
one_paint("Dusk fill", "0 O\n0 Bb\n2 (Dusk) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n")
);
// A palette with the gradient's swatch, so the document opened from the file shows its gradient.
let palette = INKS_PALETTE.replace("0 0 Pb\n", "0 0 Pb\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n");
let data = ai::editing_data(200.0, 100.0, &format!("{gradient}{palette}{styles}"));
let file = ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f");
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&file), "name": "skies.ai"});
let r = s.execute("graphicStyle.loadLibrary", &p).unwrap();
let library = r["library"].clone();
let lib = s.execute("graphicStyle.library", &json!({"library": library})).unwrap();
let names: Vec<&str> = lib["styles"].as_array().unwrap().iter().map(|g| g["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Sky band", "Sky fill", "Sky outline"], "{lib}");
// The file's gradient, as the document opened from it has its swatch.
open(&mut s, "skies.ai", &file, json!({})).unwrap();
let sky = match s.doc().unwrap().doc.swatch("Sky").map(|w| w.paint.clone()) {
Some(vectorcraft_color::Paint::Gradient(g)) => g.gradient,
other => panic!("{other:?}"),
};
// Applied to a small and a large rectangle, each gradient is fitted to the rectangle it paints.
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
for (style, (x, size)) in [("Sky band", (10, 20)), ("Sky fill", (40, 200)), ("Sky outline", (10, 120))] {
let rect = json!({"x": x, "y": x, "width": size, "height": size / 2});
let id = NodeId(s.execute("shape.rectangle", &rect).unwrap()["id"].as_u64().unwrap());
let r = s.execute("graphicStyle.addFromLibrary", &json!({"library": library, "names": [style], "apply": true, "ids": [id.0]})).unwrap();
assert_eq!(r["added"], json!([style]), "{r}");
let look = &s.doc().unwrap().doc.node(id).unwrap().appearance;
let (paint, angle, stroked) = match style {
"Sky outline" => (look.stroke().map(|st| &st.paint), 90.0, true),
"Sky band" => (look.fill().map(|f| &f.paint), 45.0, false),
_ => (look.fill().map(|f| &f.paint), 0.0, false),
};
let Some(vectorcraft_color::Paint::Gradient(g)) = paint else { panic!("{style}: {look:?}") };
assert_eq!((&g.gradient, g.geom, g.angle), (&sky, None, angle), "{style}");
assert_eq!(look.stroke().is_some(), stroked, "{style}: {look:?}");
if stroked {
assert!(look.fill().is_none() && look.stroke().is_some_and(|st| st.width == 2.0), "{look:?}");
}
}
}
/// A `.ai` symbol library (symbols and their list, no layers) opens with its symbols, and Other
/// Library… in the Symbols panel lists them in the list's order.
#[test]
+107
View File
@@ -170,6 +170,113 @@ fn a_plot_reads_back_as_its_art() {
assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}");
}
/// A plot of the art's bounds is measured on the art it plots: art on a non-printing layer, on a
/// layer at 0% opacity or at 0% opacity in a group, a placed image and a path that paints nothing
/// don't move its origin, a clipping layer is measured as clipped, and a document whose only
/// visible art is such art is refused.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_the_layers_it_does_not_plot() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let alone = plot(&mut s).unwrap();
let printing = s.doc().unwrap().doc.layers[0].id;
for props in [json!({"printable": false}), json!({})] {
let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
if props.as_object().unwrap().is_empty() {
s.execute("transparency.set", &json!({"ids": [layer], "opacity": 0})).unwrap();
} else {
let mut p = props.clone();
p["id"] = layer.clone();
s.execute("layer.setProps", &p).unwrap();
}
s.execute("shape.rectangle", &json!({"x": -300, "y": 500, "width": 20, "height": 20})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "{props}");
}
// An object at 0% opacity in a group, on a layer that plots.
s.execute("layer.new", &json!({})).unwrap();
let far = s.execute("shape.rectangle", &json!({"x": -500, "y": 700, "width": 20, "height": 20})).unwrap()["id"].clone();
s.execute("object.group", &json!({"ids": [far]})).unwrap();
s.execute("transparency.set", &json!({"ids": [far], "opacity": 0})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "0% opacity in a group");
// A placed image and a path whose fill and stroke paint nothing.
let mut png = vec![];
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "a placed image");
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "a path that paints nothing");
// A clipping layer's clipping path, which loses its paint, still clips the art measured: a
// large square clipped to the first square draws nothing more.
let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
s.execute("shape.rectangle", &json!({"x": -300, "y": -300, "width": 800, "height": 800})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap();
assert_eq!(plot(&mut s).unwrap(), alone, "a clipping layer");
s.execute("layer.setProps", &json!({"id": clipping, "visible": false})).unwrap();
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
}
/// A placed image in a symbol's art doesn't move a plot of the art's bounds either, and a
/// document whose only other visible art is an instance of that symbol is refused.
#[test]
fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let alone = plot(&mut s).unwrap();
let printing = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.new", &json!({})).unwrap();
let mut png = vec![];
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap();
s.execute("symbol.new", &json!({"name": "Far"})).unwrap();
assert!(s.doc().unwrap().doc.symbols.iter().any(|sym| sym.name == "Far"));
assert_eq!(plot(&mut s).unwrap(), alone, "an image in symbol art");
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
// A symbol of a square and an image is measured by its square.
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
let before = bounds(&s);
let image = s.execute("file.place", &json!({"name": "near.png", "dataBase64": b64(&png), "at": [400, 600]})).unwrap()["ids"][0].clone();
s.execute("symbol.new", &json!({"name": "Both", "ids": [square, image]})).unwrap();
assert_eq!(s.doc().unwrap().doc.symbols.len(), 2);
let after = bounds(&s);
for (a, b) in [(before.x0, after.x0), (before.y0, after.y0), (before.x1, after.x1), (before.y1, after.y1)] {
assert!((a - b).abs() < 1e-6, "{before:?} {after:?}");
}
}
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
/// out when it would take more cells than the effect makes.
#[test]
fn a_plot_of_the_arts_bounds_measures_images_by_their_halftone_dots() {
let mut s = two_boards();
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
let printing = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.new", &json!({})).unwrap();
let mut png = vec![];
image::DynamicImage::new_rgb8(100, 100).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.execute("file.place", &json!({"name": "dots.png", "dataBase64": b64(&png), "at": [300, 300]})).unwrap();
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
// At 300 lines per inch a 100 pt image takes more cells than the effect makes.
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 300}})).unwrap();
let e = plot(&mut s).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
s.execute("effect.apply", &json!({"effect": "addon.color.halftone", "params": {"frequency": 20}})).unwrap();
let out = String::from_utf8(plot(&mut s).unwrap()).unwrap();
assert!(out.contains("PD"), "{out}");
}
#[test]
fn export_options_are_checked() {
let mut s = two_boards();
+42
View File
@@ -103,6 +103,48 @@ fn use_artboards_false_writes_one_page_of_the_arts_bounds() {
}
}
/// A page of the art's bounds is measured on the layers the PDF draws: a non-printing layer that
/// the PDF leaves out doesn't make it larger, unless `includeNonPrinting` or `createLayers` keeps
/// the layer. A `.ai` file of the art's bounds, which keeps layers by default, measures it unless
/// `createLayers` is off. A document whose only visible art doesn't print is refused.
#[test]
fn a_page_of_the_arts_bounds_leaves_out_non_printing_layers() {
let mut s = session(1);
let printing = s.doc().unwrap().doc.layers[0].id;
let notes = s.execute("layer.new", &json!({})).unwrap()["id"].clone();
s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap();
s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap();
let size = |bytes: &[u8]| vectorcraft_pdf::import(bytes).unwrap().artboards[0].rect.size();
let printed = size(&b64(&export(&mut s, json!({"useArtboards": false}))));
assert!(printed.width < 50.0 && printed.height < 40.0, "{printed:?}");
let through_export = s.execute("document.export", &as_export(&json!({"useArtboards": false}))).unwrap();
assert_eq!(size(&b64(&through_export)), printed);
let ai = |s: &mut Session, extra: Value| {
let mut p = json!({"format": "ai", "useArtboards": false});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
size(&b64(&s.execute("document.export", &p).unwrap_or_else(|e| panic!("{p}: {e}"))))
};
assert_eq!(ai(&mut s, json!({"createLayers": false})), printed);
let kept = [
size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))),
size(&b64(&export(&mut s, json!({"useArtboards": false, "createLayers": true})))),
ai(&mut s, json!({})),
];
for all in kept {
assert!(all.width > 200.0 && all.height > 200.0, "{all:?}");
}
// Only the non-printing layer shows: the PDF would draw nothing.
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
for p in [json!({"useArtboards": false}), json!({"useArtboards": false, "includeNonPrinting": false})] {
let e = s.execute("document.exportPdf", &p).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{p}: {e}");
}
let e = s.execute("document.export", &json!({"format": "ai", "useArtboards": false, "createLayers": false})).unwrap_err().to_string();
assert!(e.contains("no visible art"), "{e}");
assert!(size(&b64(&export(&mut s, json!({"useArtboards": false, "includeNonPrinting": true})))).width < 25.0);
}
/// In a PDF without a standard, the warning for a page longer than 14,400 pt written with a
/// `UserUnit` above 1 names "Write pages longer than 200 in at full size in points": at PDF 1.5
/// (written as 1.6) and later, through `document.exportPdf`, `document.export`, a page of the
+2 -14
View File
@@ -352,20 +352,8 @@ fn svg_darkness_preserves_source_model_and_gradient_appearance() {
#[test]
fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
const CHILD: &str = "VECTORCRAFT_TEST_SHADOW_RGB_PROFILE";
if std::env::var_os(CHILD).is_none() {
// Color settings are process-wide: exercise this profile in a separate test process.
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space", "--nocapture"])
.env(CHILD, "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"isolated color profile test failed:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
// Color settings are process-wide: exercise this profile in a separate test process.
if !crate::tests::in_own_process("cmd::fileio::tests_svg::svg_darkness_uses_rendered_shadow_in_non_srgb_working_space") {
return;
}
use vectorcraft_color::{Color, Paint, cms};
+102 -10
View File
@@ -184,15 +184,17 @@ impl Sets {
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
/// cancelled ([`vectorcraft_doc::cancel`]).
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. An open box that
/// a later box of its group overlaps, starting lower and ending no further right or lower, keeps
/// only its part above the later box's top, so boxes staggered right and down each meet only the
/// one before. Fails only when cancelled ([`vectorcraft_doc::cancel`]).
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
Ok(sweep(bounds, None)?.groups())
}
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
/// box. The open
/// see-through, an open box is closed early, or a box isn't opened, only inside a see-through box,
/// and an open box is cut short only by a see-through box that is opened. The open
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
/// a box without transparency meets only the see-through ones.
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
@@ -285,12 +287,20 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
});
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
// see-through.
// see-through. Likewise, whatever later overlaps the part of an open box at or below this
// one's top, when that box ends no further right or lower than this one, overlaps this
// one: the open box then keeps only the part above this one's top.
let cut = b.y0.next_down();
for &o in &met {
sets.join(boxes[k].0, boxes[o].0);
let ob = boxes[o].1;
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
if !shadows || Some(o) == holder || b.x1 < ob.x1 || b.y1 < ob.y1 {
continue;
}
if b.y0 <= ob.y0 {
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
} else if holder.is_none() && cut < low[tree(o)][leaf[o] + size] {
set(&mut low[tree(o)], leaf[o], cut);
}
}
if holder.is_none() {
@@ -428,8 +438,10 @@ mod tests {
every_pair_joining(bounds, |_, _| true)
}
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`. A box
/// that isn't finite ([`finite`]) overlaps none.
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
let bounds: Vec<Option<Rect>> = bounds.iter().map(|b| b.filter(finite)).collect();
let n = bounds.len();
let mut group: Vec<usize> = (0..n).collect();
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
@@ -731,9 +743,9 @@ mod tests {
];
let see = [false, true, true, false];
let mut sets = sweep(&bounds, Some(&see)).unwrap();
// The second box meets the first; the third meets the second; the fourth meets the second
// and the third.
assert_eq!(sets.meets, 4);
// The second box meets the first; the third meets the second, which keeps only its part
// above the third's top; the fourth meets the third.
assert_eq!(sets.meets, 3);
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
// Opaque boxes alone meet nothing.
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
@@ -741,6 +753,86 @@ mod tests {
assert_eq!(sets.groups().len(), 4);
}
/// `n` boxes of one size, each a little right of and below the one before, all overlapping and
/// none inside another.
fn staggered(n: usize) -> Vec<Option<Rect>> {
let w = 2.0 * n as f64;
(0..n).map(|i| Some(Rect::new(i as f64, i as f64, w + i as f64, w + i as f64))).collect()
}
/// Each box of a stagger right and down meets only the box before it, which keeps only its
/// part above the new box's top, not every box still open.
#[test]
fn staggered_boxes_meet_only_the_box_before() {
let n = 512;
let bounds = staggered(n);
let mut sets = sweep(&bounds, None).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
// See-through boxes do the same with transparency.
let mut sets = sweep(&bounds, Some(&vec![true; n])).unwrap();
assert_eq!(sets.meets, n - 1);
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
}
/// An open box keeps the part a later box would meet without meeting the box that cut it short:
/// a part lower than that box, a part further right, or any part when that box is opaque.
#[test]
fn a_box_is_cut_short_only_where_the_later_box_covers_it() {
let k = Rect::new(5.0, 5.0, 15.0, 15.0);
// Lower than `k`: the last box overlaps only the bottom of the first.
let lower = [Some(Rect::new(0.0, 0.0, 10.0, 20.0)), Some(k), Some(Rect::new(8.0, 17.0, 9.0, 25.0))];
assert_eq!(overlapping(&lower).unwrap(), vec![vec![0, 1, 2]]);
// Further right than `k`: the last box starts right of it and overlaps the first.
let right = [Some(Rect::new(0.0, 0.0, 20.0, 10.0)), Some(k), Some(Rect::new(17.0, 7.0, 25.0, 9.0))];
assert_eq!(overlapping(&right).unwrap(), vec![vec![0, 1, 2]]);
// An opaque `k` doesn't join the opaque last box, which joins the see-through first one.
let opaque = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))];
let mut sets = sweep(&opaque, Some(&[true, false, false])).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
// A see-through `k` held by a see-through box around it isn't opened and cuts nothing short.
let held = [Some(Rect::new(0.0, 2.0, 30.0, 30.0)), Some(Rect::new(1.0, 0.0, 10.0, 10.0)), Some(k), Some(Rect::new(6.0, 8.0, 7.0, 20.0))];
let see = [true, false, true, false];
let mut sets = sweep(&held, Some(&see)).unwrap();
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
assert_eq!(sets.groups(), every_pair_joining(&held, |i, j| see[i] || see[j]));
}
/// Staggers in all four directions, of mixed sizes (empty ones included) with gaps and shared
/// edges, in either order, with signed zeros and boxes that aren't finite, some see-through,
/// group as comparing every pair groups them.
#[test]
fn staggered_boxes_group_as_comparing_every_pair() {
let mut seed = 0x3c6e_f372_fe94_f82bu64;
let mut next = |m: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1000) as f64 / 1000.0 * m
};
for round in 0..48 {
let n = 8 + round * 2;
let (sx, sy) = (if round % 2 == 0 { 1.0 } else { -1.0 }, if round / 2 % 2 == 0 { 1.0 } else { -1.0 });
let mut bounds: Vec<Option<Rect>> = (0..n)
.map(|i| {
let step = next(4.0).floor();
let (x, y) = (sx * (i as f64 * 2.0 + step), sy * (i as f64 * 2.0 + next(4.0).floor()));
let (w, h) = (next(8.0).floor() * 2.0, next(8.0).floor() * 2.0);
Some(Rect::new(x, y, x + w, y + h))
})
.collect();
bounds[0] = Some(Rect::new(-0.0, -0.0, 0.0, 6.0));
bounds[n / 2] = Some(Rect::new(0.0, sy * 6.0, f64::INFINITY, sy * 6.0 + 4.0));
if round / 4 % 2 == 1 {
bounds.reverse();
}
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.5).collect();
let mut sets = sweep(&bounds, Some(&see)).unwrap();
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
}
}
/// An opaque box between a member and its group's top that paints over the member joins, and
/// so on along a chain; one under the member stays, but for one within the fringe.
#[test]
+79 -7
View File
@@ -797,22 +797,47 @@ fn place_of(d: &Document, roots: &[NodeId]) -> Option<NodeId> {
}
/// The ruler guides of each of `roots` that is a sublayer (in its sublayers too), with the layer
/// that holds it, in order. Other objects hold none.
/// that holds it, in order. Other objects hold none. Each root, and each child of it and of its
/// sublayers, is looked at once.
fn held_guides(d: &Document, roots: impl IntoIterator<Item = NodeId>) -> Vec<(NodeId, Node)> {
let mut out = vec![];
for id in roots {
let (Some(n), Some(parent)) = (d.node(id), d.parent_of(id)) else { continue };
if n.holds_ruler_guides() {
n.walk(&mut |c| {
if c.is_ruler_guide() {
out.push((parent, c.clone()));
}
});
guide_seen(n);
if n.is_layer() {
guides_of(n, parent, &mut out);
}
}
out
}
/// Push each ruler guide of `layer` and of its sublayers onto `out` in paint order, with `parent`.
fn guides_of(layer: &Node, parent: NodeId, out: &mut Vec<(NodeId, Node)>) {
for c in layer.children().into_iter().flatten() {
guide_seen(c);
if c.is_ruler_guide() {
out.push((parent, Node::clone(c)));
} else if c.is_layer() {
guides_of(c, parent, out);
}
}
}
#[cfg(test)]
thread_local! {
/// The nodes that [`held_guides`] has looked at on this thread, in order.
static GUIDES_SEEN: std::cell::RefCell<Vec<NodeId>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Note that [`held_guides`] looked at `n`.
#[cfg(test)]
fn guide_seen(n: &Node) {
GUIDES_SEEN.with(|s| s.borrow_mut().push(n.id));
}
#[cfg(not(test))]
fn guide_seen(_: &Node) {}
/// An image of `r` (in a clip group when it is clipped).
fn raster_node(d: &mut Document, r: Raster) -> Node {
let key = unique_key(d, "flattened");
@@ -922,6 +947,53 @@ mod tests {
assert_eq!(flat.children(Some(layer)).and_then(|c| c.last()).map(|c| c.id), Some(g));
}
/// The guides of a sublayer and of its sublayers are gathered in paint order with the layer
/// that holds it, looking at the sublayer and each child of it and of its sublayers once.
/// Other roots give none.
#[test]
fn held_guides_look_at_each_node_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let layer = s.doc().unwrap().doc.layers[0].id;
let sublayer =
|s: &mut Session, parent: NodeId| NodeId(s.execute("layer.newSublayer", &json!({"parent": parent.0})).unwrap()["id"].as_u64().unwrap());
let rect = |s: &mut Session, on: NodeId| {
s.execute("layer.setCurrent", &json!({"id": on.0})).unwrap();
NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap())
};
let sub = sublayer(&mut s, layer);
let deep = sublayer(&mut s, sub);
let empty = sublayer(&mut s, layer);
let (a, b, c) = (rect(&mut s, sub), rect(&mut s, deep), rect(&mut s, empty));
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut guide = |on: NodeId, pos: f64| {
let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: true, pos, artboard: None });
d.insert(Some(on), usize::MAX, g).unwrap()
};
let (g1, g2, g3) = (guide(sub, 1.0), guide(deep, 2.0), guide(sub, 3.0));
let doc = &s.doc().unwrap().doc;
let ids = |n: &Node| {
let mut v = vec![];
n.walk(&mut |c| v.push(c.id));
v
};
assert_eq!(ids(doc.node(sub).unwrap()), vec![sub, deep, b, g2, a, g1, g3]);
let run = |roots: &[NodeId]| {
GUIDES_SEEN.with(|v| v.borrow_mut().clear());
let got: Vec<_> = held_guides(doc, roots.iter().copied()).into_iter().map(|(p, g)| (p, g.id)).collect();
(got, GUIDES_SEEN.with(|v| v.take()))
};
// Every node of the sublayer is looked at once, and the guides keep their paint order.
assert_eq!(run(&[sub]), (vec![(layer, g2), (layer, g1), (layer, g3)], vec![sub, deep, b, g2, a, g1, g3]));
// A sublayer that holds none gives none; a path holds none; a missing root and a top-level
// layer, which has no parent, are skipped.
assert_eq!(run(&[empty]), (vec![], vec![empty, c]));
assert_eq!(run(&[a]), (vec![], vec![a]));
assert_eq!(run(&[NodeId(u64::MAX), layer]), (vec![], vec![]));
// A deeper sublayer gives its guides to the sublayer that holds it.
assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]);
}
/// In a file without transparency with Clip Complex Regions on, art under a group's opaque
/// image within one of its pixels joins the group, also where a long image is made at a lower
/// resolution and its pixels are wider than at the preset's.
+131 -29
View File
@@ -6,20 +6,34 @@
//! (<https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html>), in our words:
//!
//! - With one object selected, Start Global Edit finds the objects that repeat its shape: the
//! same outline, wherever it lies and at whatever size. Two options narrow the match: Appearance
//! (the same fill and stroke too) and Size (the same width and height too). The search covers
//! every artboard and the canvas around them by default; it can be limited to a range of
//! artboards (`1, 3-5`) and can leave out the objects that lie on no artboard. Images, type,
//! masks, linked files and selections of more than one object are not supported.
//! same outline, wherever it lies, at whatever size and at whatever angle. Two options narrow
//! the match: Appearance (the same fill and stroke too) and Size (the same width and height
//! too). The search covers every artboard and the canvas around them by default; it can be
//! limited to a range of artboards (`1, 3-5`) and can leave out the objects that lie on no
//! artboard. Images, type, masks, linked files and selections of more than one object are not
//! supported.
//! - The help page "Edit groups with similar objects"
//! (<https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html>):
//! with a group selected, Start Global Edit finds the groups like it, and an edit made to an
//! object inside one of them is made to the matching object in each of the others. Here a group
//! is like another when it holds as many objects, in the same order, each like the one at its
//! place (paths, compound paths, symbol instances and groups of them, clipping paths included),
//! and they lie the same way relative to each other: the group as a whole is moved or scaled.
//! With Appearance on, each of those objects must have the same fill and stroke too; with Size,
//! the groups the same width and height.
//! and they lie the same way relative to each other: the group as a whole is moved, scaled or
//! rotated. With Appearance on, each of those objects must have the same fill and stroke too;
//! with Size, the groups the same width and height.
//! - The how-to "Design a modern geometric logo"
//! (<https://helpx.adobe.com/vn_vi/illustrator/how-to/modern-logo-design.html>) makes rotated
//! copies of a group of shapes around a point, then starts Global Edit on one object and edits
//! every copy of it at once. Here a rotated copy is found as a moved or scaled one is, and an
//! edit reaches it turned by its own angle: an anchor moved to the right on the selected object
//! moves downward on a copy turned a quarter turn clockwise. The rules below for rotated copies
//! are VectorCraft's own. The angle is the one that lays each anchor and handle of the selected
//! object on the copy's of the same order, so a square whose anchors were turned a quarter turn
//! is a copy turned a quarter turn. A copy is the same shape when, laid so, every anchor and
//! handle lies within a millionth of the larger side of the copy's box of its own ([`SAME`]).
//! A reflected copy is another shape. With Size, a rotated copy has the same size when it is the
//! selected object rotated without scaling: its width and height are compared as they were
//! before the rotation.
//! - Selecting one of the repeated objects with the Selection tool highlights the similar objects
//! at once, before Global Edit starts. Here they are the objects Start Global Edit would take
//! with the current Global Edit Options ([`similar`]).
@@ -29,15 +43,16 @@
//!
//! Here the found objects ([`GlobalEdit::members`]) stay highlighted while the selection keeps the
//! object that was selected, so that the Transform panel and the bounding box measure that object
//! and not the whole set. Each member keeps the transform (a move and a uniform scale) that maps
//! the first object's outline onto its own. After every edit ([`propagate`], run inside
//! [`Session::edit`], so the whole change is one undo step), the first selected member the edit
//! changed is the model: what changed about it is given to every other member, and nothing else,
//! so members found by shape alone keep their own fills and strokes where the edit didn't touch
//! them:
//! and not the whole set. Each member keeps the transform (a move, a uniform scale and, for a
//! rotated copy, a turn) that maps the first object's outline onto its own. After every edit
//! ([`propagate`], run inside [`Session::edit`], so the whole change is one undo step), the first
//! selected member the edit changed is the model: what changed about it is given to every other
//! member, and nothing else, so members found by shape alone keep their own fills and strokes
//! where the edit didn't touch them:
//!
//! - its outline (and anchors), placed through that transform, so in proportion to each member's
//! size. Only geometry is placed so: no stroke weight is scaled to a member's size;
//! size and turned by its angle. Only geometry is placed so: no stroke weight is scaled to a
//! member's size;
//! - its opacity, blending, knockout and the object's effects, each when it changed;
//! - of its fills and strokes, each setting that changed (paint, weight, opacity, blending,
//! effects, caps, dashes, arrowheads …), as it is: it goes to the member's fill or stroke of the
@@ -74,12 +89,12 @@
//! and later edits leave it as it is.
//! The object the edit started from can't be left out (a Shift-click on it selects it or
//! deselects it as before), Global Edit ends when fewer than two members are left, and leaving
//! one out is not an undo step. Rotated copies are not covered.
//! one out is not an undo step.
use serde::Serialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Shape, Vec2};
use super::wand::{fill_of, stroke_of};
use super::{CommandSpec, Result, Session, bad, bool_or, checked_id, cmd, has_doc};
@@ -98,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Start Global Edit",
["Select"],
None,
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
"{appearance?: bool, size?: bool, artboards?: \"all\" | range such as \"1, 3-5\", includeCanvas?: bool} (each defaults to the Global Edit Options) while Global Edit is off: start it on the one selected object (a path, compound path, symbol instance or group of them), with the objects of the same shape, moved, scaled or rotated copies of it and not reflected ones (for a group: the groups holding objects like its own, at the same places) (and, with `appearance`, the same fill and stroke; with `size`, the same width and height, for a rotated copy before its rotation) on the artboards given (and, with `includeCanvas`, off every artboard), at most 10000 → {active: true, count, ids}; while on: stop it (Escape does the same) → {active: false}",
can_toggle,
toggle
),
@@ -181,7 +196,8 @@ pub type Outlines = Vec<(BezPath, [u8; 3])>;
#[derive(Clone, Debug, PartialEq)]
pub struct GlobalEdit {
/// The objects edited together, the one selected at the start first, each with the transform
/// (a move and a uniform scale) that maps that first object's outline onto its own.
/// (a move, a uniform scale and, for a turned copy, a turn) that maps that first object's
/// outline onto its own.
pub members: Vec<(NodeId, Affine)>,
/// [`highlights`] as of a document revision: the canvas asks every frame.
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
@@ -257,14 +273,60 @@ impl Form {
}
}
fn same(&self, o: &Form) -> bool {
self.tag == o.tag
&& self.symbols == o.symbols
&& self.points.len() == o.points.len()
&& self.points.iter().zip(&o.points).all(|(a, b)| a.distance(*b) < 1e-6)
/// The transform that lays this form's object on `o`'s, point for point in order, and whether
/// it turns the object: a move and a uniform scale when the two lie the same way, otherwise a
/// turn too. `None` when `o` is another shape, a reflected copy included.
fn onto(&self, o: &Form) -> Option<(Affine, bool)> {
if self.tag != o.tag || self.symbols != o.symbols || self.points.len() != o.points.len() {
return None;
}
let near = |xf: Affine| self.points.iter().zip(&o.points).all(|(a, b)| (xf * *a).distance(*b) < SAME);
let back = self.frame.inverse();
if near(Affine::IDENTITY) {
return Some((o.frame * back, false));
}
let turn = self.turn_onto(o)?;
near(turn).then(|| (o.frame * turn * back, true))
}
/// The turn, uniform scale and move (both forms in their unit boxes) that best lays this
/// form's points on `o`'s in order, by least squares. A turn within [`SQUARE`] of a quarter
/// turn is that quarter turn exactly.
fn turn_onto(&self, o: &Form) -> Option<Affine> {
let n = self.points.len() as f64;
let middle = |f: &Form| f.points.iter().fold(Vec2::ZERO, |s, p| s + p.to_vec2()) / n;
let (from, to) = (middle(self), middle(o));
// With the points as complex numbers about their middles, the fit is `Σ conj(p) q / Σ |p|²`.
let (mut re, mut im, mut spread) = (0.0, 0.0, 0.0);
for (a, b) in self.points.iter().zip(&o.points) {
let (p, q) = (a.to_vec2() - from, b.to_vec2() - to);
re += p.dot(q);
im += p.cross(q);
spread += p.hypot2();
}
let len = re.hypot(im);
let scale = len / spread;
if !(scale.is_finite() && scale > 0.0) {
return None;
}
let (mut cos, mut sin) = (re / len, im / len);
if cos.abs() < SQUARE {
(cos, sin) = (0.0, sin.signum());
} else if sin.abs() < SQUARE {
(cos, sin) = (cos.signum(), 0.0);
}
let (a, b) = (scale * cos, scale * sin);
Some(Affine::translate(to) * Affine::new([a, b, -b, a, 0.0, 0.0]) * Affine::translate(-from))
}
}
/// How far apart two forms' points may lie, each form in its unit box, for the forms to be the
/// same. For a turned copy this bounds the angle too: a copy turned and then changed by more than
/// a millionth of its larger side is another shape.
const SAME: f64 = 1e-6;
/// A turn whose sine or cosine is below this is taken as a whole number of quarter turns.
const SQUARE: f64 = 1e-9;
/// Global Edit supports paths, compound paths, symbol instances and groups of them; not images,
/// type, linked files, objects with an opacity mask, clipping paths or guides (the help page lists
/// images, text, masks and links as unsupported).
@@ -395,8 +457,16 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
}
boards.as_ref().is_none_or(|rs| rs.iter().any(|r| on(*r, b)))
};
// A copy that lies the same way has the size of the selected object when their boxes are as
// wide and as high; a turned copy, when the transform that lays the object on it doesn't scale.
let same_size = |n: &Node, xf: Affine, turned: bool| {
if turned {
close(xf.determinant().abs().sqrt(), 1.0)
} else {
matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2))
}
};
let mut out = vec![(*id, Affine::IDENTITY)];
let back = form.frame.inverse();
super::select::walk_selectable(d, st.isolation, |n| {
if n.id == *id || out.len() >= MAX_MEMBERS {
return false;
@@ -413,12 +483,12 @@ fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
};
// The object count first: it turns most objects down before their form is made.
if n.children().map(Vec::len) == count
&& let Some(f) = Form::of(n).filter(|f| f.same(&form) && supported(n))
&& (!o.size || matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)))
&& let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n))
&& (!o.size || same_size(n, xf, turned))
&& (!o.appearance || same_look(key, n))
&& in_scope(n)
{
out.push((n.id, f.frame * back));
out.push((n.id, xf));
// A group taken is taken whole, as compound paths, symbol instances and the others are.
return false;
}
@@ -464,7 +534,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let o = s.global_edit_options.with(p, &s.doc()?.doc, C)?;
let members = matches(s, &o)?;
if members.len() < 2 {
return Err(bad(C, "no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again"));
return Err(bad(C, "no similar objects found (reflected copies are not matched); change the Global Edit Options and try again"));
}
let ids: Vec<u64> = members.iter().map(|(id, _)| id.0).collect();
let st = s.doc_mut()?;
@@ -1027,6 +1097,38 @@ mod tests {
assert!(taken > 100 && checked - taken > 100 && asked > 200, "{taken} of {checked}, {asked} selected");
}
#[test]
fn a_form_is_laid_on_a_turned_copy_and_on_no_reflected_or_unmeasurable_one() {
let mut d = Document::new(800.0, 600.0);
let mut path = |points: &[(f64, f64)]| {
let anchors = points.iter().map(|(x, y)| Anchor::corner(Point::new(*x, *y))).collect();
Node::path(d.alloc_id(), PathData::new(vec![SubPath::new(anchors, true)]), Appearance::default())
};
let form = Form::of(&path(&[(0.0, 0.0), (30.0, 0.0), (30.0, 70.0)])).unwrap();
let mut onto = |points: &[(f64, f64)]| Form::of(&path(points)).and_then(|f| form.onto(&f));
let near = |xf: Affine, want: [f64; 6]| xf.as_coeffs().iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9);
// The same way at twice the size: a move and a scale, no turn.
let (xf, turned) = onto(&[(100.0, 0.0), (160.0, 0.0), (160.0, 140.0)]).unwrap();
assert!(!turned && near(xf, [2.0, 0.0, 0.0, 2.0, 100.0, 0.0]), "{xf:?}");
// A quarter turn, (x, y) → (−y, x), moved by (100, 0); and a turn by 30° at half the size.
let (xf, turned) = onto(&[(100.0, 0.0), (100.0, 30.0), (30.0, 30.0)]).unwrap();
assert!(turned && near(xf, [0.0, 1.0, -1.0, 0.0, 100.0, 0.0]), "{xf:?}");
let by = Affine::rotate(30f64.to_radians()) * Affine::scale(0.5);
let at = |x: f64, y: f64| {
let p = by * Point::new(x, y);
(p.x, p.y)
};
let (xf, turned) = onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.0)]).unwrap();
assert!(turned && near(xf, by.as_coeffs()), "{xf:?}");
// A reflected copy, a copy with an anchor a thousandth of its size away, and points that
// are not numbers or not finite.
assert!(onto(&[(0.0, 0.0), (-30.0, 0.0), (-30.0, 70.0)]).is_none());
assert!(onto(&[at(0.0, 0.0), at(30.0, 0.0), at(30.0, 70.07)]).is_none());
assert!(onto(&[(f64::NAN, 0.0), (30.0, 0.0), (30.0, 70.0)]).is_none());
assert!(onto(&[(0.0, 0.0), (f64::INFINITY, 0.0), (30.0, 70.0)]).is_none());
assert!(onto(&[(0.0, 0.0), (30.0, 0.0)]).is_none(), "another count of anchors");
}
#[test]
fn support_of_empty_degenerate_and_deep_objects_is_decided_as_building_the_form_decides() {
let mut d = Document::new(800.0, 600.0);
+22 -11
View File
@@ -631,19 +631,33 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: &
changed
}
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). Returns whether
/// the kept style changed.
/// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that
/// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether
/// the kept style or that mark changed.
fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool {
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false };
let mut style = label_style(&spec.label_styles, role);
// The kept fill can already be the one `change` sets (black, the default): `change` sets the fill when it gives one
// of two different fills something else.
let sets_fill = role == Role::Legend
&& [Paint::None, Paint::solid(Color::BLACK)].into_iter().any(|fill| {
let mut probe = CharStyle { fill: fill.clone(), ..style.clone() };
change(&mut probe);
probe.fill != fill
});
change(&mut style);
let styles = &mut spec.label_styles;
let slot = match role {
Role::Value => &mut spec.label_styles.values,
Role::Category => &mut spec.label_styles.categories,
Role::Legend => &mut spec.label_styles.legend,
Role::Value => &mut styles.values,
Role::Category => &mut styles.categories,
Role::Legend => &mut styles.legend,
};
let changed = slot.as_ref() != Some(&style);
let mut changed = slot.as_ref() != Some(&style);
*slot = Some(style);
if sets_fill && !styles.legend_fill_set {
styles.legend_fill_set = true;
changed = true;
}
changed
}
@@ -872,12 +886,9 @@ fn run_paint_change(was: &Node, now: &Node, fill: bool) -> Option<(CharStyle, Ve
}
/// Does graph `g` pick the fill of its legend labels itself, white on a dark wedge and black on the others: a pie with
/// Legends in Wedges whose legend labels keep no fill of their own?
/// Legends in Wedges whose legend labels keep no fill of their own ([`GraphSpec::picks_legend_fill`])?
pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool {
g.kind == GraphKind::Pie
&& g.legend
&& g.pie_legend_in_wedges
&& !g.label_styles.legend.as_ref().is_some_and(|st| st.fill != Paint::solid(Color::BLACK))
g.picks_legend_fill()
}
/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them.
+105
View File
@@ -840,6 +840,24 @@ fn an_opacity_sort_objects_stores_the_frontmost_mark_it_changes() {
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.6));
}
/// A Sort Objects that gives series marks the opacities they already have changes nothing: the value the graph stores
/// stays and no undo step is made, even when the evenly stepped percentage differs from a mark's in the last digits.
#[test]
fn an_opacity_sort_objects_that_changes_no_mark_keeps_the_stored_opacity() {
let (mut s, id, _, marks) = column_marks();
s.execute("object.setProps", &json!({"id": marks[1].0, "opacity": 65})).unwrap();
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 30})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
// From left to right the columns have 30%, 65% and 100%, the values an even step from 30% to 100% gives them.
let undo = s.doc().unwrap().history.undo.len();
let ids = [marks[0].0, marks[1].0, marks[2].0];
s.execute("addon.arrange.sort", &json!({"ids": ids, "by": "x", "apply": "opacity", "distribute": true})).unwrap();
let opacities: Vec<f32> = marks[..3].iter().map(|m| s.doc().unwrap().doc.node(*m).unwrap().opacity).collect();
assert_eq!(opacities, [0.3, 0.65, 1.0]);
assert_eq!(spec(&s, id).series_paints[0].opacity, Some(0.3));
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
}
/// An object opacity, blend mode, fill, stroke and weight that Global Edit gives a mark of another series from the mark
/// that was edited are stored on the graph for that series in the same undo step, and every mark of the series has them
/// when the graph is drawn again.
@@ -6343,6 +6361,93 @@ fn pie_names_and_wedge_labels_keep_their_style() {
assert_eq!(fills, ["#00ff00", "#00ff00"], "the kept fill, also on the dark wedge");
}
/// On a pie with Legends in Wedges, a black fill given to the white legend label on the dark wedge is kept for every
/// legend label: the graph draws it black on the dark wedge again, also after a native save and open.
#[test]
fn a_black_fill_set_on_a_wedge_legend_label_stays_black_on_dark_wedges() {
let cases = [("paint.setFill", json!({"color": "#000000"})), ("text.setStyle", json!({"fill": "#000000"})), ("edit.colors.invert", json!({}))];
every_case(cases, |(cmd, params)| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
let legend_fill = |s: &Session, text: &str| {
let NodeKind::Text(t) = label_node(s, id, "Legend", text).kind else { panic!("{text} is not type") };
t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default()
};
assert_eq!(legend_fill(&s, "a"), "#ffffff", "white on the black wedge");
let mut p = params.clone();
p["ids"] = json!([text_id(&s, id, "Legend", "a").0]);
s.execute(cmd, &p).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(!spec(&s, id).label_styles.legend_fill_set, "{cmd}: undone");
assert_eq!(legend_fill(&s, "a"), "#ffffff", "{cmd}: white again after the undo");
s.execute("edit.redo", &json!({})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: redone");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
assert_eq!((legend_fill(&s, "a"), legend_fill(&s, "b")), ("#000000".into(), "#000000".into()), "{cmd}: black on both wedges");
let dir = vectorcraft_testkit::TempDir::new("graph-wedge-legend");
let path = dir.join("pie.vectorcraft");
s.execute("document.save", &json!({"path": path})).unwrap();
s.execute("document.open", &json!({"path": path})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "{cmd}: kept through save and open");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "rows": [[2, 1]]})).unwrap();
assert_eq!(legend_fill(&s, "a"), "#000000", "{cmd}: still black after open");
});
}
/// A size given to the legend labels of a pie with Legends in Wedges keeps the default black fill with it. A color mode
/// change leaves that fill black, so the legend label on the dark wedge is still drawn white. A legend fill that is not
/// black, in a file saved without the mark, is marked as set by the change.
#[test]
fn a_color_mode_change_keeps_the_default_wedge_legend_fill() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, "pie", ",a,b\nP1,1,2");
s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
let styles = spec(&s, id).label_styles;
assert!(!styles.legend_fill_set && !styles.legend_fill_is_own(), "{styles:?}");
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2]]})).unwrap();
let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") };
assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()), Some("#ffffff".into()), "white on the black wedge");
let red = Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap());
let styles = vectorcraft_doc::LabelStyles { legend: Some(vectorcraft_doc::CharStyle { fill: red, ..Default::default() }), ..Default::default() };
assert!(!styles.legend_fill_set && styles.legend_fill_is_own(), "{styles:?}");
s.edit("legacy", |d, _| {
d.node_mut(id).unwrap().extras_mut().graph.as_deref_mut().unwrap().label_styles = styles;
Ok(())
})
.unwrap();
s.execute("file.documentColorMode", &json!({"mode": "rgb"})).unwrap();
assert!(spec(&s, id).label_styles.legend_fill_set, "the converted red is still the labels' own");
}
/// The default black legend fill of a graph that keeps its legend beside the marks stays the default through a color
/// mode change, so turning on Legends in Wedges later still draws the labels on dark wedges white.
#[test]
fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() {
// A pie made here keeps its legend beside the pies.
for kind in ["column", "pie"] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = make(&mut s, kind, ",a,b\nP1,1,2");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("text.setStyle", &json!({"size": 11})).unwrap();
let black = Paint::solid(vectorcraft_color::Color::BLACK);
let before = spec(&s, id).label_styles;
assert_eq!(before.legend.as_ref().map(|st| st.fill.clone()), Some(black.clone()), "{kind}: {before:?}");
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
let after = spec(&s, id).label_styles;
assert_eq!(after.legend.as_ref().map(|st| st.fill.clone()), Some(black), "{kind}: {after:?}");
assert!(!after.legend_fill_set && !after.legend_fill_is_own(), "{kind}: still the default: {after:?}");
}
}
#[test]
fn labels_are_told_apart_by_where_they_come_not_by_their_text() {
let mut s = Session::new();
+8 -22
View File
@@ -470,8 +470,8 @@ impl Library {
}
}
/// Make `g` a library gradient: no placement, freeform points or swatch links (a linked stop keeps
/// the color it shows), the angle its placement showed (a finite one), and stops in order with
/// Make `g` a library gradient: no placement, freeform points, swatch links or process plates (a
/// linked stop keeps the color it shows), the angle its placement showed (a finite one), and stops in order with
/// offsets, opacities and midpoints in range. False when it has fewer than 2 or more than
/// [`MAX_STOPS`] stops.
fn clean_gradient(g: &mut GradientPaint) -> bool {
@@ -490,8 +490,8 @@ fn clean_gradient(g: &mut GradientPaint) -> bool {
st.offset = within(st.offset, 0.0, 1.0, 0.0);
st.opacity = within(st.opacity, 0.0, 1.0, 1.0);
st.midpoint = within(st.midpoint, 0.13, 0.87, 0.5);
st.swatch = None;
st.tint = 1.0;
let color = st.color;
st.set_color(color, None);
}
g.gradient.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
true
@@ -1488,29 +1488,15 @@ fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
/// it shows at full tint, and an unlinked stop has no process plates, as [`clean_gradient`] keeps
/// a library gradient's stops. A link to a
/// global or spot swatch `doc` has stays, and takes that swatch's color.
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
let keep = |name: &str| doc.global_color(name).is_some();
for key in ["fill", "stroke"] {
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
let mut changed = false;
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
if swatch.as_deref().is_some_and(|n| !keep(n)) {
*swatch = None;
*tint = 1.0;
changed = true;
}
};
match &mut paint {
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
Paint::Gradient(g) => {
for st in &mut g.gradient.stops {
unlink(&mut st.swatch, &mut st.tint);
}
}
_ => {}
}
// `map_links` gives an unlinked color full tint, and an unlinked stop no process plates.
let changed = paint.map_links(&mut |_, swatch, _| swatch.take_if(|n| !keep(n.as_str())).is_some());
if changed && let Ok(v) = serde_json::to_value(&paint) {
attrs.insert(key.to_string(), v);
}
+3 -2
View File
@@ -144,9 +144,10 @@ fn find(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(_) => {
// Images and placed documents in opacity-mask art and in the art of symbols, graph
// designs and patterns are named by their ids too (`links.list`).
// designs, patterns and stored brushes are named by their ids too (`links.list`).
let ids = ids_param(p, "ids", C)?.unwrap_or_default();
let kind = |id: &NodeId| st.doc.stored_node(*id).map(|(n, _)| &n.kind);
let doc = super::links::with_brush_art(&st.doc);
let kind = |id: &NodeId| doc.stored_node(*id).map(|(n, _)| &n.kind);
if let Some(value) = ids.iter().find(|id| kind(id).is_none()).map(|id| id.0) {
return Err(bad(C, format!("no such object id {value}")));
}
+153 -69
View File
@@ -27,6 +27,7 @@ use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::stored_art::StoredArt;
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
use vectorcraft_doc::{
Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions,
@@ -44,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Check Links",
[],
None,
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs and patterns)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{ids?: [image or placed document ids] (default: every linked image and placed document, in the layers and in opacity-mask art, symbols, graph designs, patterns and the art of stored brushes)} where each linked file is and whether it changed since it was read → {links: [{name, path?, status: ok|modified|missing, ids, found?: path (found away from its path: relative to the document, or by name in its folder), preview: true (showing the low-resolution preview, not the file), refused?: why the path is not followed (another computer, a device or a URL: it counts as missing)}], missing, modified}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
check
),
@@ -53,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Links",
[],
None,
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns and opacity masks have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}",
has_doc,
update
),
@@ -71,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Relink",
[],
None,
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs and patterns) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}",
has_doc,
relink
),
@@ -80,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Links",
[],
None,
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs and patterns (one row per stored object, never one per symbol instance or pattern tile) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern, name? (of the symbol, graph design or pattern), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
has_doc,
list
),
@@ -89,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Go To Link",
[],
None,
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design or pattern has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
"{id?} select image or placed document `id` (default: the first selected one); the Links panel scrolls it into view → {id, bounds: [x0, y0, x1, y1], onCanvas: true}; one in opacity-mask art or in the art of a symbol, graph design, pattern or stored brush has no place of its own on the canvas: the selection is cleared → {id, onCanvas: false, owner} (owner as links.list gives it)",
has_doc,
go_to
),
@@ -198,6 +199,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec<u64>)> {
/// visited before it has (art being edited on a layer and its definition) counts once, by its
/// first place; without `ids` its content is still grouped.
fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec<Group> {
let view = with_brush_art(d);
let d = &*view;
let mut out: Vec<Group> = vec![];
let mut index: BTreeMap<(String, String, bool), usize> = BTreeMap::new();
// Looked up for every linked node: a set, not the list (which may repeat an id many times).
@@ -234,13 +237,52 @@ fn stored(d: &Document, id: NodeId) -> Option<&Node> {
d.stored_node(id).map(|(n, _)| &**n)
}
/// `d` with the art of its stored brushes set on it ([`vectorcraft_brush::stored_art`]), so that
/// the images and placed documents in that art are visited and found by their ids as stored art;
/// `d` itself when no stored brush's art holds one or the art is set on it already.
pub(crate) fn with_brush_art(d: &Document) -> Cow<'_, Document> {
if !d.mounted_art.is_empty() {
return Cow::Borrowed(d);
}
let art = StoredArt::read(d);
if art.is_empty() {
return Cow::Borrowed(d);
}
let mut d = d.clone();
art.mount(&mut d);
Cow::Owned(d)
}
/// `f` run on `d` with the art of its stored brushes set on it as [`with_brush_art`] sets it; the
/// brushes whose art `f` changed are then written back into the library, the color masks of its
/// images made for their pixels first. The ids it gives that art are the ones [`with_brush_art`]
/// gives it in the same document.
pub(crate) fn editing_brush_art<T>(d: &mut Document, f: impl FnOnce(&mut Document) -> T) -> T {
if !d.mounted_art.is_empty() {
return f(d);
}
let art = StoredArt::read(d);
if art.is_empty() {
return f(d);
}
art.mount(d);
let before: Vec<Arc<Node>> = d.mounted_art.iter().map(|(n, _)| n.clone()).collect();
let out = f(d);
if d.mounted_art.len() != before.len() || d.mounted_art.iter().zip(&before).any(|((n, _), b)| !Arc::ptr_eq(n, b)) {
super::refresh_color_masks(None, d);
}
art.write_back(d);
out
}
/// Of `ids`, the objects of `d` outside the layer tree (where [`Document::node`] finds none).
fn nested_ids(d: &Document, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
ids.iter().copied().filter(|id| d.node(*id).is_none()).collect()
}
/// `links.list`'s `owner` of an object stored at `place` of `d`, when it is not in the layer tree
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`.
/// itself: `{kind: layers|symbol|graphDesign|pattern, name?, maskOf?}`, or for one in the art of a
/// stored brush, `{kind: brush, name, index, tile?, maskOf?}`.
fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
if place.in_layers() {
return None;
@@ -250,6 +292,7 @@ fn owner_json(d: &Document, place: StoredPlace) -> Option<Value> {
StoredRoot::Symbol(i) => json!({ "kind": "symbol", "name": d.symbols.get(i).map(|s| s.name.as_str()) }),
StoredRoot::GraphDesign(i) => json!({ "kind": "graphDesign", "name": d.graph_designs.get(i).map(|g| g.name.as_str()) }),
StoredRoot::Pattern { pattern, .. } => json!({ "kind": "pattern", "name": d.patterns.get(pattern).map(|p| p.name.as_str()) }),
StoredRoot::Mounted(i) => d.mounted_art.get(i).map_or_else(|| json!({}), |(_, owner)| owner.clone()),
};
if let Some(m) = place.mask_of {
owner["maskOf"] = json!(m.0);
@@ -479,7 +522,8 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec<LinkedFile> {
/// again (Preferences › Use Low Resolution Proxy for Linked EPS keeps the preview on screen only).
pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a, Document>, Vec<String>) {
let mut keys = BTreeSet::new();
d.visit_images(|_, im| {
// The art of the stored brushes draws its images too.
with_brush_art(d).visit_images(|_, im| {
if im.link.is_some() && d.images.get(&im.key).is_some_and(ImageBlob::is_proxy) {
keys.insert(im.key.clone());
}
@@ -763,7 +807,7 @@ struct Nested<'a> {
impl Nested<'_> {
/// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols,
/// graph designs and patterns.
/// graph designs and patterns, then [`Document::mounted_art`].
fn run(mut self, d: &mut Document) {
let first = d.peek_next_id();
self.next = first;
@@ -774,7 +818,7 @@ impl Nested<'_> {
for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) {
self.root(root);
}
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) {
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art).chain(d.mounted_art.iter_mut().map(|(n, _)| n)) {
self.root(root);
}
for _ in first..self.next {
@@ -1306,8 +1350,14 @@ impl Resolved {
/// found away from their path take the new path. A link nothing is known of whose image, or placed
/// document, shows a preview (a file another app wrote kept only that) was never read: its file is
/// read now, into the object's bounds, which isn't a change to report. A placed document whose
/// file's bytes are gone isn't showing a preview. Nothing here is an undo step.
/// file's bytes are gone isn't showing a preview. Links in the art of the stored brushes count too,
/// and that art keeps the ids they are listed by. Nothing here is an undo step.
pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved {
editing_brush_art(d, |d| resolve_links(d, base, update, low_res_proxy_eps))
}
/// [`resolve`] in the art `d` stores.
fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps: bool) -> Resolved {
let mut out = Resolved::default();
// The image (with its preview) and hash of each file read for a preview here, by path: images
// of other keys linking to the same file share them, rather than each reading, decoding and
@@ -1458,8 +1508,8 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
}
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from
/// the new file, each as one Update Links step of its document.
/// documents, in the layers, symbols, graph designs, patterns, opacity masks and the art of the
/// stored brushes: read again from the new file, each as one Update Links step of its document.
pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
let path = absolute_path(path);
let targets: Vec<usize> = s
@@ -1469,7 +1519,7 @@ pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
.filter(|(_, st)| st.uid != saved)
.filter(|(_, st)| {
let mut placed = false;
st.doc.visit_placed(|_, p| placed |= p.link.path == path);
with_brush_art(&st.doc).visit_placed(|_, p| placed |= p.link.path == path);
placed
})
.map(|(i, _)| i)
@@ -1526,7 +1576,7 @@ fn link_target(link: &LinkInfo, base: LinkBase) -> PathBuf {
/// `d` (looking from `base`) as saved to `dest`: the links' paths relative to its folder written
/// in; `None` when they are already. A link whose file is not at its path is written relative to
/// where its file is found, else to the place its relative path names. Links in the layers,
/// symbols, graph designs, patterns and opacity masks are all set.
/// symbols, graph designs, patterns, opacity masks and the art of the stored brushes are all set.
pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option<Document> {
let dest = absolute_path(dest);
let dir = Path::new(&dest).parent()?;
@@ -1535,23 +1585,29 @@ pub fn with_relative_paths(d: &Document, base: LinkBase, dest: &str) -> Option<D
let mut look = |l: &LinkInfo| {
wanted.entry((l.path.clone(), l.relative.clone())).or_insert_with(|| relative_path(&link_target(l, base), dir));
};
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
d.visit_placed(|_, p| look(&p.link));
let view = with_brush_art(d);
view.visit_images(|_, im| im.link.iter().for_each(&mut look));
view.visit_placed(|_, p| look(&p.link));
wanted.retain(|(_, stored), rel| rel != stored);
if wanted.is_empty() {
return None;
}
let key = |l: &LinkInfo| (l.path.clone(), l.relative.clone());
let mut d = d.clone();
d.update_links_where(|l| wanted.contains_key(&key(l)), |l| l.relative = wanted.get(&key(l)).cloned().flatten());
editing_brush_art(&mut d, |d| d.update_links_where(|l| wanted.contains_key(&key(l)), |l| l.relative = wanted.get(&key(l)).cloned().flatten()));
Some(d)
}
/// Sets each link of `d`, a copy of a document looking from `base`, to the path where that
/// document finds its file, and its relative path to it as that document's links have them, so
/// the copy finds the same files. Links in the layers, symbols, graph designs, patterns and opacity
/// masks are all set.
/// the copy finds the same files. Links in the layers, symbols, graph designs, patterns, opacity
/// masks and the art of the stored brushes are all set.
pub(crate) fn with_found_paths(d: &mut Document, base: LinkBase) {
editing_brush_art(d, |d| set_found_paths(d, base));
}
/// [`with_found_paths`] in the art `d` stores.
fn set_found_paths(d: &mut Document, base: LinkBase) {
// The new path and relative path of each link by what `locate` reads of it: its path, relative
// path and name.
type PathAndRelative = (String, Option<String>);
@@ -1706,7 +1762,9 @@ fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -
let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect();
let warnings = spot_swatch_notes(&st.doc, reads.iter().map(|(_, read)| read));
if !reads.is_empty() {
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?;
s.edit("Update Links", |d, _| {
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))
})?;
}
let mut out = json!({ "updated": updated, "missing": missing });
if !warnings.is_empty() {
@@ -1833,9 +1891,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(no_folder)?)
}
};
let doc = with_brush_art(&st.doc);
// An image or a placed document, with its link.
let image = |id: &NodeId| {
stored(&st.doc, *id).and_then(|n| match &n.kind {
stored(&doc, *id).and_then(|n| match &n.kind {
NodeKind::Image(im) => Some(im.link.as_ref()),
NodeKind::PlacedDocument(p) => Some(Some(&p.link)),
_ => None,
@@ -1865,7 +1924,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
let mut given: BTreeSet<NodeId> = ids.iter().copied().collect();
let mut more = vec![];
st.doc.visit_stored(|n, _| {
doc.visit_stored(|n, _| {
if let Some((l, _, _)) = linked(n)
&& paths.contains(l.path.as_str())
&& n.id.0 != 0
@@ -1876,7 +1935,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
});
ids.extend(more);
}
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&st.doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
if copy_to.is_some() && ids.iter().any(|id| matches!(stored(&doc, *id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
}
// (ids, the file) per file to read.
@@ -1912,7 +1971,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let mut images = vec![];
let mut documents: Vec<((u32, bool, PageBox), Vec<NodeId>)> = vec![];
for id in ids {
match stored(&st.doc, id).map(|n| &n.kind) {
match stored(&doc, id).map(|n| &n.kind) {
Some(NodeKind::PlacedDocument(pl)) => {
let k = (pl.page(), pl.bounding, pl.page_box);
match documents.iter_mut().find(|(e, _)| *e == k) {
@@ -1963,9 +2022,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
drop(doc);
let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read));
if !reads.is_empty() {
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?;
s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?;
}
not_found.sort();
not_found.dedup();
@@ -2075,14 +2135,15 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) ->
st.selection.objects.iter().copied().filter(|id| image_of(&st.doc, *id).is_some_and(&keep)).collect()
}
/// `id`, else the first selected image.
fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first
/// selected image.
fn image_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result<NodeId> {
let id = object_param(p, "id", cmd)?
.or_else(|| selected_images(st, |_| true).first().copied())
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match image_of(&st.doc, id) {
match image_of(doc, id) {
Some(_) => Ok(id),
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None => Err(bad(cmd, format!("object {} is not an image", id.0))),
}
}
@@ -2105,13 +2166,14 @@ fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
}
}
/// `id`, else the first selected image or placed document.
fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some());
/// `id` (looked up in `doc`, the document of `st` as [`with_brush_art`] gives it), else the first
/// selected image or placed document.
fn linked_param(st: &crate::DocState, doc: &Document, p: &Value, cmd: &str) -> Result<NodeId> {
let first = || st.selection.objects.iter().copied().find(|id| placement_of(doc, *id).is_some());
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
match placement_of(&st.doc, id) {
match placement_of(doc, id) {
Some(_) => Ok(id),
None if stored(&st.doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None if stored(doc, id).is_none() => Err(crate::EngineError::NoNode(id)),
None => Err(bad(cmd, format!("object {} is not an image or a linked file", id.0))),
}
}
@@ -2218,10 +2280,12 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
let statuses = statuses(st);
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
// order they are stored (opacity-mask art, symbols, graph designs, patterns), each once.
// order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the
// stored brushes), each once.
let doc = with_brush_art(&st.doc);
let (mut objects, mut nested) = (vec![], vec![]);
let mut seen = std::collections::HashSet::new();
st.doc.visit_stored(|n, place| {
doc.visit_stored(|n, place| {
if matches!(n.kind, NodeKind::Image(_) | NodeKind::PlacedDocument(_)) && n.id.0 != 0 && seen.insert(n.id) {
if place.in_layers() { objects.push((n, place)) } else { nested.push((n, place)) }
}
@@ -2273,7 +2337,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
if preview {
row["preview"] = json!(true);
}
if let Some(owner) = owner_json(&st.doc, place) {
if let Some(owner) = owner_json(&doc, place) {
row["owner"] = owner;
}
if interactions.contains(&n.id) {
@@ -2295,10 +2359,13 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let id = linked_param(st, p, "links.goTo")?;
// An object in mask art or a definition has no place of its own on the canvas: the selection
// is cleared, and the reply names what holds it.
if let Some(owner) = st.doc.stored_node(id).and_then(|(_, place)| owner_json(&st.doc, place)) {
let doc = with_brush_art(&st.doc);
let id = linked_param(st, &doc, p, "links.goTo")?;
// An object in mask art, a definition or a stored brush's art has no place of its own on the
// canvas: the selection is cleared, and the reply names what holds it.
let owner = doc.stored_node(id).and_then(|(_, place)| owner_json(&doc, place));
drop(doc);
if let Some(owner) = owner {
s.select(|_, sel| sel.set([]))?;
return Ok(json!({ "id": id.0, "onCanvas": false, "owner": owner }));
}
@@ -2310,7 +2377,8 @@ fn go_to(s: &mut Session, p: &Value) -> Result<Value> {
fn embed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.embed";
let st = s.doc()?;
let kind = |id: &NodeId| stored(&st.doc, *id).map(|n| &n.kind);
let doc = with_brush_art(&st.doc);
let kind = |id: &NodeId| stored(&doc, *id).map(|n| &n.kind);
let linked = |id: &NodeId| match kind(id) {
Some(NodeKind::Image(im)) => im.link.is_some(),
Some(NodeKind::PlacedDocument(_)) => true,
@@ -2362,17 +2430,20 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
_ => missing.extend(g.ids),
}
}
drop(doc);
if !done.is_empty() || !documents.is_empty() {
s.edit("Embed", |d, _| {
for (ids, read) in reads {
install(d, &ids, read, Some(Preserve::Bounds), None)?;
}
for id in &done {
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
im.link = None;
editing_brush_art(d, |d| {
for (ids, read) in reads {
install(d, &ids, read, Some(Preserve::Bounds), None)?;
}
}
documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C))
for id in &done {
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.stored_node_mut(*id) {
im.link = None;
}
}
documents.iter().try_for_each(|id| super::place::document::expand(d, *id, C))
})
})?;
}
done.extend(documents);
@@ -2395,9 +2466,10 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result<Vec<u8>, String
fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.unembed";
let st = s.doc()?;
let id = image_param(st, p, C)?;
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
let doc = with_brush_art(&st.doc);
let id = image_param(st, &doc, p, C)?;
let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?;
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
if im.link.is_some() {
return Err(bad(C, format!("image {} is linked already", id.0)));
}
@@ -2422,7 +2494,8 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
let img = linked_image(&bytes, Some(&path))?;
write_file(&path, &bytes)?;
let read = (link_info(&path, &bytes), img);
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?;
drop(doc);
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?;
Ok(json!({ "id": id.0, "path": path }))
}
@@ -2480,9 +2553,10 @@ fn scale_rotation(xf: Affine, (px, py): (f64, f64)) -> (Value, Value) {
(json!([a.hypot(b) / px * 100.0, c.hypot(d) / py * 100.0]), json!((-b).atan2(a).to_degrees() + 0.0))
}
/// Link Info of placed document `id`.
fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
let n = stored(&st.doc, id).ok_or(crate::EngineError::NoNode(id))?;
/// Link Info of placed document `id` (looked up in `doc`, the document of `st` as
/// [`with_brush_art`] gives it).
fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result<Value> {
let n = stored(doc, id).ok_or(crate::EngineError::NoNode(id))?;
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
let size = n.geometric_bounds().unwrap_or_default();
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
@@ -2507,13 +2581,19 @@ fn placed_info(st: &crate::DocState, id: NodeId) -> Result<Value> {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.info";
let id = linked_param(s.doc()?, p, C)?;
if image_of(&s.doc()?.doc, id).is_none() {
return placed_info(s.doc()?, id);
}
let id = {
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let id = linked_param(st, &doc, p, C)?;
if image_of(&doc, id).is_none() {
return placed_info(st, &doc, id);
}
id
};
let mut out = super::place::image_info(s, &json!({ "id": id.0 }))?;
let st = s.doc()?;
let im = image_of(&st.doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
let doc = with_brush_art(&st.doc);
let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?;
let (px, py) = file_pt(&st.doc, &im.key);
out["effectivePpi"] = out["ppi"].take();
out["ppi"] = json!([72.0 / px, 72.0 / py]);
@@ -2530,9 +2610,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "links.placementOptions";
let st = s.doc()?;
let doc = with_brush_art(&st.doc);
let ids =
ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&st.doc, *id).is_some()).collect());
if let Some(id) = ids.iter().find(|id| placement_of(&st.doc, **id).is_none()) {
ids_param(p, "ids", C)?.unwrap_or_else(|| st.selection.objects.iter().copied().filter(|id| placement_of(&doc, *id).is_some()).collect());
if let Some(id) = ids.iter().find(|id| placement_of(&doc, **id).is_none()) {
return Err(bad(C, format!("object {} is not an image or a linked file", id.0)));
}
if ids.is_empty() {
@@ -2551,7 +2632,8 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
None | Some(Value::Null) => None,
Some(v) => Some(v.as_bool().ok_or_else(|| bad(C, "clip must be true or false"))?),
};
let first = ids.first().and_then(|id| placement_of(&st.doc, *id)).unwrap_or_default();
let first = ids.first().and_then(|id| placement_of(&doc, *id)).unwrap_or_default();
drop(doc);
if preserve.is_none() && align.is_none() && clip.is_none() {
return Ok(json!({ "placement": placement_json(first) }));
}
@@ -2561,11 +2643,13 @@ fn placement_options(s: &mut Session, p: &Value) -> Result<Value> {
o.clip = clip.unwrap_or(o.clip);
};
s.edit("Placement Options", |d, _| {
for id in &ids {
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
set(o);
editing_brush_art(d, |d| {
for id in &ids {
if let Some(o) = d.stored_node_mut(*id).and_then(placement_mut) {
set(o);
}
}
}
});
Ok(())
})?;
let mut shown = first;
+3 -2
View File
@@ -472,7 +472,7 @@ impl Session {
pub fn transparency_info(&self) -> TransparencyInfo {
match (self.active(), transparency_targets(self, &Value::Null)) {
(Some(st), Ok(ids)) => {
let points = super::paint::picked_mesh_points_of(self, &ids);
let points = self.mesh_points_picked();
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
}
_ => TransparencyInfo::default(),
@@ -483,7 +483,8 @@ impl Session {
fn info(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let ids = transparency_targets(s, p)?;
let points = super::paint::picked_mesh_points_of(s, &ids);
// The points `transparency.set` with the same `ids` (or none) fades.
let points = if p.get("ids").is_none() && p.get("id").is_none() { s.mesh_points_picked() } else { super::paint::picked_mesh_points_of(s, &ids) };
let i = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
Ok(json!({
"ids": i.ids.iter().map(|id| id.0).collect::<Vec<_>>(),
+15 -11
View File
@@ -229,7 +229,7 @@ impl<'a> Collector<'a> {
Some((d, base)) => super::links::linked_files(d, base),
None => super::links::linked_files(doc, LinkBase::file(Some(source))),
};
doc.visit_placed(|_, p| {
super::links::with_brush_art(doc).visit_placed(|_, p| {
let page = (p.link.page.unwrap_or(1), p.bounding, p.page_box);
let pages = placed.entry(p.link.path.clone()).or_default();
if !pages.contains(&page) {
@@ -389,16 +389,20 @@ impl<'a> Collector<'a> {
}
if self.opts.relink {
// The child files have already been rewritten; the hash and size of each
// target must reflect the *packaged* bytes rather than the original.
doc.update_links(|link: &mut LinkInfo| {
if let Some(copy) = local.get(&link.path) {
let relative = relative_in_package(destination, &copy.name);
link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(&copy.name).to_string_lossy().into_owned());
link.relative = Some(relative);
link.size = copy.size;
link.hash = copy.hash.clone();
link.modified = None;
}
// target must reflect the *packaged* bytes rather than the original. The links in the
// art of the stored brushes are written back into the brush library.
let root = &self.root;
super::links::editing_brush_art(doc, |doc| {
doc.update_links(|link: &mut LinkInfo| {
if let Some(copy) = local.get(&link.path) {
let relative = relative_in_package(destination, &copy.name);
link.path = root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(&copy.name).to_string_lossy().into_owned());
link.relative = Some(relative);
link.size = copy.size;
link.hash = copy.hash.clone();
link.modified = None;
}
})
});
}
if let Some(s) = self.sections.get_mut(section) {
+74 -10
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency",
["Window", "Transparency"],
None,
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too",
has_doc,
transparency
),
@@ -154,7 +154,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Fill and Stroke",
[],
None,
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}",
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
always,
proxies
),
@@ -179,9 +179,13 @@ impl Session {
/// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
/// first selected object's own stack) for the proxy of its kind, else the first selected
/// object's (a group's first painted object's; type: its first run's), else the defaults for
/// new art.
/// new art. When the object whose fill the proxy shows is a gradient mesh with points picked
/// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid
/// fill color changes.
pub fn proxy_paints(&self) -> (Paint, Paint) {
let points = self.fill_mesh_points();
let show = |stroke: bool| match self.proxy_source(stroke) {
Some((n, None)) if !stroke && let Some(c) = picked_colors(&n, &points).first() => Paint::solid(*c),
Some((n, item)) => proxy_paint(&n, stroke, item),
None if stroke => self.paint.stroke.clone(),
None => self.paint.fill.clone(),
@@ -273,6 +277,13 @@ impl DocState {
/// each selected object's own stack is compared. One walk of the document, so callers that ask
/// every frame cache it by revision.
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
self.proxy_mixed_with(item, &[])
}
/// [`DocState::proxy_mixed`] with the gradient mesh points a solid fill color recolors
/// (`points`, see [`Session::fill_mesh_points`]): a mesh among them counts with the colors of
/// its picked points instead of its fill.
fn proxy_mixed_with(&self, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
if self.selection.is_empty() {
return (false, false);
}
@@ -291,7 +302,10 @@ impl DocState {
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
let set = if item.is_some() { &selected } else { &nodes };
let mut paints = set.iter().map(|n| proxy_paint(n, stroke, item));
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
});
let Some(p0) = paints.next() else { return false };
paints.any(|p| !same_in_proxy(&p0, &p))
};
@@ -313,8 +327,9 @@ impl DocState {
impl Session {
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
pub fn proxy_mixed(&self) -> (bool, bool) {
self.active().map_or((false, false), |st| st.proxy_mixed(self.appearance_item()))
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
}
}
@@ -539,8 +554,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let selected = item.targets(s, p)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let paint = if span { placed_across(&s.doc()?.doc, &ids, paint, p, fill) } else { paint };
// The gradient mesh points picked with the Mesh tool or Direct Selection: a solid fill
// recolours just those points of their meshes.
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
// Without `item`, unless the Appearance panel's active fill item takes the paint.
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
@@ -871,6 +886,55 @@ pub(crate) fn picked_mesh_points_of(s: &Session, ids: &[NodeId]) -> Option<Vec<(
(!ids.is_empty() && ids.iter().all(|id| v.iter().any(|(m, _)| m == id))).then_some(v)
}
/// The colors of the picked points of `n` (see [`picked_mesh_points`]) when it is a gradient mesh
/// among `points`, in the order they were picked; empty otherwise.
fn picked_colors(n: &Node, points: &[(NodeId, Vec<usize>)]) -> Vec<Color> {
match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) {
(NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.color).collect(),
_ => vec![],
}
}
impl Session {
/// The picked gradient mesh points that a solid fill color (`paint.setFill` without `ids` or
/// `item`) recolors instead of their meshes' fills, each mesh with its points: the targets are
/// resolved as [`set_paint`] resolves them, so this is empty while the Appearance panel's
/// active item is a fill row or an object of a symbol instance is selected, and a mesh with
/// points picked counts even when other objects are selected with it.
pub fn fill_mesh_points(&self) -> Vec<(NodeId, Vec<usize>)> {
let Some(st) = self.active() else { return vec![] };
// Only gradient meshes have points to pick: a selection with no mesh and no container that
// could hold one skips reading the tool's options.
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) {
return vec![];
}
let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] };
if item != ItemTarget::Top {
return vec![];
}
let Ok(selected) = item.targets(self, &Value::Null) else { return vec![] };
picked_mesh_points(self, &super::graph::paint_targets(&st.doc, &selected))
}
/// The picked gradient mesh points that the Transparency panel's opacity (`transparency.set`
/// without `ids` or `item`) fades instead of their objects: `None` unless every target is a
/// gradient mesh with points picked, and while the Appearance panel's active item takes the
/// opacity (outside opacity mask editing).
pub fn mesh_points_picked(&self) -> Option<Vec<(NodeId, Vec<usize>)>> {
let st = self.active()?;
let ids = super::opacitymask::transparency_targets(self, &Value::Null).ok()?;
// Only gradient meshes have points to pick: other targets skip reading the tool's options.
if ids.is_empty() || !ids.iter().all(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Mesh(_)))) {
return None;
}
if st.doc.mask_edit.is_none() && self.appearance_item().is_some() {
return None;
}
picked_mesh_points_of(self, &ids)
}
}
/// A type run's stroke; a painted stroke on a run without one gets 1 pt.
pub(super) fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
if !paint.is_none() {
@@ -1086,8 +1150,8 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
q.remove("item");
q.remove("id");
q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
// The gradient mesh points picked with the Mesh tool or Direct Selection take the opacity
// themselves, so only the mesh around them fades (#4206, #4170, #4208).
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take the
// opacity themselves, so only the mesh around them fades (#4206, #4170, #4208).
if matches!(item, ItemTarget::Top)
&& let Some(o) = q.get("opacity").and_then(Value::as_f64)
&& let Some(points) = picked_mesh_points_of(s, &ids)
+48 -23
View File
@@ -5,7 +5,7 @@ use serde_json::{Value, json};
use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify, TextRun};
use vectorcraft_geom::{Rect, Vec2};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, point_indices, switch_or};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or};
use crate::{Clipboard, EngineError};
pub fn specs() -> Vec<CommandSpec> {
@@ -137,19 +137,16 @@ pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec
return artboard_indices(d, p, cmd);
}
if let Some(recorded) = p.get("selectedArtboards") {
return artboard_indices(d, &json!({ "indices": recorded }), cmd);
return listed_artboards(d, recorded, "selectedArtboards", cmd);
}
let mut picked: Vec<u64> = t["selected"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_u64)
.filter(|i| usize::try_from(*i).is_ok_and(|i| i < d.artboards.len()))
.collect();
let mut picked: Vec<usize> =
t["selected"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(index).filter(|i| *i < d.artboards.len()).collect();
if picked.is_empty() {
picked.push(t["active"].as_u64().unwrap_or(0));
picked.push(on_board(d, t["active"].as_u64().map_or(0, index))?);
}
artboard_indices(d, &json!({ "indices": picked }), cmd)
picked.sort_unstable();
picked.dedup();
Ok(picked)
}
/// Rename Artboards: one artboard takes the name, and several take it numbered in artboard order, in
@@ -221,23 +218,51 @@ fn artboard_switch_orientation(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "switched": switched }))
}
/// The one artboard `cmd` acts on: `index`, an artboard of `d`, with the errors of
/// [`artboard_indices`] (`missing index`, `no such artboard`).
/// The one artboard `cmd` acts on: `index`, an artboard of `d`. Left out or null, it is
/// `missing index`; a value that is not a whole number is "`index` must be a whole number"; a
/// whole number past the last artboard is `no such artboard`.
pub(crate) fn artboard_index(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result<usize> {
let i = p.get("index").ok_or_else(|| bad(cmd, "missing index"))?;
artboard_indices(d, &json!({ "index": i }), cmd)?.into_iter().next().ok_or_else(|| EngineError::Other("no such artboard".into()))
artboard_at(d, p, "index", cmd)?.ok_or_else(|| bad(cmd, "missing index"))
}
/// The artboard of `d` that `key` of `p` names, or `None` when `p` leaves it out or gives null. A
/// value that is not a whole number is "`{key}` must be a whole number", and a whole number past the
/// last artboard is `no such artboard`.
pub(crate) fn artboard_at(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result<Option<usize>> {
super::index_opt(p, key, cmd)?.map(|i| on_board(d, i)).transpose()
}
/// `i` when it is an artboard of `d`, else `no such artboard`.
pub(crate) fn on_board(d: &vectorcraft_doc::Document, i: usize) -> Result<usize> {
match i < d.artboards.len() {
true => Ok(i),
false => Err(EngineError::Other("no such artboard".into())),
}
}
/// The artboards `cmd` acts on: `indices` (several), else `index` (one), each an artboard of `d`,
/// in order and once each.
/// in order and once each. `indices` is read as [`listed_artboards`] reads it, and `index` as
/// [`artboard_index`] reads it.
pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &str) -> Result<Vec<usize>> {
let listed = match (p.get("indices"), p.get("index")) {
(Some(v), _) => point_indices(v),
(None, Some(i)) => point_indices(&json!([i])),
(None, None) => return Err(bad(cmd, "missing index")),
};
let mut indices =
listed.filter(|v| !v.is_empty() && v.iter().all(|i| *i < d.artboards.len())).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
match p.get("indices") {
Some(v) => listed_artboards(d, v, "indices", cmd),
None => Ok(vec![artboard_index(d, p, cmd)?]),
}
}
/// `v`, the value of `key`, as artboards of `d`, in order and once each. A value that is not a list
/// is "`{key}` must be a list of artboard indices", an empty list is "`{key}` must be a non-empty
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
/// is checked for its form before any is checked against the artboards.
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
if entries.is_empty() {
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
}
let listed = entries.iter().map(Value::as_u64).collect::<Option<Vec<u64>>>();
let listed = listed.ok_or_else(|| bad(cmd, format!("`{key}` must contain whole numbers")))?;
let mut indices = listed.into_iter().map(|i| on_board(d, index(i))).collect::<Result<Vec<usize>>>()?;
indices.sort_unstable();
indices.dedup();
Ok(indices)
+23 -21
View File
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reverse Path Direction",
["Object", "Path"],
None,
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step → {changed: paths}",
"{ids?|id?, subpath?: usize (reverse only this subpath of each path, 0 included; default: every subpath), reversed?: bool (true: every subpath runs counter-clockwise on screen, false: clockwise, the Attributes panel's Reverse Path Direction On / Off; omitted: flip each path; with subpath, the direction is not read: that subpath is flipped)} the paths in ids or the selection (groups and compound paths: the paths inside), as one undo step; when every subpath of a path turns alike, its strokes' width profiles (sides swapped) and pen pressure, tilt, bearing and rotation turn with it, so they draw as before → {changed: paths}",
has_selected_path,
reverse
),
@@ -315,13 +315,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?);
let independent = switch_or(p, "independent", false, "path.setHandle")?;
// A handle already there, on an anchor already of the kind it would get, changes nothing and
// records no undo step.
if let Some(a) = anchor_of(s, id, si, ai)? {
let mut b = a;
b.set_handle(out, pos, independent);
if b == a {
return ok();
}
// records no undo step. The handle is compared directly: `set_handle` would recompute the
// other handle of a smooth anchor, which need not give back the same value.
if let Some(a) = anchor_of(s, id, si, ai)?
&& (if out { a.h_out } else { a.h_in }) == pos
&& !(independent && a.kind != AnchorKind::Corner)
{
return ok();
}
s.edit("Reshape", |d, _| {
let path = path_mut(d, id)?;
@@ -462,22 +462,24 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
let mut changed = 0;
for id in &ids {
let path = path_mut(d, *id)?;
if let Some(si) = subpath {
if let Some(sp) = path.subpaths.get_mut(si) {
let flip: Vec<bool> = match subpath {
Some(si) => (0..path.subpaths.len()).map(|i| i == si).collect(),
None => path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect(),
};
if !flip.contains(&true) {
continue;
}
// The stroke's width profile and pen recordings turn with the path, read before it turns.
if let Some(n) = d.node_mut(*id) {
vectorcraft_doc::blend::reverse_stroke_records(n, &flip);
}
let path = path_mut(d, *id)?;
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
if f {
sp.reverse();
changed += 1;
}
} else {
let flip: Vec<bool> = path.subpaths.iter().map(|sp| want.is_none_or(|ccw| (sp.signed_area() < 0.0) != ccw)).collect();
if flip.contains(&true) {
for (sp, f) in path.subpaths.iter_mut().zip(flip) {
if f {
sp.reverse();
}
}
changed += 1;
}
}
changed += 1;
}
Ok(changed)
})?;
+16 -5
View File
@@ -19,7 +19,7 @@ use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace}
use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid};
use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey};
use super::distortcmds::{grid_of, silent, store_grid};
use super::distortcmds::{grid_kept, grid_of, silent, store_grid};
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name};
pub fn specs() -> Vec<CommandSpec> {
@@ -261,10 +261,21 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result<Value> {
let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?;
// The objects stay attached and the view options stay as they were.
let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g };
s.edit("Perspective Grid Preset", |d, _| {
store_grid(d, &g);
Ok(())
})?;
// When the document holds this grid already, apart from whether it shows and its active plane,
// the preset only sets those two, without an undo step (as perspective.grid.show and
// perspective.plane.set do).
let view = PerspectiveGrid { visible: old.visible, plane: old.plane, ..g.clone() };
if !grid_kept(&s.doc()?.doc, &view) {
s.edit("Perspective Grid Preset", |d, _| {
store_grid(d, &g);
Ok(())
})?;
} else if (old.visible, old.plane) != (g.visible, g.plane) {
silent(s, |cur| {
cur.visible = g.visible;
cur.plane = g.plane;
})?;
}
Ok(g.definition_json())
}
+5 -3
View File
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
has_doc,
place
),
@@ -962,8 +962,10 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
(None, [id]) => *id,
_ => return Err(bad(C, "select one image or pass id")),
};
// An image in opacity-mask art or a definition's art is found by its id too (`links.list`).
let n = st.doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
// An image in opacity-mask art, a definition's art or a stored brush's art is found by its id
// too (`links.list`).
let doc = super::links::with_brush_art(&st.doc);
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
let [a, b, c, d, ..] = im.xf.as_coeffs();
+4 -3
View File
@@ -330,7 +330,8 @@ pub(crate) fn node(d: &mut Document, s: &Source, link: LinkInfo, bounding: bool)
}
/// `d` for output: linked images and placed documents that keep only their previews get their
/// files back, else output as their previews, with a warning.
/// files back, else output as their previews, with a warning. The art of the stored brushes counts
/// too.
pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let (d, mut warnings) = super::super::links::full_linked_images(d, Default::default());
let doc = match &d {
@@ -339,7 +340,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
};
let mut need: Vec<PlacedDocument> = vec![];
let mut seen = std::collections::HashSet::new();
doc.visit_placed(|_, p| {
super::super::links::with_brush_art(doc).visit_placed(|_, p| {
if doc.images.get(&p.key).is_some_and(ImageBlob::is_proxy) && seen.insert(p.key.clone()) {
need.push(p.clone());
}
@@ -370,7 +371,7 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
"{n} placed documents output as their previews: their files can't be found, or changed since they were read (relink or update them)"
),
});
out.placed_as_previews(&previews);
super::super::links::editing_brush_art(&mut out, |out| out.placed_as_previews(&previews));
}
(Cow::Owned(out), warnings)
}
+16 -3
View File
@@ -3,6 +3,7 @@
use serde_json::Value;
use super::super::utf16_order_without_mark;
use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param};
/// Text files as `file.place` reports them (not a format `document.open` reads).
@@ -76,8 +77,10 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result<String>
Ok(clean(&decode(bytes, o), o))
}
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark; bytes that aren't UTF-8 are
/// read as the platform's 8-bit set), or the platform's 8-bit character set.
/// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the
/// file has an even length, reads as valid UTF-16 with no NUL character in the byte order
/// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit
/// set), or the platform's 8-bit character set.
fn decode(bytes: &[u8], o: TextOptions) -> String {
let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() };
if o.ansi {
@@ -91,7 +94,17 @@ fn decode(bytes: &[u8], o: TextOptions) -> String {
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
_ => std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string),
_ => {
let without_mark = (bytes.len().is_multiple_of(2) && bytes.contains(&0))
.then(|| utf16_order_without_mark(bytes))
.flatten()
.and_then(|le| {
let units = bytes.as_chunks::<2>().0.iter().map(|&c| if le { u16::from_le_bytes(c) } else { u16::from_be_bytes(c) });
char::decode_utf16(units).collect::<std::result::Result<String, _>>().ok()
})
.filter(|text| !text.contains('\0'));
without_mark.unwrap_or_else(|| std::str::from_utf8(bytes).map_or_else(|_| eight_bit(bytes), str::to_string))
}
}
}
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more