mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 14:14:50 +00:00
Merge main into fix/js-interp-errors-translated
This commit is contained in:
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
//! 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,
|
||||
@@ -172,6 +172,85 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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 +1173,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 +1314,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 +1417,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 +1866,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,11 +1900,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, 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"];
|
||||
/// 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 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;
|
||||
@@ -1905,6 +1994,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 +2207,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 +2221,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 +2256,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 +2307,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 +2980,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(¬es, "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(&[¬es, &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(&[¬es, &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 +3176,70 @@ mod tests {
|
||||
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+104
-12
@@ -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)]
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
+142
-15
@@ -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))
|
||||
}
|
||||
})
|
||||
@@ -2462,6 +2483,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)]| {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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))));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
+100
-13
@@ -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
@@ -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;
|
||||
|
||||
@@ -367,6 +367,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 {
|
||||
|
||||
@@ -248,14 +248,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 +385,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 +411,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 +474,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);
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
+86
-27
@@ -2,7 +2,7 @@
|
||||
//! 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;
|
||||
|
||||
@@ -26,6 +26,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 +54,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 +96,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 +106,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 +121,19 @@ 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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SymbolBoxes<'a> {
|
||||
@@ -120,6 +142,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 +202,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 +355,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 +387,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,7 +436,7 @@ 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 art = self.symbol_art(name)?;
|
||||
let most = match self.doc.symbol_slice_map(name, linear) {
|
||||
Some(m) => m.most_placed(art, self.doc),
|
||||
None => art.count_with_masks() as u64,
|
||||
@@ -431,11 +488,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 +521,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());
|
||||
|
||||
@@ -201,6 +201,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`]);
|
||||
@@ -226,6 +229,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.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
+85
-27
@@ -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);
|
||||
|
||||
@@ -1760,6 +1760,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]
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -663,10 +664,16 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
/// 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())
|
||||
/// 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<Vec<WireFace>, 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
|
||||
@@ -682,7 +689,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
|
||||
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);
|
||||
}
|
||||
@@ -695,7 +702,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec
|
||||
return Err("the revolved object has no fill or stroke".into());
|
||||
}
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
return faces(&path, b, fx_options(fx));
|
||||
return faces(&path, b, fx, fx_options(fx));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
let mut out = vec![];
|
||||
@@ -705,7 +712,7 @@ 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 }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<Path
|
||||
// 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: Vec<PathData> = after_geometry(doc, n, faces, 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"));
|
||||
@@ -65,29 +65,46 @@ 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> {
|
||||
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<WireFace>, 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) })
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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))];
|
||||
Arc::new(Node::path(id, f.path, Appearance { items, ..Default::default() }))
|
||||
};
|
||||
let mut art = Node::group(id, 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()));
|
||||
art.walk(&mut |c| {
|
||||
if let Some(path) = c.path_data() {
|
||||
out.push(WireFace { path: path.clone(), stroke: c.appearance.stroke().map_or(0.0, |s| s.width) });
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
@@ -95,7 +112,7 @@ pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext
|
||||
/// 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> {
|
||||
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<WireFace>, 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))?;
|
||||
@@ -126,17 +143,20 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, S
|
||||
/// 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 +164,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)
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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() }))
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,14 +859,14 @@ 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);
|
||||
@@ -857,7 +882,8 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
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) {
|
||||
out.push((id, break_cuts(&t.plain_text(), 0, usize::MAX, brk)));
|
||||
}
|
||||
@@ -891,10 +917,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,196 @@ fn remove_breaks_reads_the_threads_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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"][..])] {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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) };
|
||||
|
||||
@@ -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(¶ms).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)
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -49,6 +49,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 +304,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 +319,11 @@ 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();
|
||||
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
let mut open = sp.clone();
|
||||
@@ -256,7 +338,9 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
|
||||
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))
|
||||
}
|
||||
@@ -621,6 +705,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]
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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, ©.name);
|
||||
link.path = self.root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.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, ©.name);
|
||||
link.path = root.as_ref().map_or_else(|| copy.name.clone(), |r| r.join(©.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) {
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ use vectorcraft_doc::{Effect, Node};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
use crate::store::StoreTurn;
|
||||
|
||||
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
|
||||
|
||||
@@ -683,6 +684,9 @@ thread_local! {
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after it installs and before it
|
||||
/// writes the store.
|
||||
pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`keep_installed`] has written the module to the store
|
||||
/// and before it writes the grant.
|
||||
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
@@ -718,7 +722,9 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store
|
||||
/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant
|
||||
/// held for its id. A `plugin.remove` in another session waits until the install has written the
|
||||
/// store.
|
||||
/// store. With a plug-in store, all of it happens in a turn on the store ([`StoreTurn`]), so another
|
||||
/// process using the same folder changes it before or after; when the store can't be locked, nothing
|
||||
/// is installed.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
@@ -736,8 +742,11 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
// A removal in another session waits until the store holds what this install wrote.
|
||||
// A removal in another session waits until the store holds what this install wrote, and so
|
||||
// does a change of the store by another process.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn =
|
||||
s.plugin_store_turn().map_err(|e| EngineError::Other(format!("{C}: {}: {e}: nothing was installed", crate::store::STORE_NOT_LOCKED)))?;
|
||||
// The grant the checks below count on, the approval included. The install checks it again,
|
||||
// with the plug-in installed under the id, before anything is stored: another session may
|
||||
// change either in between.
|
||||
@@ -844,41 +853,12 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The plug-in gets the settings and cache kept for its id. A module without permissions takes
|
||||
// the id over, so nothing the user approved for the id applies any more.
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?;
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&turn, &id), err)?;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_STORE.take() {
|
||||
between();
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
// held back. A failed write of that module is only logged: the store then holds the new module,
|
||||
// which the grant doesn't cover. A write that reports a failure may still have put the old
|
||||
// module back, so the store is read again to tell which module it holds. A stored module that
|
||||
// can't be read back isn't replaced by one that needs a grant.
|
||||
let previous = s.stored_plugin_bytes(&id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if asks {
|
||||
if stored && !s.store_grant(&id, Some(g)) {
|
||||
stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
} else {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for every session in
|
||||
// the process attached to the folder. A grants file that is too large or doesn't hold a list
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
let stored = keep_installed(s, &turn, &id, &bytes, asks.then_some(g));
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
@@ -891,8 +871,9 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
drop(turn);
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -900,6 +881,53 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Keeps the plug-in `id` that `plugin.install` installed, its module `bytes`, in the plug-in store,
|
||||
/// in `turn`, with `grant` when its module lists permissions (`None`: it lists none, and the grant
|
||||
/// held for the id is removed) → whether the store now holds the new module (`false` without a
|
||||
/// store).
|
||||
///
|
||||
/// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
/// grant only once it is there; when the grant can't be written, the store gets the module it held
|
||||
/// back. A failed write of that module is only logged: the store then holds the new module, which
|
||||
/// the grant doesn't cover. A write that reports a failure may still have put the old module back,
|
||||
/// so the store is read again to tell which module it holds. A stored module that can't be read back
|
||||
/// isn't replaced by one that needs a grant.
|
||||
pub(crate) fn keep_installed(s: &Session, turn: &StoreTurn, id: &str, bytes: &[u8], grant: Option<Grant>) -> bool {
|
||||
let asks = grant.is_some();
|
||||
let previous = s.stored_plugin_bytes(id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(turn, id, bytes);
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_GRANT_STORED.take() {
|
||||
between();
|
||||
}
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(id).is_ok_and(|held| held.as_deref() == Some(bytes));
|
||||
match grant {
|
||||
Some(g) => {
|
||||
if stored && !s.store_grant_in(turn, id, Some(g)) {
|
||||
stored = !s.put_back_plugin(turn, id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant
|
||||
// at the next launch. A grant that can't be removed still approves the old bytes, so the
|
||||
// store gets the module it held back. When that module can't be read or written back, or
|
||||
// there was none, no module goes with the grant, and the grant stops counting for every
|
||||
// session in the process attached to the folder. A grants file that is too large or
|
||||
// doesn't hold a list approves nothing, and the new module stays; one that can't be
|
||||
// opened or read may approve the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant_in(turn, id, None) && s.holds_plugin_grant(id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(turn, id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stored
|
||||
}
|
||||
|
||||
/// `plugin.inspect`: what installing the module would install, without installing it, whether that
|
||||
/// needs the user to grant its permissions first (`needsApproval`) and whether it would take
|
||||
/// another module's place (`needsReplace`).
|
||||
@@ -992,15 +1020,17 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session finishes writing the store first.
|
||||
// A `plugin.install` in another session or process finishes writing the store first. When the
|
||||
// store can't be locked, the folder still loads, and the store isn't written.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins();
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
|
||||
}
|
||||
@@ -1140,6 +1170,9 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
|
||||
};
|
||||
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
|
||||
// The list is changed and saved in one turn on the plug-in store, so that an install in another
|
||||
// process doesn't change the store in between.
|
||||
let turn = s.plugin_store_turn().ok();
|
||||
if enabled && !safe_mode::disabled().iter().any(|i| items.iter().any(|item| i.same(item))) {
|
||||
return Err(bad(C, "that plug-in isn't disabled (see plugin.safeMode)"));
|
||||
}
|
||||
@@ -1149,7 +1182,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Without a plug-in folder (a session confined to automation roots), or when the list there
|
||||
// can't take the change, the change stays in this process and goes with the next change that saves.
|
||||
let saved = !changed || s.store_disabled_plugins();
|
||||
let saved = !changed || turn.as_ref().is_some_and(|turn| s.store_disabled_plugins_in(turn));
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
@@ -1164,31 +1197,35 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// An install in another session finishes its store writes first.
|
||||
// An install in another session or process finishes its store writes first. When the store
|
||||
// can't be locked, nothing is removed.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s
|
||||
.plugin_store_turn()
|
||||
.map_err(|e| EngineError::Other(format!("plugin.remove: {}: {e}: nothing was removed", crate::store::STORE_NOT_LOCKED)))?;
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id);
|
||||
let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(id, forget).err().map(|e| e.to_string())
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
};
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
s.unstore_plugin(id);
|
||||
s.unstore_plugin(&turn, id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
}
|
||||
@@ -1248,7 +1285,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -1266,7 +1303,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Graphic Style Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcstyles library, or the graphic styles of any document VectorCraft opens (see document.formats), for the library panel (Window → Graphic Style Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library; a .ai or EPS style painting with one of the file's gradients by name takes it at the style's angle, fitted to each object it is applied to, VectorCraft's own placement) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Options",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
|
||||
has_doc,
|
||||
swatch_edit
|
||||
),
|
||||
@@ -187,11 +187,7 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})),
|
||||
Paint::None => Err(bad(C, "a swatch needs a colour, gradient or pattern")),
|
||||
_ if spot || mode.is_some() || group.is_some() => Err(bad(C, "spot, mode and group apply to solid colours only")),
|
||||
// The swatch holds the gradient itself, not a link to the swatch it may have come from.
|
||||
// It keeps `geom`, which holds the aspect the swatch is applied with.
|
||||
Paint::Gradient(g) => Ok(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g }))),
|
||||
// The swatch holds the pattern untransformed, not the placement of the art it came from.
|
||||
Paint::Pattern { pattern, .. } => Ok(pattern_paint(&pattern)),
|
||||
paint @ (Paint::Gradient(_) | Paint::Pattern { .. }) => Ok(stored_paint(paint, p)),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// A name applies to a single new swatch.
|
||||
@@ -220,6 +216,27 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
match paint {
|
||||
// A gradient given an `aspect` but no vector is placed on a box so that the swatch keeps
|
||||
// the aspect, as `paint.setFill` places it on each object.
|
||||
Paint::Gradient(ref g) if g.geom.is_none() && g.freeform.is_none() => {
|
||||
match super::gradient::place_paint(&paint, p, Some(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0))) {
|
||||
Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
// The swatch holds the gradient itself, not a link to the swatch it may have come from.
|
||||
// It keeps `geom`, which holds the aspect the swatch is applied with.
|
||||
Paint::Gradient(g) => Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { swatch: None, ..*g })),
|
||||
// The swatch holds the pattern untransformed, not the placement of the art it came from.
|
||||
Paint::Pattern { pattern, .. } => pattern_paint(&pattern),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `names` list and `name` parameters, without repeats; at least one is required.
|
||||
pub(super) fn names_param(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
@@ -866,12 +883,21 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// A replacement paint of the swatch's kind (a dropped colour or edited gradient).
|
||||
let paint = match p.get("paint").filter(|v| !v.is_null()) {
|
||||
Some(v) => match (if given("mode") { paint_from(s, &keeping_model(v))? } else { paint_from(s, v)? }, &sw.paint) {
|
||||
Some(v) => match (
|
||||
// A pattern by name, as `swatch.new` takes it.
|
||||
match str_param(v, "pattern") {
|
||||
Some(pat) if d.pattern(pat).is_some() => Some(pattern_paint(pat)),
|
||||
Some(pat) => return Err(bad(C, format!("no pattern `{pat}`"))),
|
||||
None if given("mode") => paint_from(s, &keeping_model(v))?,
|
||||
None => paint_from(s, v)?,
|
||||
},
|
||||
&sw.paint,
|
||||
) {
|
||||
(Some(Paint::Solid { color, .. }), Paint::Solid { .. }) => Some(Paint::solid(color)),
|
||||
(Some(Paint::Gradient(g)), Paint::Gradient(_)) => {
|
||||
Some(Paint::Gradient(Box::new(vectorcraft_color::GradientPaint { geom: None, swatch: None, ..*g })))
|
||||
// Stored as `swatch.new` stores it.
|
||||
(Some(new @ Paint::Gradient(_)), Paint::Gradient(_)) | (Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => {
|
||||
Some(stored_paint(new, v))
|
||||
}
|
||||
(Some(new @ Paint::Pattern { .. }), Paint::Pattern { .. }) => Some(new),
|
||||
_ => return Err(bad(C, format!("`{name}` takes a paint of its own kind (colour, gradient or pattern)"))),
|
||||
},
|
||||
None => None,
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vertical",
|
||||
["Type", "Orientation"],
|
||||
None,
|
||||
"{ids?|id?} set vertical writing for the selected type and every frame of its threads → {vertical, ids}",
|
||||
"{ids?|id?} set vertical writing for the selected type and every frame of its threads; no undo step when every object is already vertical → {vertical, ids}",
|
||||
has_selection,
|
||||
|s, p| orientation(s, p, true)
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Horizontal",
|
||||
["Type", "Orientation"],
|
||||
None,
|
||||
"{ids?|id?} set horizontal writing for the selected type and every frame of its threads → {vertical, ids}",
|
||||
"{ids?|id?} set horizontal writing for the selected type and every frame of its threads; no undo step when every object is already horizontal → {vertical, ids}",
|
||||
has_selection,
|
||||
|s, p| orientation(s, p, false)
|
||||
),
|
||||
@@ -59,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Optical Margin Alignment",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered → {on, ids}",
|
||||
"{ids?|id?, on?: bool} turn Optical Margin Alignment on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting): in every paragraph of point and area type, quotation marks, hyphens, full stops and commas at a line's start or end hang wholly outside the margin there; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their advance; a left-aligned line hangs at its left margin, a right-aligned line hangs at its right margin, and centered and justified lines hang at both; Auto aligns a right-to-left line at its right; type on a path hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered; no undo step when every object already has the setting → {on, ids}",
|
||||
has_selection,
|
||||
optical_margin_alignment
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"System Layout",
|
||||
[],
|
||||
None,
|
||||
"{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting → {on}",
|
||||
"{on?: bool} turn System Layout on or off for the document (on omitted: the opposite of the document's setting) and every text object in it. On, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. Off (the default, and what a document from before it reads as), spacing uses fractions of a point. New point, area and path type inherits the document's setting. No undo step when the document and every text object already have the setting → {on}",
|
||||
has_doc,
|
||||
system_layout
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fractional Widths",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters → {on, ids}",
|
||||
"{ids?|id?, on?: bool} turn Fractional Widths on or off for the selected type and every frame of its threads (on omitted: the opposite of the first object's setting). On (the default, and what a document from before it reads as), spacing between characters uses fractions of a point. Off, each character that takes any space advances by a whole number of points, at least one, so small type does not run together; a character with no width stays at none. The setting is the whole type object, not a range of characters. No undo step when every object already has the setting → {on, ids}",
|
||||
has_selection,
|
||||
fractional_widths
|
||||
),
|
||||
@@ -157,24 +157,30 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// Type › Type Orientation: set vertical or horizontal writing on every selected text object and
|
||||
/// every frame of their threads, in one undo step.
|
||||
/// every frame of their threads, in one undo step (none when nothing changes).
|
||||
fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Text Orientation")?);
|
||||
s.edit("Text Orientation", |d, _| {
|
||||
// When every object already has the orientation, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Text Orientation", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.vertical = vertical;
|
||||
refresh_bounds(t);
|
||||
if t.vertical != vertical {
|
||||
t.vertical = vertical;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"vertical": vertical, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Type › Optical Margin Alignment: set `on` (without it, the opposite of the first object's
|
||||
/// setting) on every selected text object and every frame of their threads, in one undo step.
|
||||
/// setting) on every selected text object and every frame of their threads, in one undo step
|
||||
/// (none when nothing changes).
|
||||
fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Optical Margin Alignment")?);
|
||||
let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) {
|
||||
@@ -182,29 +188,38 @@ fn optical_margin_alignment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let on = switch_or(p, "on", !first.unwrap_or(false), "type.opticalMarginAlignment")?;
|
||||
s.edit("Optical Margin Alignment", |d, _| {
|
||||
// When every object already has the setting, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Optical Margin Alignment", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.optical_margin = on;
|
||||
refresh_bounds(t);
|
||||
if t.optical_margin != on {
|
||||
t.optical_margin = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Character panel menu › System Layout: set `on` (without it, the opposite of the document's
|
||||
/// setting) on the document and every text object, in one undo step. Off is the default.
|
||||
/// setting) on the document and every text object, in one undo step (none when nothing changes).
|
||||
/// Off is the default.
|
||||
fn system_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let current = s.doc()?.doc.setup.system_layout;
|
||||
let on = switch_or(p, "on", !current, "type.systemLayout")?;
|
||||
s.edit("System Layout", |d, _| {
|
||||
// When the document and every text object already have the setting, the document and its undo
|
||||
// history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "System Layout", |_, d| {
|
||||
let mut changed = d.setup.system_layout != on;
|
||||
d.setup.system_layout = on;
|
||||
let mut ids = vec![];
|
||||
d.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
if matches!(&n.kind, NodeKind::Text(t) if t.system_layout != on) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
@@ -214,15 +229,16 @@ fn system_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
t.system_layout = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({ "on": on }))
|
||||
}
|
||||
|
||||
/// Character panel menu › Fractional Widths: set `on` (without it, the opposite of the first
|
||||
/// object's setting) on every selected text object and every frame of their threads, in one undo
|
||||
/// step. On is the default.
|
||||
/// step (none when nothing changes). On is the default.
|
||||
fn fractional_widths(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::threads::with_threads(&s.doc()?.doc, &text_targets(s, p, "Fractional Widths")?);
|
||||
let first = ids.first().and_then(|id| match s.doc().ok()?.doc.node(*id).map(|n| &n.kind) {
|
||||
@@ -230,15 +246,20 @@ fn fractional_widths(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
});
|
||||
let on = switch_or(p, "on", !first.unwrap_or(true), "type.fractionalWidths")?;
|
||||
s.edit("Fractional Widths", |d, _| {
|
||||
// When every object already has the setting, the document and its undo history stay as they are.
|
||||
super::colorcmds::edit_if_changed(s, "Fractional Widths", |_, d| {
|
||||
let mut changed = false;
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
};
|
||||
t.fractional_widths = on;
|
||||
refresh_bounds(t);
|
||||
if t.fractional_widths != on {
|
||||
t.fractional_widths = on;
|
||||
refresh_bounds(t);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(((), changed))
|
||||
})?;
|
||||
Ok(json!({"on": on, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
@@ -199,8 +199,11 @@ fn optical_margin_alignment_is_set_per_object_and_saved_only_when_on() {
|
||||
assert!(left(&s) < inside - 5.0, "{} {inside}", left(&s));
|
||||
assert_eq!(serde_json::to_value(text(&s)).unwrap()["opticalMarginAlignment"], true);
|
||||
// `on` sets it; without `on` it toggles.
|
||||
// Setting the value the type already has: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.opticalMarginAlignment", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert!(text(&s).optical_margin);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(s.execute("type.opticalMarginAlignment", &json!({})).unwrap()["on"], false);
|
||||
assert!(!text(&s).optical_margin);
|
||||
assert_eq!(left(&s), inside);
|
||||
@@ -247,6 +250,10 @@ fn system_layout_sets_the_document_and_every_text_object() {
|
||||
assert!(fractional.iter().zip(&whole).any(|(a, b)| (a - b).abs() > 0.05), "{fractional:?} {whole:?}");
|
||||
assert_eq!(serde_json::to_value(setup(&s)).unwrap()["systemLayout"], true);
|
||||
assert_eq!(serde_json::to_value(text(&s, id)).unwrap()["systemLayout"], true);
|
||||
// Setting the value the document and its type already have: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.systemLayout", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
// New type inherits the document's setting.
|
||||
let made = s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Z"})).unwrap()["id"].as_u64().unwrap();
|
||||
assert!(text(&s, made).system_layout);
|
||||
@@ -305,6 +312,10 @@ fn fractional_widths_is_set_per_object_and_saved_only_when_off() {
|
||||
assert!(text(&s).fractional_widths);
|
||||
assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert!(!text(&s).fractional_widths);
|
||||
// Setting the value the type already has: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("type.fractionalWidths", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
// One undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(text(&s).fractional_widths);
|
||||
@@ -2331,8 +2342,17 @@ fn vertical_point_type_keeps_its_anchor_on_the_column_centre_line() {
|
||||
let tall = bounds(&s);
|
||||
assert!(tall.height() > tall.width(), "{tall:?}");
|
||||
assert!((tall.center().x - 100.0).abs() < 6.0, "the anchor stays on the column's centre line: {tall:?}");
|
||||
// Vertical type set vertical again: no undo step.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("type.orientation.vertical", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
assert_eq!(bounds(&s), tall);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(bounds(&s), wide);
|
||||
// Horizontal type set horizontal: no undo step either.
|
||||
let n = s.doc().unwrap().history.undo.len();
|
||||
s.execute("type.orientation.horizontal", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+180
-53
@@ -17,9 +17,8 @@
|
||||
//! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named
|
||||
//! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it.
|
||||
//! Attaching the folder installs them again, except in Safe Mode and except the ones the user
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`; a window locks
|
||||
//! `disabled.lock` while it writes the list). The Additional Plug-ins Folder preference is not
|
||||
//! copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional
|
||||
//! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins
|
||||
//! stored there that list permissions (id, module hash, permissions); a stored plug-in whose
|
||||
//! permissions it doesn't grant is skipped with a log record, and stays in the folder.
|
||||
//! * **Plug-in settings and caches**: `storage/id-<id>/` in the plug-in store, the id written as
|
||||
@@ -27,6 +26,11 @@
|
||||
//! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a
|
||||
//! `cache` folder with one file per entry. The host names every file; a plug-in only names keys.
|
||||
//! Replacing a plug-in keeps them, and `plugin.remove` deletes them.
|
||||
//! * **Turns on the plug-in store**: a window or process locks `disabled.lock` in the plug-in folder
|
||||
//! ([`StoreTurn`]) while it reads and changes the stored plug-ins, `grants.json`, `disabled.json`
|
||||
//! and the plug-ins' settings and caches, so that two of them using one folder change it one after
|
||||
//! the other: an install's module and grant are written in one turn, and a grant written for one
|
||||
//! plug-in doesn't undo another one's.
|
||||
//!
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
@@ -62,12 +66,15 @@ pub const MAX_PLUGIN_STORE: u64 = 512 << 20;
|
||||
const PLUGIN_EXT: &str = "wasm";
|
||||
/// The file in the plug-in folder that lists the plug-ins the user disabled.
|
||||
pub const DISABLED_FILE: &str = "disabled.json";
|
||||
/// The file in the plug-in folder that a window locks while it reads and writes [`DISABLED_FILE`].
|
||||
/// The file in the plug-in folder that a window locks while it reads and changes the plug-in store
|
||||
/// ([`StoreTurn`]), [`DISABLED_FILE`] included.
|
||||
pub const DISABLED_LOCK: &str = "disabled.lock";
|
||||
/// The file in the plug-in store that holds the permissions the user granted.
|
||||
const GRANTS_FILE: &str = "grants.json";
|
||||
/// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`].
|
||||
pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store";
|
||||
/// The error of a change to the plug-in store that can't take its turn ([`StoreTurn`]).
|
||||
pub(crate) const STORE_NOT_LOCKED: &str = "the plug-in store can't be locked";
|
||||
/// The largest grants file read.
|
||||
const MAX_GRANTS_FILE: u64 = 1 << 20;
|
||||
/// The folder in the plug-in store that holds each plug-in's settings and cache.
|
||||
@@ -84,7 +91,7 @@ const CACHE_EXT: &str = "bin";
|
||||
/// A write to a folder that holds more is refused as full.
|
||||
pub(crate) const MAX_CACHE_SCAN: usize = storage::MAX_CACHE_ENTRIES * 2;
|
||||
/// Held while a plug-in's settings or cache change, so two runs can't pass a cap together or lose
|
||||
/// each other's settings.
|
||||
/// each other's settings. Taken after the plug-in store's turn ([`StoreTurn`]), never before it.
|
||||
static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
|
||||
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
|
||||
/// the plug-in is removed, which closes it and drops it.
|
||||
@@ -99,7 +106,7 @@ const MAX_GRANT_WRITES_KEPT: usize = 256;
|
||||
struct IgnoredGrants {
|
||||
/// The grants that should be gone but could not be removed: no session in the process counts
|
||||
/// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id
|
||||
/// ([`Session::store_grant`]).
|
||||
/// ([`Session::store_grant_in`]).
|
||||
ignored: BTreeSet<(PathBuf, String)>,
|
||||
/// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the
|
||||
/// count of writes it made ([`IgnoredGrants::writes`]).
|
||||
@@ -217,23 +224,53 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, locked until the file is dropped, waiting while another window holds
|
||||
/// it; `None` when it can't be opened or locked.
|
||||
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while
|
||||
/// another window or process holds it, or another handle in this process. The file is opened for
|
||||
/// reading and writing (a handle that only appends can't be locked on Windows) and is never
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_disabled(dir: &Path) -> Option<std::fs::File> {
|
||||
let opened = std::fs::create_dir_all(dir)
|
||||
.and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK)));
|
||||
let file = opened.and_then(|f| f.lock().map(|()| f));
|
||||
if let Err(e) = &file {
|
||||
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
file.ok()
|
||||
#[cfg(test)]
|
||||
if let Some(waiting) = WHILE_STORE_LOCKED.take() {
|
||||
waiting();
|
||||
}
|
||||
file.lock()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_disabled(_: &Path) -> Option<std::fs::File> {
|
||||
None
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// A turn on a plug-in store ([`Session::plugin_store_turn`]): while it is held, no other window or
|
||||
/// process that takes one reads and changes the store's plug-ins, grants, disabled list, settings
|
||||
/// or caches. Dropping it ends the turn. A turn is taken once per operation and handed to the
|
||||
/// functions it calls, since a second lock of the same file by the same thread waits for ever.
|
||||
pub(crate) struct StoreTurn {
|
||||
/// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without
|
||||
/// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store.
|
||||
lock: Option<std::fs::File>,
|
||||
}
|
||||
|
||||
impl StoreTurn {
|
||||
/// A turn that isn't held, for a load that goes ahead without one: it writes nothing.
|
||||
pub(crate) fn unheld() -> Self {
|
||||
StoreTurn { lock: None }
|
||||
}
|
||||
|
||||
/// Whether the store may be written in this turn.
|
||||
fn held(&self) -> bool {
|
||||
self.lock.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -252,6 +289,15 @@ thread_local! {
|
||||
/// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`])
|
||||
/// fails on this thread, as on a full volume.
|
||||
pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: runs once on this thread when locking the plug-in store ([`lock_store`]) finds it
|
||||
/// locked and waits.
|
||||
pub(crate) static WHILE_STORE_LOCKED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when a grant write has read `grants.json` and before it
|
||||
/// writes the file.
|
||||
pub(crate) static AFTER_GRANTS_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when a change of a plug-in's settings has read them and
|
||||
/// before it writes them.
|
||||
pub(crate) static AFTER_SETTINGS_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
|
||||
@@ -401,11 +447,14 @@ impl Session {
|
||||
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
|
||||
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
|
||||
let disabled =
|
||||
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
self.plugin_dir = Some(dir);
|
||||
self.load_stored_plugins();
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
self.load_stored_plugins_in(&turn);
|
||||
}
|
||||
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
@@ -415,14 +464,25 @@ impl Session {
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]).
|
||||
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]).
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
if self.plugin_dir.is_none() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
self.load_stored_plugins_in(&turn);
|
||||
}
|
||||
|
||||
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
|
||||
/// is held.
|
||||
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
@@ -454,7 +514,7 @@ impl Session {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
}
|
||||
@@ -466,7 +526,7 @@ impl Session {
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id()));
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
}
|
||||
@@ -483,13 +543,34 @@ impl Session {
|
||||
};
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
|
||||
/// process holds one; without a store, a turn that writes nothing. An error, with a log record,
|
||||
/// when the lock file can't be made, opened or locked. Taken after
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] when both are needed, and never by a thread that
|
||||
/// holds a turn already.
|
||||
pub(crate) fn plugin_store_turn(&self) -> std::io::Result<StoreTurn> {
|
||||
let Some(dir) = self.plugin_dir.as_deref() else { return Ok(StoreTurn::unheld()) };
|
||||
lock_store(dir)
|
||||
.map(|file| StoreTurn { lock: Some(file) })
|
||||
.inspect_err(|e| log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display()))
|
||||
}
|
||||
|
||||
/// [`Session::plugin_store_turn`] for a load, which goes ahead without the turn when the store
|
||||
/// folder isn't there (nothing is stored) or can't be locked, and then writes nothing to it.
|
||||
pub(crate) fn plugin_store_turn_for_load(&self) -> StoreTurn {
|
||||
match self.plugin_dir.as_deref() {
|
||||
Some(dir) if dir.is_dir() => self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()),
|
||||
_ => StoreTurn::unheld(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they
|
||||
/// went there, every change included (`false` without a folder, and when a plug-in turned off
|
||||
/// found the file's list full: [`safe_mode::Merged::complete`]). The changes this launch made are applied to the list
|
||||
@@ -499,8 +580,15 @@ impl Session {
|
||||
/// a file that can't be read (too large, say) or that a later version wrote
|
||||
/// ([`safe_mode::read_disabled_file`]): it is kept as it is.
|
||||
pub fn store_disabled_plugins(&self) -> bool {
|
||||
self.plugin_store_turn().is_ok_and(|turn| self.store_disabled_plugins_in(&turn))
|
||||
}
|
||||
|
||||
/// [`Session::store_disabled_plugins`] in `turn`; `false` when it isn't held.
|
||||
pub(crate) fn store_disabled_plugins_in(&self, turn: &StoreTurn) -> bool {
|
||||
let Some(dir) = self.plugin_dir.as_deref() else { return false };
|
||||
let Some(_turn) = lock_disabled(dir) else { return false };
|
||||
if !turn.held() {
|
||||
return false;
|
||||
}
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
let theirs = match read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES) {
|
||||
Ok(bytes) => match safe_mode::read_disabled_file(&bytes) {
|
||||
@@ -580,10 +668,10 @@ impl Session {
|
||||
grants
|
||||
}
|
||||
|
||||
/// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false`
|
||||
/// without a folder).
|
||||
pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes))
|
||||
/// Write the module `bytes` of the plug-in `id` to the store in `turn` → whether they went there
|
||||
/// (`false` without a folder, and when `turn` isn't held).
|
||||
pub(crate) fn store_plugin(&self, turn: &StoreTurn, id: &str, bytes: &[u8]) -> bool {
|
||||
turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| put(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)), bytes))
|
||||
}
|
||||
|
||||
/// The module the store holds for the plug-in `id`: `None` without a folder or such a file, and
|
||||
@@ -601,14 +689,15 @@ impl Session {
|
||||
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the
|
||||
/// write reported success; a write that reports a failure may still have put `previous` back.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
/// In `turn`, the one the write was made in.
|
||||
pub(crate) fn put_back_plugin(&self, turn: &StoreTurn, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS.get() {
|
||||
return false;
|
||||
}
|
||||
let back = match previous {
|
||||
Some(bytes) => self.store_plugin(id, bytes),
|
||||
None => self.unstore_plugin(id),
|
||||
Some(bytes) => self.store_plugin(turn, id, bytes),
|
||||
None => self.unstore_plugin(turn, id),
|
||||
};
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS_AFTER_WRITE.get() {
|
||||
@@ -623,15 +712,23 @@ impl Session {
|
||||
self.plugin_dir.as_ref().map(|dir| dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id))).display().to_string())
|
||||
}
|
||||
|
||||
/// Tests: [`Session::store_grant_in`] in a turn of its own ([`Session::plugin_store_turn`]);
|
||||
/// `false` when it can't be taken.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
self.plugin_store_turn().is_ok_and(|turn| self.store_grant_in(&turn, id, grant))
|
||||
}
|
||||
|
||||
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
|
||||
/// other grants as they are; with none left, remove the file. Entries this version can't use
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
|
||||
/// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = self.write_grant(id, grant);
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and
|
||||
/// written in `turn`. → whether the store now holds what was asked (`false` without a folder,
|
||||
/// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every
|
||||
/// session in the process attached to the store ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant_in(&self, turn: &StoreTurn, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = turn.held() && self.write_grant(id, grant);
|
||||
if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
|
||||
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = (key, id.to_string());
|
||||
@@ -648,7 +745,7 @@ impl Session {
|
||||
done
|
||||
}
|
||||
|
||||
/// How many grant writes the sessions of the process have made ([`Session::store_grant`]).
|
||||
/// How many grant writes the sessions of the process have made ([`Session::store_grant_in`]).
|
||||
/// Taken before a write that may fail, for [`Session::ignore_stored_grant`].
|
||||
pub(crate) fn grant_writes(&self) -> u64 {
|
||||
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes
|
||||
@@ -661,7 +758,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Stop counting the attached store's grant for the plug-in `id`, in every session in the
|
||||
/// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in
|
||||
/// process attached to the same folder, until [`Session::store_grant_in`] next succeeds for it in
|
||||
/// one of them: for a grant that should be gone and could not be removed, which would otherwise
|
||||
/// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed
|
||||
/// write: when a session has written the store's grants for `id` since, the file holds what that
|
||||
@@ -687,6 +784,10 @@ impl Session {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANTS_READ.take() {
|
||||
between();
|
||||
}
|
||||
let others = file.other.len();
|
||||
file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id));
|
||||
let changed = match grant {
|
||||
@@ -724,16 +825,17 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder).
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
/// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a
|
||||
/// folder, and when `turn` isn't held).
|
||||
pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool {
|
||||
turn.held() && self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
}
|
||||
|
||||
/// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without
|
||||
/// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal
|
||||
/// kept are moved back first ([`plugin_storage`]).
|
||||
pub(crate) fn attach_plugin_storage(&self, id: &str) {
|
||||
vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id));
|
||||
/// kept are moved back first, in `turn` ([`plugin_storage`]).
|
||||
pub(crate) fn attach_plugin_storage(&self, turn: &StoreTurn, id: &str) {
|
||||
vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id, turn));
|
||||
}
|
||||
|
||||
/// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one
|
||||
@@ -757,9 +859,13 @@ impl Session {
|
||||
/// that rename fails too, the error also names both paths and the reason, and the next attach or
|
||||
/// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the
|
||||
/// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log
|
||||
/// record, and a later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
/// record, and a later call for the id tries to delete it again. All of it happens in `turn`;
|
||||
/// with a store and a turn that isn't held, nothing changes and this fails.
|
||||
pub(crate) fn remove_plugin_storage(&self, turn: &StoreTurn, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string());
|
||||
if self.plugin_dir.is_some() && !turn.held() {
|
||||
return Err(StorageError::Io(STORE_NOT_LOCKED.to_string()));
|
||||
}
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
let Some(dir) = &self.plugin_dir else {
|
||||
return if forget() { Ok(()) } else { Err(not_forgotten()) };
|
||||
@@ -943,13 +1049,16 @@ fn restore_removed(path: &Path) -> std::io::Result<()> {
|
||||
/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. Settings and cache
|
||||
/// that a removal kept are moved back first ([`restore_removed`]); when that fails, the failure is
|
||||
/// logged and there is no storage (its calls fail as unavailable), so that nothing the plug-in
|
||||
/// writes takes their place. A later attach or load tries again.
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> {
|
||||
/// writes takes their place. A later attach or load tries again. They are moved in `turn`; when it
|
||||
/// isn't held, they stay where they are, as when moving them fails.
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str, turn: &StoreTurn) -> Option<Arc<dyn Storage>> {
|
||||
let dir = dir?;
|
||||
let data = plugin_data_dir(dir, id);
|
||||
if !is_link(&dir.join(PLUGIN_DATA_DIR)) {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Err(e) = restore_removed(&data) {
|
||||
let kept_aside = || std::fs::symlink_metadata(&data).is_err() && aside_paths(&data).iter().any(|a| is_kept(a));
|
||||
let restored = if turn.held() || !kept_aside() { restore_removed(&data) } else { Err(std::io::Error::other(STORE_NOT_LOCKED)) };
|
||||
if let Err(e) = restored {
|
||||
log::warn!("can't move the settings and cache of {} back: {e}", data.display());
|
||||
return None;
|
||||
}
|
||||
@@ -1088,6 +1197,12 @@ impl PluginStorage {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a
|
||||
/// window or process changing the same settings or cache waits for this change.
|
||||
fn turn(&self) -> Result<std::fs::File, StorageError> {
|
||||
lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}")))
|
||||
}
|
||||
|
||||
fn kept(&self) -> MutexGuard<'_, Kept> {
|
||||
self.state.kept.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
@@ -1212,6 +1327,8 @@ impl PluginStorage {
|
||||
|
||||
impl Storage for PluginStorage {
|
||||
fn setting(&self, key: &str, meter: &mut Meter) -> Result<Option<Vec<u8>>, StorageError> {
|
||||
// Reading may move a settings file that doesn't read aside.
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
@@ -1219,10 +1336,15 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn set_setting(&self, key: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
let settings = &mut self.read_settings(&mut kept.settings, meter)?.values;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_SETTINGS_READ.take() {
|
||||
between();
|
||||
}
|
||||
if value.len() > storage::MAX_SETTING_BYTES || (!settings.contains_key(key) && settings.len() >= storage::MAX_SETTINGS) {
|
||||
return Err(StorageError::Full);
|
||||
}
|
||||
@@ -1234,6 +1356,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn delete_setting(&self, key: &str, meter: &mut Meter) -> Result<bool, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let mut kept = self.kept();
|
||||
@@ -1258,6 +1381,8 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn set_cache_entry(&self, name: &str, value: &[u8], meter: &mut Meter) -> Result<(), StorageError> {
|
||||
// The cache's size and count are added up and the entry written in one turn.
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let path = self.entry_path(name);
|
||||
@@ -1281,6 +1406,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn remove_cache_entry(&self, name: &str) -> Result<bool, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let path = self.entry_path(name);
|
||||
@@ -1296,6 +1422,7 @@ impl Storage for PluginStorage {
|
||||
}
|
||||
|
||||
fn clear_cache(&self) -> Result<u64, StorageError> {
|
||||
let _turn = self.turn()?;
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.open()?;
|
||||
let dir = self.cache_dir();
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::path::measured_segments;
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -109,3 +109,29 @@ fn an_anchor_edit_that_changes_nothing_records_no_undo_step() {
|
||||
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 5, "x": a.p.x + 1.0, "y": a.p.y})).unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
/// `path.setHandle` to where the handle already is, on a smooth anchor whose other handle is not in
|
||||
/// line with it, leaves both handles as they are and records no undo step. With `independent` it
|
||||
/// makes the anchor a corner, which records one.
|
||||
#[test]
|
||||
fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() {
|
||||
let (mut s, id) = long_path(100);
|
||||
let p = anchor(&s, id, 5).p;
|
||||
let smooth = Anchor { p, h_in: p + Vec2::new(-3.0, 0.0), h_out: p + Vec2::new(0.0, 4.0), kind: AnchorKind::Smooth };
|
||||
let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap();
|
||||
path.subpaths[0].anchors[5] = smooth;
|
||||
for which in ["out", "in"] {
|
||||
let h = if which == "out" { smooth.h_out } else { smooth.h_in };
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": which, "x": h.x, "y": h.y})).unwrap();
|
||||
assert_eq!(undo_steps(&s), 0, "path.setHandle on the {which} handle recorded an undo step");
|
||||
assert_eq!(anchor(&s, id, 5), smooth, "path.setHandle on the {which} handle changed the anchor");
|
||||
}
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true}))
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
assert_eq!(anchor(&s, id, 5).kind, AnchorKind::Corner);
|
||||
// On a corner, the same independent request changes nothing.
|
||||
s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": smooth.h_out.x, "y": smooth.h_out.y, "independent": true}))
|
||||
.unwrap();
|
||||
assert_eq!(undo_steps(&s), 1);
|
||||
}
|
||||
|
||||
@@ -963,6 +963,69 @@ fn brush_freehand_paints_with_a_brush_in_one_step() {
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Charcoal"));
|
||||
}
|
||||
|
||||
/// `brush.freehand` refuses a `brush` that is not a string or names no brush in the document,
|
||||
/// and a `style` other than "pencil" or "brush", before it draws: the document, the selection
|
||||
/// and the undo history stay as they were. A `brush` left out or null draws the plain path.
|
||||
#[test]
|
||||
fn brush_freehand_refuses_a_brush_or_style_it_cannot_use() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
let points = json!([[10, 10], [60, 40], [120, 10]]);
|
||||
for (extra, words) in [
|
||||
(json!({"brush": "Nope"}), "no brush named `Nope`"),
|
||||
(json!({"brush": ""}), "no brush named ``"),
|
||||
(json!({"brush": 5}), "`brush` must be a string"),
|
||||
(json!({"brush": {"name": "Charcoal"}}), "`brush` must be a string"),
|
||||
(json!({"brush": true}), "`brush` must be a string"),
|
||||
(json!({"brush": "Charcoal", "style": "marker"}), "`style` must be \"pencil\" or \"brush\", not \"marker\""),
|
||||
(json!({"brush": "Charcoal", "style": 1}), "`style` must be \"pencil\" or \"brush\", not 1"),
|
||||
] {
|
||||
let mut p = extra.clone();
|
||||
p["points"] = points.clone();
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("brush.freehand", &p).expect_err(&format!("{extra} is refused"));
|
||||
assert!(e.to_string().contains(words), "{extra}: {e}");
|
||||
assert!(*s.doc().unwrap().doc == *before, "{extra} leaves the document");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a], "{extra} leaves the selection");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{extra} records no undo step");
|
||||
}
|
||||
for extra in [json!({}), json!({"brush": null, "style": null})] {
|
||||
let mut p = extra.clone();
|
||||
p["points"] = points.clone();
|
||||
let id = NodeId(s.execute("brush.freehand", &p).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(brush_of(&s, id), None, "{extra} draws the plain path");
|
||||
}
|
||||
for style in ["pencil", "brush"] {
|
||||
let r = s.execute("brush.freehand", &json!({"points": points, "style": style, "brush": "Charcoal"})).unwrap();
|
||||
assert!(r["id"].is_u64(), "{style}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Paintbrush skips a brush deleted after it was chosen: a deleted tool brush gives way to
|
||||
/// the document's current brush, and with neither the stroke is drawn without a brush.
|
||||
#[test]
|
||||
fn paintbrush_tool_skips_a_deleted_brush() {
|
||||
let mut s = session();
|
||||
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("paintbrush", v).unwrap();
|
||||
s.set_tool_option("brush", &json!("Dots"));
|
||||
s.execute("brush.delete", &json!({"name": "Dots"})).unwrap();
|
||||
let stroke = |s: &mut Session, y: f64| {
|
||||
for (k, x) in [(PointerKind::Down, 10.0), (PointerKind::Drag, 50.0), (PointerKind::Drag, 90.0), (PointerKind::Up, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(k, x, y), v).unwrap();
|
||||
}
|
||||
s.doc().unwrap().selection.objects[0]
|
||||
};
|
||||
let id = stroke(&mut s, 10.0);
|
||||
assert_eq!(brush_of(&s, id).as_deref(), Some("Arrow"));
|
||||
s.execute("brush.delete", &json!({"name": "Arrow"})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.unknown.get("currentBrush"), None);
|
||||
let id = stroke(&mut s, 110.0);
|
||||
assert_eq!(brush_of(&s, id), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paintbrush_tool_uses_the_current_brush() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -4415,6 +4415,41 @@ fn a_trace_run_hands_its_trace_to_the_command() {
|
||||
assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}");
|
||||
}
|
||||
|
||||
/// A trace made in one document applies only there: in another document with the same image,
|
||||
/// object and settings, the run no longer applies, and both trace commands drop the trace handed
|
||||
/// in and trace that document's own image, as one undo step.
|
||||
#[test]
|
||||
fn a_trace_run_applies_only_in_its_own_document() {
|
||||
let p = json!({"params": {"ignoreWhite": true}});
|
||||
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
|
||||
let mut direct = session();
|
||||
image_doc(&mut direct);
|
||||
let want = direct.execute(command, &p).unwrap();
|
||||
let mut s = session();
|
||||
let img = image_doc(&mut s);
|
||||
let a = s.active_index().unwrap();
|
||||
let copy = (*s.doc().unwrap().doc).clone();
|
||||
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
|
||||
let traced = run.run(&|_, _| true).unwrap();
|
||||
let b = s.add_document(copy, None);
|
||||
assert_ne!(s.documents()[a].uid, s.documents()[b].uid);
|
||||
assert!(!run.current(&s), "{command}: another document");
|
||||
assert!(s.set_active(a));
|
||||
assert!(run.current(&s), "{command}: its own document");
|
||||
assert!(s.set_active(b));
|
||||
traced.hand_in(&mut s);
|
||||
let got = s.execute(run.command(), run.params()).unwrap();
|
||||
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
|
||||
assert_eq!(got, want, "{command}");
|
||||
let g = NodeId(got["id"].as_u64().unwrap());
|
||||
assert_eq!(node(&s, g), node(&direct, g), "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
|
||||
assert!(s.set_active(a));
|
||||
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: the first document is untouched");
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
|
||||
/// place, as it leaves the document.
|
||||
#[test]
|
||||
|
||||
@@ -184,6 +184,26 @@ fn rgb_cmyk_converts_each_gradient_stop() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each point of a freeform gradient converts on its own, as gradient stops do.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_each_freeform_point() {
|
||||
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0, 10.0, 50.0, 50.0, json!("#000000"));
|
||||
let stops = json!([{"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)}, {"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)}]);
|
||||
let points = json!([{"at": [20, 20], "color": Color::rgb(0.2, 0.876_543, 0.3)}, {"at": [50, 50], "color": Color::rgb(0.6, 0.111_111, 0.9)}]);
|
||||
let gradient = json!({"kind": "freeform", "stops": stops, "freeform": {"points": points}});
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": gradient})).unwrap();
|
||||
let points = |s: &Session| match fill_of(s, id) {
|
||||
Paint::Gradient(g) => g.freeform.map(|f| f.points.iter().map(|p| p.color).collect::<Vec<_>>()).unwrap_or_default(),
|
||||
p => panic!("not a gradient: {p:?}"),
|
||||
};
|
||||
let old = points(&s);
|
||||
assert!(!old.is_empty(), "the freeform fill has points");
|
||||
s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
assert_eq!(points(&s), old.into_iter().map(to_cmyk).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// A pattern's tile art converts, and the art filled with the pattern keeps it.
|
||||
#[test]
|
||||
fn rgb_cmyk_converts_a_pattern_tile() {
|
||||
|
||||
@@ -1651,6 +1651,97 @@ fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() {
|
||||
assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt");
|
||||
}
|
||||
|
||||
/// Checks that the closed path `p` starts at its point nearest `old`, within `reach` of it: its first
|
||||
/// anchor is no farther from `old` than any other point along the path, and its outline starts there.
|
||||
fn assert_starts_nearest(p: &PathData, old: Point, reach: f64) {
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed, "the path stays closed");
|
||||
let first = sp.anchors[0].p;
|
||||
let nearest = smooth_test_samples(p).iter().map(|q| q.distance(old)).fold(f64::INFINITY, f64::min);
|
||||
let d = first.distance(old);
|
||||
assert!(d <= nearest + 1e-6 && d <= reach, "the path starts {d} pt from its old start, its nearest point is {nearest} pt away: {sp:?}");
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
assert_eq!(bp.elements().first(), Some(&kurbo::PathEl::MoveTo(first)));
|
||||
}
|
||||
|
||||
/// A drag over a closed path's first anchor and the anchors either side of it smooths the bump there,
|
||||
/// and the path starts at the point of the smoothed path nearest the old first anchor. The anchors out
|
||||
/// of reach keep their places, and undo brings the path back.
|
||||
#[test]
|
||||
fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 100.0);
|
||||
let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians());
|
||||
let anchors: Vec<_> = (0..12)
|
||||
.map(|i| {
|
||||
let q = at(30.0 * f64::from(i), if i == 0 { r + 8.0 } else { r });
|
||||
json!({"x": q.x, "y": q.y})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
let old = before.subpaths[0].anchors[0].p;
|
||||
// Along the circle from -40° to 40°, over anchors 11, 0 and 1.
|
||||
let drag: Vec<Point> = (-20..=20).map(|k| at(2.0 * f64::from(k), r)).collect();
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the bump is smoothed");
|
||||
assert_starts_nearest(&after, old, 12.0);
|
||||
let kept = &after.subpaths[0].anchors;
|
||||
for a in &before.subpaths[0].anchors[2..=10] {
|
||||
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(path(&s, id), before);
|
||||
}
|
||||
|
||||
/// A drag over the whole of a closed path with a spike that turns back on itself, which the refit
|
||||
/// keeps as a corner, leaves the path starting at its point nearest the old first anchor.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_with_a_spike_keeps_its_start() {
|
||||
let mut s = session();
|
||||
let mut seed = 5u64;
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let at = |a: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(a);
|
||||
use std::f64::consts::{PI, TAU};
|
||||
let mut pts: Vec<Point> = (0..64).map(|i| at(f64::from(i) / 64.0 * TAU, r + 2.5 * smooth_noise(&mut seed))).collect();
|
||||
// Out from the anchor at 180° to a tip 40 pt beyond the circle and back.
|
||||
pts.splice(33..33, [at(PI, r + 40.0), at(PI + 0.002, r)]);
|
||||
let anchors: Vec<_> = pts.iter().map(|q| json!({"x": q.x, "y": q.y})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
let mut drag: Vec<Point> = (0..=128).map(|i| at(f64::from(i) / 128.0 * TAU, r)).collect();
|
||||
drag.splice(65..65, (0..=16).chain((0..=16).rev()).map(|k| at(PI, r + 2.5 * f64::from(k))));
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the path is smoothed");
|
||||
assert_starts_nearest(&after, pts[0], 12.0);
|
||||
}
|
||||
|
||||
/// A drag that reaches a closed path but not its first anchor leaves that anchor first, where it was.
|
||||
#[test]
|
||||
fn smoothing_a_closed_path_away_from_its_first_anchor_keeps_it_first() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 100.0);
|
||||
let at = |deg: f64, rr: f64| c + rr * kurbo::Vec2::from_angle(deg.to_radians());
|
||||
let anchors: Vec<_> = (0..12)
|
||||
.map(|i| {
|
||||
let q = at(30.0 * f64::from(i), if i == 6 { r + 8.0 } else { r });
|
||||
json!({"x": q.x, "y": q.y})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let before = path(&s, id);
|
||||
// Along the circle from 140° to 220°, over anchors 5, 6 and 7.
|
||||
let drag: Vec<Point> = (70..=110).map(|k| at(2.0 * f64::from(k), r)).collect();
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "the bump is smoothed");
|
||||
assert!(after.subpaths[0].closed);
|
||||
assert_eq!(after.subpaths[0].anchors[0], before.subpaths[0].anchors[0]);
|
||||
}
|
||||
|
||||
/// A straight line along y = 200 from x = 100 to 400, one anchor every 5 pt, whose second and
|
||||
/// second-to-last anchors are 1.5 pt off the line: its first and last segments leave and arrive at
|
||||
/// 16.7° to it.
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
//! Inline graphics in text: `text.insertInline`, editing over them, undo, following their symbol.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use crate::*;
|
||||
@@ -325,6 +329,143 @@ fn a_symbol_that_shows_itself_inline_is_an_empty_slot() {
|
||||
assert_eq!(d.inline_art_bounds("Loop"), None);
|
||||
}
|
||||
|
||||
/// A rectangle `r` filled black, without a stroke.
|
||||
fn filled_rect(d: &mut vectorcraft_doc::Document, r: Rect) -> Arc<Node> {
|
||||
let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look))
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` placed by `xf`.
|
||||
fn symbol_instance(d: &mut vectorcraft_doc::Document, name: &str, xf: Affine) -> Arc<Node> {
|
||||
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: name.into(), xf }))
|
||||
}
|
||||
|
||||
/// Gives symbol `name` the art `art` in a group, adding the symbol when there is none of that name.
|
||||
fn set_symbol_art(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<Arc<Node>>) {
|
||||
let art = Arc::new(Node::group(d.alloc_id(), art));
|
||||
match d.symbols.iter_mut().find(|x| x.name == name) {
|
||||
Some(x) => x.art = art,
|
||||
None => d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art }),
|
||||
}
|
||||
}
|
||||
|
||||
/// An inline graphic of a symbol whose art holds an instance of another symbol is sized by that
|
||||
/// symbol's art, and follows it when it changes, through undo, redo and a saved copy.
|
||||
#[test]
|
||||
fn an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol() {
|
||||
let mut s = session();
|
||||
s.edit("Symbols", |d, _| {
|
||||
let far = filled_rect(d, Rect::new(100.0, 0.0, 160.0, 20.0));
|
||||
set_symbol_art(d, "Far", vec![far]);
|
||||
let inner = symbol_instance(d, "Far", Affine::IDENTITY);
|
||||
set_symbol_art(d, "Holder", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let id = text(&mut s, "ab");
|
||||
let w0 = obj(&s, id).bounds().unwrap().width();
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Holder", "scale": 1})).unwrap();
|
||||
let wide = Some(Rect::new(100.0, 0.0, 160.0, 20.0));
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(inline_bounds(&t), wide);
|
||||
// 20 pt tall at 20 pt type and 3 times as wide: the text grows by 60 pt.
|
||||
let w1 = t.bounds().unwrap().width();
|
||||
assert!((w1 - w0 - 60.0).abs() < 1.5, "{w0} → {w1}");
|
||||
// Far redefined as a 10 × 40 rectangle: the graphic is 20 pt tall and 5 pt wide.
|
||||
s.edit("Redefine Far", |d, _| {
|
||||
let tall = filled_rect(d, Rect::new(0.0, 0.0, 10.0, 40.0));
|
||||
set_symbol_art(d, "Far", vec![tall]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let tall = Some(Rect::new(0.0, 0.0, 10.0, 40.0));
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(inline_bounds(&t), tall);
|
||||
assert_eq!(s.doc().unwrap().doc.symbol_art_bounds("Holder"), tall);
|
||||
let w2 = t.bounds().unwrap().width();
|
||||
assert!((w2 - w0 - 5.0).abs() < 1.5, "{w0} → {w2}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(inline_bounds(&obj(&s, id)), wide);
|
||||
assert!((obj(&s, id).bounds().unwrap().width() - w1).abs() < 1e-6);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(inline_bounds(&obj(&s, id)), tall);
|
||||
// Opening a saved copy measures it the same way.
|
||||
let doc = (*s.doc().unwrap().doc).clone();
|
||||
let mut back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
back.title = "copy".into();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(back, None);
|
||||
assert_eq!(inline_bounds(&obj(&s2, id)), tall);
|
||||
assert!((obj(&s2, id).bounds().unwrap().width() - w2).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Symbol C shows Holder inline, Holder holds an instance of B, and B shows A inline: with the
|
||||
/// symbols listed C, Holder, B, A, a change to A reaches C through B's and Holder's new sizes.
|
||||
#[test]
|
||||
fn symbols_are_resolved_after_the_symbols_their_instances_show() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "A", 10.0);
|
||||
let t = text(&mut s, "z");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "A"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("Holder", |d, _| {
|
||||
let inner = symbol_instance(d, "B", Affine::IDENTITY);
|
||||
set_symbol_art(d, "Holder", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let t = text(&mut s, "z");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 0, "symbol": "Holder"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "C", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("Reverse the symbols", |d, _| {
|
||||
d.symbols.reverse();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let h0 = s.doc().unwrap().doc.symbol_art_bounds("Holder");
|
||||
redefine_as_wide_ellipse(&mut s, "A");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.symbol_art_bounds("Holder"), h0);
|
||||
assert_eq!(inline_bounds(&art_text(&s, "C")), d.symbol_art_bounds("Holder"));
|
||||
}
|
||||
|
||||
/// Symbol A holds an instance of B, and B's type shows A inline: the size of each would depend on
|
||||
/// itself, so both are empty slots, and stay so through later edits.
|
||||
#[test]
|
||||
fn a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "A", 10.0);
|
||||
let t = text(&mut s, "ab");
|
||||
s.execute("text.insertInline", &json!({"id": t.0, "at": 1, "symbol": "A"})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "B", "ids": [t.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.edit("A holds B", |d, _| {
|
||||
let inner = symbol_instance(d, "B", Affine::IDENTITY);
|
||||
set_symbol_art(d, "A", vec![inner]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let line = text(&mut s, "x");
|
||||
s.execute("text.insertInline", &json!({"id": line.0, "at": 0, "symbol": "A"})).unwrap();
|
||||
for _ in 0..2 {
|
||||
for name in ["A", "B"] {
|
||||
assert_eq!(s.doc().unwrap().doc.inline_art_bounds(name), None, "{name}");
|
||||
}
|
||||
assert_eq!(inline_bounds(&art_text(&s, "B")), None);
|
||||
assert_eq!(inline_bounds(&obj(&s, line)), None);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
}
|
||||
let _ = s.execute("document.serialize", &json!({"format": "png"})).unwrap();
|
||||
// Redefined without the instance, A is on no cycle.
|
||||
redefine_as_wide_ellipse(&mut s, "A");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(d.inline_art_bounds("A").is_some());
|
||||
assert_eq!(inline_bounds(&art_text(&s, "B")), d.symbol_art_bounds("A"));
|
||||
assert_eq!(inline_bounds(&obj(&s, line)), d.symbol_art_bounds("A"));
|
||||
}
|
||||
|
||||
/// A list paragraph that starts with an inline graphic draws its bullet before the graphic, and
|
||||
/// live SVG text writes the bullet.
|
||||
#[test]
|
||||
|
||||
@@ -733,6 +733,38 @@ fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() {
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true)));
|
||||
}
|
||||
|
||||
/// A gradient stop linked to a spot swatch with process plates, as a library file can hold one.
|
||||
fn plated_stops() -> Value {
|
||||
let ink = vectorcraft_color::Color::cmyk(0.0, 0.5, 0.0, 0.0);
|
||||
json!([
|
||||
{"offset": 0, "color": vectorcraft_color::Color::WHITE},
|
||||
{"offset": 1, "color": ink, "swatch": "Brand", "tint": 0.5, "plates": [0.3, 0, 0, 0]}
|
||||
])
|
||||
}
|
||||
|
||||
/// Library gradients and the gradient stops of library character styles lose their links to
|
||||
/// swatches the document does not have together with the process plates those links print with.
|
||||
#[test]
|
||||
fn library_stops_unlinked_from_their_swatch_keep_no_process_plates() {
|
||||
let data = json!({
|
||||
"name": "Plated",
|
||||
"gradients": [{"name": "Glow", "gradient": {"gradient": {"kind": "Linear", "stops": plated_stops()}, "angle": 0}}],
|
||||
"charStyles": [{"name": "Accent", "attrs": {"fill": {"type": "gradient", "gradient": {"kind": "Linear", "stops": plated_stops()}}}}]
|
||||
});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let a = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 20}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
run(&mut s, "library.use", json!({"library": lib, "kind": "fillGradient", "item": "Glow"}));
|
||||
let st = gradient(&paint_of(&s, &a, false)).gradient.stops[1].clone();
|
||||
assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}");
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
let style = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == "Accent").map(|c| c.attrs["fill"].clone()).unwrap();
|
||||
let fill = serde_json::from_value::<vectorcraft_color::Paint>(style).unwrap();
|
||||
let st = gradient(&fill).gradient.stops[1].clone();
|
||||
assert_eq!((st.swatch.as_deref(), st.tint, st.plates), (None, 1.0, None), "{st:?}");
|
||||
}
|
||||
|
||||
/// A library style is compared with the document's in the form the document stores it in, so a
|
||||
/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a
|
||||
/// click alike.
|
||||
|
||||
@@ -213,6 +213,24 @@ fn spot_stops_with_process_plates_export_both_in_device_n_shadings() {
|
||||
assert_eq!(gradient(&s, id).gradient.stops[1].plates, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
|
||||
let (mut s, id) = setup();
|
||||
let plated = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]}]});
|
||||
run(&mut s, "paint.editGradient", plated.clone());
|
||||
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
|
||||
let linked = gradient(&s, id).gradient.stops[1].clone();
|
||||
assert_eq!((linked.swatch.as_deref(), linked.plates), (Some("Ink"), Some([0.3, 0.0, 0.0, 0.0])));
|
||||
run(&mut s, "swatch.delete", json!({"name": "Ink"}));
|
||||
// The art's stop and the gradient swatch's stop keep the color they show, unlinked and without plates.
|
||||
let Paint::Gradient(sw) = doc(&s).swatch("Glow").unwrap().paint.clone() else { panic!("a gradient swatch") };
|
||||
for st in [&gradient(&s, id).gradient.stops[1], &sw.gradient.stops[1]] {
|
||||
assert_eq!((st.color, st.swatch.as_deref(), st.tint, st.plates), (linked.color, None, 1.0, None), "{st:?}");
|
||||
}
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
|
||||
let (mut s, _) = setup();
|
||||
|
||||
@@ -768,6 +768,223 @@ fn nested_objects_that_repeat_ids_open_with_ids_of_their_own() {
|
||||
assert!(image(&s, layer_image).link.is_some(), "the image in the layers stays linked");
|
||||
}
|
||||
|
||||
/// The files of the linked images that the stored brushes of [`brush_links`] are made of: a scatter
|
||||
/// brush's, an art brush's and a pattern brush's side tile.
|
||||
const BRUSHED: [(&str, &str, &str); 3] = [("scatter.png", "scatter", "Specks"), ("art.png", "art", "Band"), ("side.png", "pattern", "Frame")];
|
||||
|
||||
/// A document whose stored brushes are made of [`BRUSHED`]'s linked images in `dir`. The art
|
||||
/// brush's image is still in the layers too, so its brush art repeats that object's id; the other
|
||||
/// two images were cleared from the layers.
|
||||
fn brush_links(dir: &Folder) -> (Session, NodeId) {
|
||||
for (i, (name, ..)) in (0u8..).zip(BRUSHED) {
|
||||
write(&dir.file(name), &png(20, 10, [30 + 60 * i, 120, 90]));
|
||||
}
|
||||
let mut s = session();
|
||||
let mut kept = NodeId(0);
|
||||
for (name, kind, brush) in BRUSHED {
|
||||
let id = place(&mut s, &dir.file(name));
|
||||
s.execute("brush.new", &json!({"type": kind, "name": brush, "ids": [id.0]})).unwrap();
|
||||
if kind == "art" {
|
||||
kept = id;
|
||||
} else {
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
}
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
(s, kept)
|
||||
}
|
||||
|
||||
/// The image in the art of stored brush `name`, as the document stores it.
|
||||
fn brush_image(s: &Session, name: &str) -> ImageObject {
|
||||
let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap_or_else(|| panic!("no brush {name}"));
|
||||
let mut found = None;
|
||||
b.art()[0].walk(&mut |n| {
|
||||
if let (None, NodeKind::Image(im)) = (&found, &n.kind) {
|
||||
found = Some((**im).clone());
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("no image in brush {name}"))
|
||||
}
|
||||
|
||||
/// The id of the image in the art of stored brush `name`, as the document stores it.
|
||||
fn brush_image_id(s: &Session, name: &str) -> u64 {
|
||||
let b = vectorcraft_brush::find(&s.doc().unwrap().doc, name).unwrap();
|
||||
let mut found = None;
|
||||
b.art()[0].walk(&mut |n| {
|
||||
if found.is_none() && matches!(n.kind, NodeKind::Image(_)) {
|
||||
found = Some(n.id.0);
|
||||
}
|
||||
});
|
||||
found.unwrap()
|
||||
}
|
||||
|
||||
/// Images in the art of stored brushes are listed after the others, one row per image in each brush tile,
|
||||
/// each with an id no other object has (the layer tree keeps its own), the brush named as what holds it; Check
|
||||
/// Links and the missing filter count them, and the ids stay the same from one list to the next.
|
||||
#[test]
|
||||
fn links_in_stored_brush_art_are_listed_and_checked_with_ids() {
|
||||
let dir = Folder::new("brush-ids");
|
||||
let (mut s, kept) = brush_links(&dir);
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let rows = list["links"].as_array().unwrap();
|
||||
let owners: Vec<(&str, &Value)> = rows.iter().map(|r| (r["name"].as_str().unwrap(), &r["owner"])).collect();
|
||||
let library = vectorcraft_brush::library(&s.doc().unwrap().doc);
|
||||
let index = |name: &str| library.iter().position(|b| b.name == name).unwrap();
|
||||
assert_eq!(
|
||||
owners,
|
||||
[
|
||||
("art.png", &Value::Null),
|
||||
("scatter.png", &json!({"kind": "brush", "name": "Specks", "index": index("Specks")})),
|
||||
("art.png", &json!({"kind": "brush", "name": "Band", "index": index("Band")})),
|
||||
("side.png", &json!({"kind": "brush", "name": "Frame", "index": index("Frame"), "tile": "side"})),
|
||||
],
|
||||
"{list}"
|
||||
);
|
||||
assert_eq!(rows[0]["id"], json!(kept.0), "the layer tree keeps its ids: {list}");
|
||||
let ids: std::collections::BTreeSet<u64> = rows.iter().map(|r| r["id"].as_u64().unwrap()).collect();
|
||||
assert_eq!(ids.len(), 4, "{list}");
|
||||
assert!(!ids.contains(&0), "{list}");
|
||||
assert!(rows.iter().all(|r| r["status"] == "ok" && r["linked"] == true), "{list}");
|
||||
assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids each time");
|
||||
let other = super::rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
s.execute("edit.clear", &json!({"ids": [other.0]})).unwrap();
|
||||
assert_eq!(s.execute("links.list", &json!({})).unwrap(), list, "the same ids after other objects are made");
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!(check["links"].as_array().unwrap().len(), 3, "{check}");
|
||||
std::fs::remove_file(dir.file("side.png")).unwrap();
|
||||
let check = s.execute("links.check", &json!({})).unwrap();
|
||||
assert_eq!(check["missing"].as_u64(), Some(1), "{check}");
|
||||
let missing = s.execute("links.list", &json!({"show": "missing"})).unwrap();
|
||||
assert_eq!(missing["links"][0]["id"], rows[3]["id"], "{missing}");
|
||||
}
|
||||
|
||||
/// Every links command takes the id of an image in a stored brush's art and acts on that brush's art,
|
||||
/// never on the image in the layers whose id the art repeated: Link Info, Go To (which clears the
|
||||
/// selection and names the brush), Placement Options, Relink, Update and Embed. The ids each change
|
||||
/// gives the art are kept in the library, so the next list names the same rows.
|
||||
#[test]
|
||||
fn links_commands_act_on_images_in_stored_brush_art_by_id() {
|
||||
let dir = Folder::new("brush-act");
|
||||
let (mut s, kept) = brush_links(&dir);
|
||||
let band = row_id_owned(&mut s, "art.png", "brush");
|
||||
assert_ne!(band, kept.0);
|
||||
let info = s.execute("links.info", &json!({"id": band})).unwrap();
|
||||
assert_eq!((info["fileName"].as_str(), info["status"].as_str(), info["id"].as_u64()), (Some("art.png"), Some("ok"), Some(band)), "{info}");
|
||||
s.execute("select.set", &json!({"ids": [kept.0]})).unwrap();
|
||||
let go = s.execute("links.goTo", &json!({"id": band})).unwrap();
|
||||
assert_eq!(
|
||||
(go["onCanvas"].clone(), go["owner"]["kind"].clone(), go["owner"]["name"].clone()),
|
||||
(json!(false), json!("brush"), json!("Band")),
|
||||
"{go}"
|
||||
);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "nothing on the canvas is selected");
|
||||
s.execute("links.placementOptions", &json!({"ids": [band], "preserve": "fit"})).unwrap();
|
||||
assert_eq!(s.execute("links.placementOptions", &json!({"ids": [band]})).unwrap()["placement"]["preserve"], "fit");
|
||||
assert_eq!(brush_image(&s, "Band").placement.preserve, vectorcraft_doc::links::Preserve::Fit);
|
||||
assert_eq!(brush_image_id(&s, "Band"), band, "the brush keeps the id it is listed by");
|
||||
assert_ne!(image(&s, kept).placement.preserve, vectorcraft_doc::links::Preserve::Fit, "the image in the layers is left as it was");
|
||||
// Relink: the brush's image shows the new file; the image in the layers keeps its file.
|
||||
let other = dir.file("other.png");
|
||||
write(&other, &png(40, 20, BLUE));
|
||||
let r = s.execute("links.relink", &json!({"ids": [band], "path": other})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([band]), "{r}");
|
||||
assert_eq!(brush_image(&s, "Band").link.unwrap().path, other);
|
||||
assert_eq!(image(&s, kept).link.unwrap().path, dir.file("art.png"));
|
||||
assert_eq!(row_id_owned(&mut s, "other.png", "brush"), band, "{}", s.execute("links.list", &json!({})).unwrap());
|
||||
// Update: a changed file is read again for the scatter brush's image.
|
||||
let dots = row_id_owned(&mut s, "scatter.png", "brush");
|
||||
let changed = png(30, 30, RED);
|
||||
write(&dir.file("scatter.png"), &changed);
|
||||
let r = s.execute("links.update", &json!({"ids": [dots]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([dots]), "{r}");
|
||||
assert_eq!(brush_image(&s, "Specks").link.unwrap().size, Some(changed.len() as u64));
|
||||
// Embed: the pattern brush's side tile keeps its pixels and no longer links.
|
||||
let frame = row_id_owned(&mut s, "side.png", "brush");
|
||||
let r = s.execute("links.embed", &json!({"ids": [frame]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([frame]), "{r}");
|
||||
assert!(brush_image(&s, "Frame").link.is_none());
|
||||
let embedded = s.execute("links.list", &json!({"show": "embedded"})).unwrap();
|
||||
assert_eq!(embedded["links"][0]["id"], json!(frame), "{embedded}");
|
||||
// Relink All Instances takes the image in the layers and the brush's image of the same file.
|
||||
let r = s.execute("links.relink", &json!({"ids": [kept.0], "path": dir.file("scatter.png"), "scope": "all"})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([kept.0]), "{r}");
|
||||
let r = s.execute("links.relink", &json!({"ids": [dots], "path": other, "scope": "all"})).unwrap();
|
||||
let mut relinked: Vec<u64> = r["relinked"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
|
||||
relinked.sort();
|
||||
let mut both = vec![kept.0, dots];
|
||||
both.sort();
|
||||
assert_eq!(relinked, both, "{r}");
|
||||
assert_eq!(image(&s, kept).link.unwrap().path, other);
|
||||
// One undo step puts the brushes back as they were.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(brush_image(&s, "Specks").link.unwrap().path, dir.file("scatter.png"));
|
||||
}
|
||||
|
||||
/// The id of the `links.list` row of file `name` whose owner is of `kind`.
|
||||
fn row_id_owned(s: &mut Session, name: &str, kind: &str) -> u64 {
|
||||
let list = s.execute("links.list", &json!({})).unwrap();
|
||||
let row = list["links"].as_array().unwrap().iter().find(|r| r["name"] == name && r["owner"]["kind"] == kind);
|
||||
row.unwrap_or_else(|| panic!("{name} in {kind}: {list}"))["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A document saved with links in its stored brushes opens with them reported by the ids the list
|
||||
/// gives them, and a library entry that does not read as a brush is kept as it was.
|
||||
#[test]
|
||||
fn links_in_stored_brush_art_open_by_id_and_unreadable_entries_stay() {
|
||||
let dir = Folder::new("brush-open");
|
||||
let (mut s, _) = brush_links(&dir);
|
||||
let odd = json!({"name": "Odd", "type": "unknown", "art": {"id": 3}});
|
||||
s.edit("Odd brush", |d, _| {
|
||||
if let Some(list) = d.unknown.get_mut(vectorcraft_brush::DOC_KEY).and_then(Value::as_array_mut) {
|
||||
list.push(odd.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &path);
|
||||
std::fs::remove_file(dir.file("scatter.png")).unwrap();
|
||||
let r = open(&mut s, &path);
|
||||
let dots = row_id_owned(&mut s, "scatter.png", "brush");
|
||||
assert_eq!(r["missingLinks"][0]["ids"], json!([dots]), "{r}");
|
||||
assert_eq!(brush_image_id(&s, "Specks"), dots, "the library keeps the ids opening gave");
|
||||
let band = row_id_owned(&mut s, "art.png", "brush");
|
||||
s.execute("links.embed", &json!({"ids": [band]})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let stored = doc.unknown[vectorcraft_brush::DOC_KEY].as_array().unwrap();
|
||||
assert_eq!(stored.last(), Some(&odd), "the unreadable entry is left as it was");
|
||||
assert!(doc.mounted_art.is_empty());
|
||||
}
|
||||
|
||||
/// The Color Mask of an image in a stored brush's art is made again for the new pixels when Update
|
||||
/// reads the image's changed file.
|
||||
#[test]
|
||||
fn updating_an_image_in_stored_brush_art_makes_its_color_mask_again() {
|
||||
let dir = Folder::new("brush-mask");
|
||||
let path = dir.file("logo.png");
|
||||
write(&path, &png(12, 10, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &path);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let hide_white = json!({"background": "colors", "colors": "#ffffff", "contiguous": false, "tolerance": 0, "softness": 0});
|
||||
s.execute("addon.image.colorMask", &hide_white).unwrap();
|
||||
s.execute("brush.new", &json!({"type": "scatter", "name": "Masked", "ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
write(&path, &png(14, 10, BLUE));
|
||||
let row = row_id_owned(&mut s, "logo.png", "brush");
|
||||
let r = s.execute("links.update", &json!({"ids": [row]})).unwrap();
|
||||
assert_eq!(r["updated"], json!([row]), "{r}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let brush = vectorcraft_brush::find(doc, "Masked").unwrap();
|
||||
let mut masks = vec![];
|
||||
brush.art()[0].walk(&mut |n| {
|
||||
if let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) {
|
||||
masks.push((m.made_for(im), doc.images.contains_key(&m.key)));
|
||||
}
|
||||
});
|
||||
assert_eq!(masks, [(true, true)], "the mask is made for the new pixels");
|
||||
}
|
||||
|
||||
/// An image that Placement Options clip, alone in a group the user made, goes into a new clip group
|
||||
/// inside that group when its file grows, in the layers and in a symbol's art; the user's group
|
||||
/// stays a plain group.
|
||||
|
||||
@@ -90,6 +90,38 @@ fn two_links_and_a_font_are_collected_and_relinked() {
|
||||
assert!(s.doc().unwrap().doc.images.values().all(|b| !b.is_proxy()), "the copies' pixels");
|
||||
}
|
||||
|
||||
/// A file linked only from a stored brush's art is copied, and the packaged document's brush
|
||||
/// links to the copy.
|
||||
#[test]
|
||||
fn a_file_linked_from_a_stored_brush_is_collected_and_relinked() {
|
||||
let dir = Folder::new("package-brush");
|
||||
let file = dir.file("art/leaf.png");
|
||||
write(&file, &png(40, 20, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &file);
|
||||
run(&mut s, "brush.new", json!({"type": "scatter", "name": "Leaves Here", "ids": [id.0]}));
|
||||
run(&mut s, "edit.clear", json!({"ids": [id.0]}));
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let out = dir.file("out");
|
||||
let r = run(&mut s, "file.package", json!({"folder": out, "copyFonts": false}));
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
|
||||
assert!(files.contains(&"Links/leaf.png"), "{r}");
|
||||
let root = std::path::Path::new(&out).join("poster Folder");
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
let r = open(&mut s, &root.join("poster.vectorcraft").to_string_lossy());
|
||||
assert_eq!(r["missingLinks"], json!([]), "{r}");
|
||||
let brush = vectorcraft_brush::find(&s.doc().unwrap().doc, "Leaves Here").unwrap();
|
||||
let mut paths = vec![];
|
||||
brush.art()[0].walk(&mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
|
||||
paths.push(im.link.as_ref().map(|l| (l.path.clone(), l.relative.clone())));
|
||||
}
|
||||
});
|
||||
let [Some((path, relative))] = paths.as_slice() else { panic!("{paths:?}") };
|
||||
assert!(std::path::Path::new(path).starts_with(root.join("Links")), "{path}");
|
||||
assert_eq!(relative.as_deref(), Some("Links/leaf.png"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_document_cant_be_packaged() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -150,6 +150,42 @@ fn built_in_views_apply_by_name_or_type() {
|
||||
assert!(s.execute("perspective.grid.preset", &json!({})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reapplying_the_current_grid_preset_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
// On a document with no grid defined, a preset defines and shows one: an undo step.
|
||||
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
|
||||
assert_eq!(undo_len(&s), 1);
|
||||
let g = grid(&s);
|
||||
// The same preset again, by type or by name, leaves the grid as it is: no undo step.
|
||||
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
|
||||
run(&mut s, "perspective.grid.preset", json!({"name": "[2P-Normal View]"}));
|
||||
assert_eq!((grid(&s), undo_len(&s)), (g.clone(), 1));
|
||||
// Another active plane, or a hidden grid, is set back without an undo step.
|
||||
run(&mut s, "perspective.plane.set", json!({"plane": "ground"}));
|
||||
run(&mut s, "perspective.grid.show", json!({"visible": false}));
|
||||
assert_ne!(grid(&s), g);
|
||||
run(&mut s, "perspective.grid.preset", json!({"kind": 2}));
|
||||
assert_eq!((grid(&s), undo_len(&s)), (g, 1));
|
||||
// Another preset changes the grid.
|
||||
run(&mut s, "perspective.grid.preset", json!({"kind": 3}));
|
||||
assert_eq!((grid(&s).kind, undo_len(&s)), (3, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_grid_with_unchanged_fields_records_no_undo_step() {
|
||||
let mut s = session();
|
||||
// On a document with no grid defined, `perspective.grid.set` stores the grid: an undo step,
|
||||
// and the grid no longer follows the first artboard.
|
||||
run(&mut s, "perspective.grid.set", json!({}));
|
||||
assert_eq!((run(&mut s, "perspective.grid.get", json!({}))["defined"].clone(), undo_len(&s)), (json!(true), 1));
|
||||
// The stored grid's own values leave it as it is: no undo step.
|
||||
let g = grid(&s);
|
||||
run(&mut s, "perspective.grid.set", json!({}));
|
||||
run(&mut s, "perspective.grid.set", json!({"cell": g.cell, "horizon": g.horizon}));
|
||||
assert_eq!((grid(&s), undo_len(&s)), (g, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_save_rename_delete_and_protect_the_built_in_ones() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1042,6 +1042,57 @@ fn saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns() {
|
||||
assert_eq!(hashes, [hash.clone(), hash], "the symbol's, then the pattern's");
|
||||
}
|
||||
|
||||
/// Saving a document reads it again for its placed copy in the art of a stored brush of another
|
||||
/// open document, the only place that document shows it.
|
||||
#[test]
|
||||
fn saving_a_document_refreshes_its_placed_copy_in_a_stored_brush() {
|
||||
let dir = Folder::new("placed-refresh-brush");
|
||||
let src = dir.file("logo.vectorcraft");
|
||||
source(&src, 100.0, 50.0, RED, 0);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &src);
|
||||
s.execute("brush.new", &json!({"type": "scatter", "name": "Logos", "ids": [id.0]})).unwrap();
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let parent = s.active_index().unwrap();
|
||||
s.execute("document.open", &json!({"path": src})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#1414e6"})).unwrap();
|
||||
s.execute("document.save", &json!({})).unwrap();
|
||||
let hash = Some(vectorcraft_doc::links::hash_bytes(&std::fs::read(&src).unwrap()));
|
||||
let doc = &s.documents()[parent];
|
||||
assert_eq!(doc.history.undo.last().unwrap().label, "Update Links");
|
||||
let brush = vectorcraft_brush::find(&doc.doc, "Logos").unwrap();
|
||||
let mut hashes = vec![];
|
||||
brush.art()[0].walk(&mut |n| {
|
||||
if let NodeKind::PlacedDocument(p) = &n.kind {
|
||||
hashes.push(p.link.hash.clone());
|
||||
}
|
||||
});
|
||||
assert_eq!(hashes, [hash]);
|
||||
}
|
||||
|
||||
/// A placed document kept only in a stored brush's art, whose file is gone and of which the
|
||||
/// document holds only the preview, is output as its preview with the warning that says so.
|
||||
#[test]
|
||||
fn a_placed_document_in_a_stored_brush_without_its_file_is_output_as_its_preview() {
|
||||
let dir = Folder::new("placed-brush-preview");
|
||||
let src = dir.file("logo.vectorcraft");
|
||||
// Content of its own: files read are cached by content, and this one is removed.
|
||||
source(&src, 100.0, 50.0, RED, 3);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &src);
|
||||
s.execute("brush.new", &json!({"type": "scatter", "name": "Logos", "ids": [id.0]})).unwrap();
|
||||
// The copy in the layers has the save keep only the preview.
|
||||
let doc_path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &doc_path);
|
||||
std::fs::remove_file(&src).unwrap();
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!(r["missingLinks"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap();
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
assert!(svg["warnings"].to_string().contains("1 placed document output as its preview"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_info_gives_the_artboards_size_not_pixels() {
|
||||
let dir = Folder::new("placed-info");
|
||||
|
||||
@@ -1921,6 +1921,12 @@ fn disabled_plugins_name_files_outside_the_read_root_by_their_names() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// The files and folders in the plug-in store `dir`, without the file windows lock while they
|
||||
/// change it.
|
||||
fn store_files(dir: &std::path::Path) -> usize {
|
||||
std::fs::read_dir(dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.file_name() != crate::store::DISABLED_LOCK)).count()
|
||||
}
|
||||
|
||||
/// #2541: a plug-in installed in a session with a plug-in store is installed again in the next
|
||||
/// session that attaches the store, and Remove Plug-in takes it out of the store.
|
||||
#[test]
|
||||
@@ -1931,14 +1937,14 @@ fn installed_plugins_are_kept_in_the_store() {
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
install_wat(&mut s, &src);
|
||||
assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 1, "one file in the store");
|
||||
assert_eq!(store_files(&folder.0), 1, "one file in the store");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store");
|
||||
run(&mut next, "plugin.remove", json!({"id": id}));
|
||||
assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 0, "removed from the store");
|
||||
assert_eq!(store_files(&folder.0), 0, "removed from the store");
|
||||
|
||||
// A file that isn't a plug-in is skipped; the store still attaches.
|
||||
std::fs::write(folder.0.join("broken.wasm"), b"\0asm?").unwrap();
|
||||
@@ -3274,6 +3280,198 @@ fn a_store_loaded_while_installing_loads_the_new_version() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant of `doc.read` to plug-in `id`, the module with the SHA-256 `hash`.
|
||||
fn doc_read_grant(id: &str, hash: &str) -> vectorcraft_plugins::permissions::Grant {
|
||||
serde_json::from_value(json!({"id": id, "hash": hash, "permissions": ["doc.read"]})).unwrap()
|
||||
}
|
||||
|
||||
/// A session that uses the plug-in store `dir` without loading it, as another process using the
|
||||
/// same folder does: it doesn't wait for the installs and removals of this process's sessions.
|
||||
fn other_process(dir: std::path::PathBuf) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.plugin_dir = Some(dir);
|
||||
s
|
||||
}
|
||||
|
||||
/// Waits on this thread for a turn on a plug-in store, telling `waiting` before it waits.
|
||||
fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) {
|
||||
crate::store::WHILE_STORE_LOCKED.set(Some(Box::new(move || {
|
||||
let _ = waiting.send("waiting");
|
||||
})));
|
||||
}
|
||||
|
||||
/// The ids `grants.json` in `dir` holds grants for, and the hash of each.
|
||||
fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap<String, String> {
|
||||
let entries: Vec<Value> = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap();
|
||||
entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect()
|
||||
}
|
||||
|
||||
/// An install into a `Plug-ins` folder that another process also installs the same id into keeps a
|
||||
/// module with its own grant: the other process's install waits for this one's turn on the folder,
|
||||
/// between this install's module and its grant, and then writes both of its own.
|
||||
#[test]
|
||||
fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-installs-take-turns");
|
||||
let id = "test.engine.permissions.installsturns";
|
||||
let ours = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let theirs = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, other) = std::sync::mpsc::channel();
|
||||
let (dir, module) = (folder.0.clone(), theirs.clone());
|
||||
crate::cmd::plugin::BEFORE_GRANT_STORED.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
tell_when_waiting(said.clone());
|
||||
let other = other_process(dir);
|
||||
let turn = other.plugin_store_turn().unwrap();
|
||||
let stored = crate::cmd::plugin::keep_installed(&other, &turn, id, &module, Some(doc_read_grant(id, &sha256_hex(&module))));
|
||||
let _ = said.send(if stored { "stored" } else { "not stored" });
|
||||
});
|
||||
// The other install has written the store, or waits for this one.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&ours), "grant": ["doc.read"]}));
|
||||
let (first, thread) = other.recv().unwrap();
|
||||
thread.join().unwrap();
|
||||
|
||||
let module = std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap();
|
||||
assert_eq!(stored_grant_hashes(&folder.0).get(id), Some(&sha256_hex(&module)), "the stored grant covers the stored module");
|
||||
assert_eq!(module, theirs, "the install that waited wrote last");
|
||||
assert_eq!(first, "waiting", "the other install waits for this one");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the
|
||||
/// second write reads `grants.json` only once the first has written it.
|
||||
#[test]
|
||||
fn grants_written_by_two_processes_into_one_store_keep_both() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-grants-take-turns");
|
||||
let (ours, theirs) = ("test.engine.permissions.grantturnsa", "test.engine.permissions.grantturnsb");
|
||||
let hash = vectorcraft_plugins::permissions::sha256_hex(b"module");
|
||||
let s = other_process(folder.0.clone());
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, other) = std::sync::mpsc::channel();
|
||||
let (dir, other_hash) = (folder.0.clone(), hash.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
tell_when_waiting(said.clone());
|
||||
let written = other_process(dir).store_grant(theirs, Some(doc_read_grant(theirs, &other_hash)));
|
||||
let _ = said.send(if written { "written" } else { "not written" });
|
||||
});
|
||||
// The other write has written the file, or waits for this one.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
assert!(s.store_grant(ours, Some(doc_read_grant(ours, &hash))), "the grant is written");
|
||||
let (first, thread) = other.recv().unwrap();
|
||||
thread.join().unwrap();
|
||||
|
||||
let kept = stored_grant_hashes(&folder.0);
|
||||
assert_eq!(kept.keys().map(String::as_str).collect::<Vec<_>>(), [ours, theirs], "both grants are kept");
|
||||
assert_eq!(first, "waiting", "the other write waits for this one");
|
||||
}
|
||||
|
||||
/// A setting a plug-in changes in one process and another setting it changes in a second process
|
||||
/// using the same `Plug-ins` folder are both kept: the second process waits for the first's turn on
|
||||
/// the folder and reads what it wrote. The second process is this test run again with
|
||||
/// `VECTORCRAFT_TEST_PLUGIN_SETTINGS_STORE` naming the folder; it prints when it waits and when it
|
||||
/// is done.
|
||||
#[test]
|
||||
fn settings_changed_by_two_processes_keep_both() {
|
||||
use std::io::{BufRead, Write};
|
||||
use vectorcraft_plugins::storage::Meter;
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_PLUGIN_SETTINGS_STORE";
|
||||
const NAME: &str = "tests::plugins::settings_changed_by_two_processes_keep_both";
|
||||
let id = "test.engine.storagetwoprocesses";
|
||||
// Nothing a removal kept is moved back, so the storage is made without a turn on the folder.
|
||||
let attached = |s: &Session| {
|
||||
s.attach_plugin_storage(&crate::store::StoreTurn::unheld(), id);
|
||||
vectorcraft_plugins::registry::storage(id).unwrap()
|
||||
};
|
||||
if let Some(dir) = std::env::var_os(CHILD) {
|
||||
let st = attached(&other_process(std::path::PathBuf::from(dir)));
|
||||
crate::store::WHILE_STORE_LOCKED.set(Some(Box::new(|| {
|
||||
println!("settings-child-waiting");
|
||||
let _ = std::io::stdout().flush();
|
||||
})));
|
||||
st.set_setting("theirs", b"2", &mut Meter::unlimited()).unwrap();
|
||||
println!("settings-child-done");
|
||||
let _ = std::io::stdout().flush();
|
||||
return;
|
||||
}
|
||||
let folder = crate::tests_links::Folder::new("plugin-settings-two-processes");
|
||||
let st = attached(&other_process(folder.0.clone()));
|
||||
|
||||
let (handed, child) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::store::AFTER_SETTINGS_READ.set(Some(Box::new(move || {
|
||||
let mut process = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", NAME, "--nocapture", "--test-threads=1"])
|
||||
.env(CHILD, &dir)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut lines = std::io::BufReader::new(process.stdout.take().unwrap()).lines();
|
||||
// The other process has written the settings, or waits for this change.
|
||||
let first = lines
|
||||
.by_ref()
|
||||
.map_while(std::io::Result::ok)
|
||||
.find_map(|l| ["waiting", "done"].into_iter().find(|said| l.contains(&format!("settings-child-{said}"))));
|
||||
let _ = handed.send((first, process, lines));
|
||||
})));
|
||||
st.set_setting("ours", b"1", &mut Meter::unlimited()).unwrap();
|
||||
let (first, mut process, lines) = child.recv().unwrap();
|
||||
let rest: Vec<String> = lines.map_while(std::io::Result::ok).collect();
|
||||
assert!(process.wait().unwrap().success(), "the other process failed: {rest:?}");
|
||||
|
||||
let file: std::collections::BTreeMap<String, String> =
|
||||
serde_json::from_slice(&std::fs::read(crate::store::plugin_data_dir(&folder.0, id).join("settings.json")).unwrap()).unwrap();
|
||||
assert_eq!(file.keys().map(String::as_str).collect::<Vec<_>>(), ["ours", "theirs"], "both settings are kept");
|
||||
assert_eq!(first, Some("waiting"), "the other process waits for this change");
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
}
|
||||
|
||||
/// When the `Plug-ins` folder can't be locked (here `disabled.lock` is a folder), `plugin.install`
|
||||
/// and `plugin.remove` change nothing and say why: the plug-in installed with the id, its grant and
|
||||
/// the stored module stay as they were.
|
||||
#[test]
|
||||
fn a_store_that_cant_be_locked_refuses_installs_and_removals() {
|
||||
use vectorcraft_plugins::{permissions::sha256_hex, registry};
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-not-locked");
|
||||
let id = "test.engine.permissions.notlocked";
|
||||
let first = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let second = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first), "grant": ["doc.read"]}));
|
||||
let lock = folder.0.join(crate::store::DISABLED_LOCK);
|
||||
std::fs::remove_file(&lock).unwrap();
|
||||
std::fs::create_dir(&lock).unwrap();
|
||||
let grants = std::fs::read(folder.0.join("grants.json")).unwrap();
|
||||
|
||||
let update = json!({"dataBase64": vectorcraft_format::base64_encode(&second), "grant": ["doc.read"], "replace": true});
|
||||
let refused = s.execute("plugin.install", &update).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::STORE_NOT_LOCKED) && refused.contains("nothing was installed"), "{refused}");
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&first)), "the installed plug-in stays");
|
||||
assert_eq!(registry::granted(id).map(|g| g.hash), Some(sha256_hex(&first)), "its grant stays");
|
||||
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), first, "the store keeps its module");
|
||||
assert_eq!(std::fs::read(folder.0.join("grants.json")).unwrap(), grants, "and its grant");
|
||||
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::STORE_NOT_LOCKED) && refused.contains("nothing was removed"), "{refused}");
|
||||
assert!(registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert!(std::path::Path::new(&s.stored_plugin_file(id).unwrap()).exists(), "and stored");
|
||||
|
||||
std::fs::remove_dir(&lock).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// Runs the test `name` of this module again in a process of its own → whether this is that
|
||||
/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here
|
||||
/// read it again each time they attach a plug-in store.
|
||||
@@ -3740,7 +3938,7 @@ fn granted_permissions_are_kept_and_folders_skip_the_rest() {
|
||||
let mut third = session();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nobody granted it");
|
||||
assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 1, "the module stays in the store");
|
||||
assert_eq!(store_files(&folder.0), 1, "the module stays in the store");
|
||||
|
||||
// The Additional Plug-ins Folder skips it with a note until it is granted.
|
||||
let dir = crate::tests_links::Folder::new("plugin-folder-grants");
|
||||
@@ -4678,7 +4876,7 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() {
|
||||
|
||||
// An id that differs only in case has storage of its own, which removing this one leaves.
|
||||
let upper_id = "test.engine.StorageCaps";
|
||||
s.attach_plugin_storage(upper_id);
|
||||
s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), upper_id);
|
||||
let upper = vectorcraft_plugins::registry::storage(upper_id).unwrap();
|
||||
assert_eq!(upper.setting("k0", m).unwrap(), None);
|
||||
upper.set_setting("k0", b"upper", m).unwrap();
|
||||
@@ -4690,13 +4888,13 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() {
|
||||
|
||||
// Removing the plug-in closes the storage a run still holds, even one from before the plug-in
|
||||
// was replaced, so nothing is written back.
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), id);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert_eq!(st.set_setting("zoom", b"again", m), Err(StorageError::Unavailable));
|
||||
assert_eq!(st.set_cache_entry("tile", b"again", m), Err(StorageError::Unavailable));
|
||||
assert!(!dir.exists());
|
||||
assert_eq!(upper.setting("k0", m).unwrap(), Some(b"upper".to_vec()));
|
||||
s.remove_plugin_storage(upper_id, || true).unwrap();
|
||||
s.remove_plugin_storage(&s.plugin_store_turn().unwrap(), upper_id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although
|
||||
@@ -4874,12 +5072,12 @@ fn removing_a_plugin_drops_its_settings_from_memory() {
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, &bytes).unwrap();
|
||||
set_modified(&file, written);
|
||||
s.attach_plugin_storage(id);
|
||||
s.attach_plugin_storage(&s.plugin_store_turn().unwrap(), id);
|
||||
let st = vectorcraft_plugins::registry::storage(id).unwrap();
|
||||
let mut m = Meter::unlimited();
|
||||
assert_eq!(st.setting("zoom", &mut m).unwrap(), Some(b"hello".to_vec()));
|
||||
assert_eq!(m.used(), bytes.len() as u64, "read from the file");
|
||||
s.remove_plugin_storage(id, || true).unwrap();
|
||||
s.remove_plugin_storage(&s.plugin_store_turn().unwrap(), id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// The cache's total stays in memory while the cache folder keeps its time; a write and a clear
|
||||
|
||||
@@ -1099,13 +1099,18 @@ fn fill_and_stroke(s: &Session, id: NodeId) -> (Paint, Paint) {
|
||||
/// in the batch, and one drawn after it, the same fill and stroke. Returns the batch's rectangle's
|
||||
/// fill and stroke.
|
||||
fn batch_matches_steps(steps: &[(&str, Value)]) -> (Paint, Paint) {
|
||||
batch_matches_steps_from(brand_defaults_session, steps)
|
||||
}
|
||||
|
||||
/// [`batch_matches_steps`] with both sessions made by `setup`.
|
||||
fn batch_matches_steps_from(setup: impl Fn() -> Session, steps: &[(&str, Value)]) -> (Paint, Paint) {
|
||||
let shape = ("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
let mut one_by_one = brand_defaults_session();
|
||||
let mut one_by_one = setup();
|
||||
for (id, p) in steps {
|
||||
run(&mut one_by_one, id, p.clone());
|
||||
}
|
||||
let single = rect(&mut one_by_one);
|
||||
let mut batched = brand_defaults_session();
|
||||
let mut batched = setup();
|
||||
let commands: Vec<Value> = steps.iter().chain([&shape]).map(|(id, p)| json!({"command": id, "params": p})).collect();
|
||||
let r = run(&mut batched, "command.batch", json!({ "commands": commands }));
|
||||
let in_batch = NodeId(r["results"][steps.len()]["id"].as_u64().unwrap());
|
||||
@@ -1133,6 +1138,43 @@ fn swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do() {
|
||||
assert_eq!(batch_matches_steps(&[("swatch.editGroup", json!({"group": "G", "colors": ["#ababab"]}))]), (gray.clone(), gray));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does() {
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let lab = Color::Lab { l: 55.0, a: 60.0, b: 40.0 };
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let cmyk = cms.convert(&lab, vectorcraft_color::cms::Model::Cmyk, cms.settings().intent);
|
||||
assert!(matches!(cmyk, Color::Cmyk { .. }));
|
||||
// The default fill and stroke for new art are linked to 40 % of the Lab spot swatch "Lab Ink".
|
||||
let lab_ink_defaults = |use_lab: bool| {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Lab Ink", "color": {"l": 55, "a": 60, "b": 40}, "spot": true}));
|
||||
run(&mut s, "swatch.spotOptions", json!({ "useLab": use_lab }));
|
||||
run(&mut s, "select.set", json!({"ids": []}));
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Lab Ink", "tint": 40}));
|
||||
run(&mut s, "paint.setStroke", json!({"swatch": "Lab Ink", "tint": 40}));
|
||||
s
|
||||
};
|
||||
let ink = |color: Color| Paint::Solid { color: color.tinted(0.4), swatch: Some("Lab Ink".into()), tint: 0.4 };
|
||||
assert_eq!(lab_ink_defaults(true).paint.fill, ink(lab));
|
||||
let to_cmyk = [("swatch.spotOptions", json!({"useLab": false}))];
|
||||
assert_eq!(batch_matches_steps_from(|| lab_ink_defaults(true), &to_cmyk), (ink(cmyk), ink(cmyk)));
|
||||
assert_eq!(lab_ink_defaults(false).paint.fill, ink(cmyk));
|
||||
let to_lab = [("swatch.spotOptions", json!({"useLab": true}))];
|
||||
assert_eq!(batch_matches_steps_from(|| lab_ink_defaults(false), &to_lab), (ink(lab), ink(lab)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does() {
|
||||
// Brand and Other are not default swatches, so replacing the swatches drops the links to them.
|
||||
let blue = Paint::solid(Color::from_hex("#2a6fb0").unwrap());
|
||||
let replace = [("swatch.resetDefaults", json!({"replace": true}))];
|
||||
assert_eq!(batch_matches_steps(&replace), (blue.clone(), blue));
|
||||
// Without replace the swatches stay, and so do the links.
|
||||
let link = linked("#2a6fb0", "Brand");
|
||||
assert_eq!(batch_matches_steps(&[("swatch.resetDefaults", json!({}))]), (link.clone(), link));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints() {
|
||||
let edit = json!({"name": "Brand", "newName": "Signal", "color": "#00ff00"});
|
||||
|
||||
@@ -636,6 +636,114 @@ fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradi
|
||||
assert_eq!(doc(&s).swatch("Red").unwrap().paint.color().map(|c| c.to_hex()), Some("#00ff00".into()));
|
||||
}
|
||||
|
||||
/// A radial gradient from red to blue, with `extra` keys.
|
||||
fn radial_gradient(extra: Value) -> Value {
|
||||
let mut g = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
if let (Some(g), Some(extra)) = (g.as_object_mut(), extra.as_object()) {
|
||||
g.extend(extra.clone());
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// The gradient swatch `name` keeps an aspect of 50%, holds no swatch link, and applies with that
|
||||
/// aspect, fitted to the object it is applied to.
|
||||
fn assert_swatch_applies_with_half_aspect(s: &mut Session, name: &str) {
|
||||
let Paint::Gradient(sw) = &doc(s).swatch(name).unwrap().paint else { panic!("{name}: a gradient swatch") };
|
||||
assert!(sw.geom.is_some_and(|g| (g.aspect - 0.5).abs() < 1e-9), "{name} keeps the aspect: {:?}", sw.geom);
|
||||
assert_eq!(sw.swatch, None, "{name} holds no link to the swatch its gradient came from");
|
||||
let r = run(s, "shape.rectangle", json!({"x": 100, "y": 0, "width": 100, "height": 60}));
|
||||
let id = r["id"].as_u64().unwrap();
|
||||
run(s, "paint.setFill", json!({"ids": [id], "swatch": name}));
|
||||
let fill = doc(s).node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint();
|
||||
let Paint::Gradient(g) = fill else { panic!("{name}: a gradient fill") };
|
||||
let geom = g.geom.unwrap();
|
||||
assert!(
|
||||
geom.start.distance(vectorcraft_geom::Point::new(150.0, 30.0)) < 1e-9 && (geom.aspect - 0.5).abs() < 1e-9,
|
||||
"{name} fits the object with its aspect: {geom:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// An edited gradient with a vector and an aspect that replaces a gradient swatch keeps its aspect,
|
||||
/// as a new swatch made from it does.
|
||||
#[test]
|
||||
fn a_gradient_swatch_takes_an_edited_gradient_with_its_aspect() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Edited", "gradient": radial_gradient(json!({}))}));
|
||||
let placed = radial_gradient(json!({"start": [25, 25], "end": [50, 25], "aspect": 50}));
|
||||
run(&mut s, "swatch.edit", json!({"name": "Edited", "paint": {"gradient": placed}}));
|
||||
assert_swatch_applies_with_half_aspect(&mut s, "Edited");
|
||||
}
|
||||
|
||||
/// A gradient swatch Alt-dropped on another gradient swatch gives it its gradient with its aspect.
|
||||
#[test]
|
||||
fn a_gradient_swatch_takes_a_dropped_swatch_with_its_aspect() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Dropped", "gradient": radial_gradient(json!({}))}));
|
||||
let placed = radial_gradient(json!({"start": [25, 25], "end": [50, 25], "aspect": 50}));
|
||||
run(&mut s, "swatch.new", json!({"name": "Oval", "gradient": placed}));
|
||||
run(&mut s, "swatch.edit", json!({"name": "Dropped", "paint": {"swatch": "Oval"}}));
|
||||
assert_swatch_applies_with_half_aspect(&mut s, "Dropped");
|
||||
}
|
||||
|
||||
/// A gradient given an aspect but no vector keeps the aspect in a new swatch and in a replacement,
|
||||
/// as `paint.setFill` keeps it on the object.
|
||||
#[test]
|
||||
fn a_gradient_without_a_vector_keeps_its_aspect_in_a_swatch() {
|
||||
let mut s = session();
|
||||
let oval = radial_gradient(json!({"aspect": 50}));
|
||||
run(&mut s, "swatch.new", json!({"name": "New", "gradient": oval}));
|
||||
assert_swatch_applies_with_half_aspect(&mut s, "New");
|
||||
run(&mut s, "swatch.new", json!({"name": "Edited", "gradient": radial_gradient(json!({}))}));
|
||||
run(&mut s, "swatch.edit", json!({"name": "Edited", "paint": {"gradient": oval}}));
|
||||
assert_swatch_applies_with_half_aspect(&mut s, "Edited");
|
||||
// Without an aspect the swatch stays unplaced.
|
||||
run(&mut s, "swatch.new", json!({"name": "Round", "gradient": radial_gradient(json!({}))}));
|
||||
let Paint::Gradient(round) = &doc(&s).swatch("Round").unwrap().paint else { panic!("a gradient swatch") };
|
||||
assert_eq!(round.geom, None);
|
||||
}
|
||||
|
||||
/// A pattern that replaces a pattern swatch is stored untransformed, as a new swatch stores it, so
|
||||
/// art the swatch is applied to keeps its own tile placement.
|
||||
#[test]
|
||||
fn a_pattern_swatch_takes_a_new_pattern_untransformed() {
|
||||
let mut s = session();
|
||||
for (name, color) in [("Dots", "#ff0000"), ("Bars", "#0000ff")] {
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [r["id"]], "color": color}));
|
||||
run(&mut s, "select.set", json!({"ids": [r["id"]]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": name, "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
}
|
||||
// A pattern swatch holding a tile transform, as documents saved by older versions can.
|
||||
let moved = vectorcraft_geom::Affine::new([2.0, 0.0, 0.0, 2.0, 15.0, 10.0]);
|
||||
let st = s.doc_mut().unwrap();
|
||||
let Some(Paint::Pattern { xf, .. }) = std::sync::Arc::make_mut(&mut st.doc).swatch_mut("Bars").map(|w| &mut w.paint) else {
|
||||
panic!("the Bars pattern swatch")
|
||||
};
|
||||
*xf = moved;
|
||||
run(&mut s, "swatch.edit", json!({"name": "Dots", "paint": {"swatch": "Bars"}}));
|
||||
assert_eq!(doc(&s).swatch("Dots").unwrap().paint, vectorcraft_doc::pattern::pattern_paint("Bars"));
|
||||
}
|
||||
|
||||
/// A pattern swatch takes a pattern given by name, as an Alt-drop of a pattern fill sends it, and
|
||||
/// an unknown pattern is an error that leaves the swatch as it was.
|
||||
#[test]
|
||||
fn a_pattern_swatch_takes_a_pattern_by_name() {
|
||||
let mut s = session();
|
||||
for (name, color) in [("Dots", "#ff0000"), ("Bars", "#0000ff")] {
|
||||
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [r["id"]], "color": color}));
|
||||
run(&mut s, "select.set", json!({"ids": [r["id"]]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": name, "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
}
|
||||
run(&mut s, "swatch.edit", json!({"name": "Dots", "paint": {"pattern": "Bars"}}));
|
||||
assert_eq!(doc(&s).swatch("Dots").unwrap().paint, vectorcraft_doc::pattern::pattern_paint("Bars"));
|
||||
let before = doc(&s).swatch("Dots").unwrap().paint.clone();
|
||||
assert!(s.execute("swatch.edit", &json!({"name": "Dots", "paint": {"pattern": "Nope"}})).is_err());
|
||||
assert_eq!(doc(&s).swatch("Dots").unwrap().paint, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organic_fades_add_with_their_method_midpoints_and_opacities_in_rgb_and_cmyk() {
|
||||
let lib = vectorcraft_color::libraries::builtin_library("organic-fades").unwrap();
|
||||
|
||||
@@ -241,6 +241,69 @@ fn options_are_saved_with_the_preferences() {
|
||||
assert_eq!(t.prefs.tool_settings["polygon"]["sides"], json!(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() {
|
||||
let mut s = session();
|
||||
for active in [false, true] {
|
||||
select(&mut s, if active { "spiral" } else { "selection" });
|
||||
let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap();
|
||||
assert_eq!(options["decay"], json!(99.99));
|
||||
assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99));
|
||||
assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99));
|
||||
assert_eq!(s.tool_id(), if active { "spiral" } else { "selection" });
|
||||
select(&mut s, "selection");
|
||||
select(&mut s, "spiral");
|
||||
assert_eq!(s.tool_options()["decay"], json!(99.99));
|
||||
}
|
||||
let saved = serde_json::to_string(&s.prefs).unwrap();
|
||||
let mut restored = session();
|
||||
restored.apply_prefs(serde_json::from_str(&saved).unwrap());
|
||||
select(&mut restored, "spiral");
|
||||
assert_eq!(restored.tool_options(), json!({"decay": 99.99, "segments": 4, "clockwise": false}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() {
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
// Older versions saved 100–150, although their geometry already capped the ratio at 0.9999.
|
||||
for clockwise in [false, true] {
|
||||
let mut s = session();
|
||||
let mut prefs = Prefs::default();
|
||||
prefs.tool_settings.insert("spiral".into(), json!({"decay": 150, "segments": 4, "clockwise": clockwise}).as_object().unwrap().clone());
|
||||
s.apply_prefs(serde_json::from_str(&serde_json::to_string(&prefs).unwrap()).unwrap());
|
||||
let view = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("spiral", view).unwrap();
|
||||
let decay = s.tool_options()["decay"].as_f64().unwrap();
|
||||
assert_eq!(decay, 99.99);
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
for (kind, x) in [(PointerKind::Down, 200.0), (PointerKind::Drag, 300.0), (PointerKind::Up, 300.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, 200.0), view).unwrap();
|
||||
}
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.history.undo.len(), before + 1);
|
||||
assert_eq!(d.selection.objects.len(), 1);
|
||||
let id = d.selection.objects[0];
|
||||
let path = d.doc.node(id).unwrap().path_data().unwrap().clone();
|
||||
let anchors = &path.subpaths[0].anchors;
|
||||
assert_eq!(anchors.len(), 5);
|
||||
assert!(!path.is_closed());
|
||||
let center = Point::new(200.0, 200.0);
|
||||
// The path runs from the centre end outwards, and decay is per full wind: four quarter-turn
|
||||
// segments give the decay.
|
||||
for pair in anchors.windows(2) {
|
||||
let ratio = pair[0].p.distance(center) / pair[1].p.distance(center);
|
||||
assert!((100.0 * ratio.powi(4) - decay).abs() < 1e-9);
|
||||
}
|
||||
assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap(), &path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape on a polygon or rounded rectangle drag puts back the side count or corner radius its
|
||||
/// arrows changed, in the saved options and the Corner Radius preference too.
|
||||
#[test]
|
||||
|
||||
@@ -149,6 +149,34 @@ fn loading_an_assigned_profile_again_keeps_it_in_use() {
|
||||
assert_eq!(cms::working_settings(), working);
|
||||
}
|
||||
|
||||
/// A document behind the front one draws through its own assigned profile: loading that profile's
|
||||
/// file again or removing it redraws the document, and the front document stays as it was.
|
||||
#[test]
|
||||
fn loading_or_removing_a_back_documents_profile_redraws_it() {
|
||||
const NAME: &str = "Back RGB P";
|
||||
let _g = settings();
|
||||
let dir = fresh_dir("back-assigned");
|
||||
let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![dir.clone()] };
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("back.icc");
|
||||
std::fs::write(&path, icc_named(NAME)).unwrap();
|
||||
let mut s = session();
|
||||
let load = |s: &mut Session| assert_eq!(exec(s, "color.loadProfile", json!({"path": path.to_str().unwrap()}))["name"], NAME);
|
||||
load(&mut s);
|
||||
exec(&mut s, "edit.assignProfile", json!({"rgb": NAME}));
|
||||
exec(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::<Vec<_>>();
|
||||
let before = revisions(&s);
|
||||
load(&mut s);
|
||||
let loaded = revisions(&s);
|
||||
assert!(loaded[0] > before[0], "the back document assigned the profile redraws after a load");
|
||||
assert_eq!(loaded[1], before[1], "the front document does not use it");
|
||||
exec(&mut s, "color.removeProfile", json!({"name": NAME}));
|
||||
let removed = revisions(&s);
|
||||
assert!(removed[0] > loaded[0], "the back document assigned the profile redraws after a removal");
|
||||
assert_eq!(removed[1], loaded[1], "the front document does not use it");
|
||||
}
|
||||
|
||||
/// A batch that assigns a profile and then changes the color mode, as Document Setup's OK does,
|
||||
/// converts the colors through the profile it assigns.
|
||||
#[test]
|
||||
|
||||
@@ -4329,7 +4329,8 @@ proptest! {
|
||||
"0 R", "0 O", "0 1 1 0 K", "1 0 0 0 k", "0 0 0 0 1 0 0 Xa", "0 0 0 0 1 0 0 XA", "0.5 G", "0 g", "K", "Xa",
|
||||
"0 J 0 j 2 w 10 M []0 d", "-1 w", "1e400 w", "0 M", "[3 -1]0 d", "[]0 d",
|
||||
"1 0 Xd", "0 1 Xd", "1 1 Xd", "0 0 Xd", "1 Xd", "Xd", "0 1 0 0 0 Xy", "1 0.5 1 1 0 Xy", "Xy",
|
||||
"0 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p",
|
||||
"0 Bb", "1 Bb", "2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg", "2 (Sky) 0 0 1e400 100 1 0 0 1 0 0 Bg", "2 (Dusk) 0 0 0 100 1 0 0 1 0 0 Bg",
|
||||
"0 BB", "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p",
|
||||
"(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P", "0 XR",
|
||||
]).prop_map(|op| (op.to_string(), true)),
|
||||
"[ -~]{0,12}".prop_map(|text| (text, false)),
|
||||
@@ -4338,9 +4339,11 @@ proptest! {
|
||||
) {
|
||||
use vectorcraft_testkit::ai;
|
||||
let close = if closed { "/Paint ;\n/Def ;\n" } else { "" };
|
||||
// C, a red 2 pt stroke, comes first, so that it reads whatever A holds.
|
||||
// C, a red 2 pt stroke, comes first, so that it reads whatever A holds. The file defines the
|
||||
// gradient Sky, which a gradient paint of A may name.
|
||||
let header = format!(
|
||||
"%AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\
|
||||
"%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\
|
||||
%AI9_BeginArtStyles\n/KnownStyle :\n(C) /Name ,\n/SimpleStyle :\n0 R\n0 1 1 0 K\n2 w\n1 0 Xd\n/Paint ;\n/Def ;\n\
|
||||
/KnownStyle :\n(A) /Name ,\n/SimpleStyle :\n{}\n{close}/KnownStyle :\n(B) /Name ,\n/SimpleStyle :\n1 0 Xd\n/Paint ;\n/Def ;\n\
|
||||
%AI9_EndArtStyles\n%AI9_BeginArtStyleList\n(A)\n(B)\n(C)\n%AI9_EndArtStyleList\n",
|
||||
ops.iter().map(|(op, _)| op.as_str()).collect::<Vec<_>>().join("\n")
|
||||
|
||||
@@ -419,6 +419,56 @@ fn a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side() {
|
||||
assert_eq!(text(&s, id), "100.00 pt");
|
||||
}
|
||||
|
||||
/// An unlinked aligned dimension reflected on its own has its line on the reflected side of its
|
||||
/// points: a line 30 pt above a level pair is 30 pt below it after a flip top to bottom, and a
|
||||
/// half turn moves it below them as well, by turning it.
|
||||
#[test]
|
||||
fn a_reflected_aligned_dimension_keeps_its_line_on_the_reflected_side() {
|
||||
let mut s = session();
|
||||
let id = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,200],"offset":-30}))["id"].as_u64().unwrap();
|
||||
assert_eq!(path_ends(&s, id)[2], vec![(100.0, 170.0), (200.0, 170.0)]);
|
||||
run(&mut s, "select.set", json!({"ids":[id]}));
|
||||
run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,200]}));
|
||||
assert_eq!(path_ends(&s, id)[2], vec![(100.0, 230.0), (200.0, 230.0)]);
|
||||
assert_eq!(text(&s, id), "100.00 pt");
|
||||
// Reflected left to right, the points swap ends and the line stays below them.
|
||||
run(&mut s, "object.reflect", json!({"axis":"vertical","origin":[150,0]}));
|
||||
assert_eq!(path_ends(&s, id)[2], vec![(200.0, 230.0), (100.0, 230.0)]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(path_ends(&s, id)[2], vec![(100.0, 170.0), (200.0, 170.0)]);
|
||||
// A half turn about the points' midpoint puts the line below them by turning it.
|
||||
run(&mut s, "object.rotate", json!({"angle":180,"origin":[150,200]}));
|
||||
let ends = path_ends(&s, id)[2].iter().map(|(x, y)| (x.round(), y.round())).collect::<Vec<_>>();
|
||||
assert_eq!(ends, vec![(200.0, 230.0), (100.0, 230.0)]);
|
||||
}
|
||||
|
||||
/// An unlinked aligned dimension of a diagonal pair reflected about a mirror line through its
|
||||
/// points has its line on the other side of them, and a scale by a negative factor reverses the
|
||||
/// side as a reflection does, while a scale by positive factors keeps it.
|
||||
#[test]
|
||||
fn an_aligned_dimension_reflected_about_an_angle_or_scaled_by_a_negative_factor_changes_sides() {
|
||||
let mut s = session();
|
||||
let id = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,100],"offset":-30}))["id"].as_u64().unwrap();
|
||||
let k = 30.0 / 2f64.sqrt();
|
||||
let near = |got: &[(f64, f64)], want: [(f64, f64); 2]| got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6);
|
||||
let ends = path_ends(&s, id)[2].clone();
|
||||
assert!(near(&ends, [(100.0 - k, 200.0 - k), (200.0 - k, 100.0 - k)]), "{ends:?}");
|
||||
run(&mut s, "select.set", json!({"ids":[id]}));
|
||||
// The mirror line at 45 degrees through (150, 150) holds both points.
|
||||
run(&mut s, "object.reflect", json!({"axis":45,"origin":[150,150]}));
|
||||
let ends = path_ends(&s, id)[2].clone();
|
||||
assert!(near(&ends, [(100.0 + k, 200.0 + k), (200.0 + k, 100.0 + k)]), "{ends:?}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
let level = run(&mut s, "dimension.create", json!({"a":[100,200],"b":[200,200],"offset":-30}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[level]}));
|
||||
run(&mut s, "object.scale", json!({"sx":-200,"sy":100,"origin":[150,0]}));
|
||||
assert_eq!(path_ends(&s, level)[2], vec![(250.0, 170.0), (50.0, 170.0)]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
run(&mut s, "object.scale", json!({"sx":200,"sy":200,"origin":[150,200]}));
|
||||
assert_eq!(path_ends(&s, level)[2], vec![(50.0, 170.0), (250.0, 170.0)]);
|
||||
}
|
||||
|
||||
/// The line of a linked horizontal dimension below both points stays below them when the art
|
||||
/// turns a half turn; a line between the points keeps its distance from the first point.
|
||||
#[test]
|
||||
|
||||
@@ -950,9 +950,10 @@ proptest! {
|
||||
prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec()));
|
||||
prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec()));
|
||||
prop_assert_eq!(theirs.cache_bytes(), 4);
|
||||
// The host names every file: the store holds the two modules, their grants and their folders.
|
||||
// The host names every file: the store holds the two modules, their grants, their folders and
|
||||
// the file windows lock while they change the store.
|
||||
let names = |dir: &std::path::Path| std::fs::read_dir(dir).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect::<Vec<_>>();
|
||||
prop_assert!(names(&folder).len() <= 4, "{:?}", names(&folder));
|
||||
prop_assert!(names(&folder).len() <= 5, "{:?}", names(&folder));
|
||||
prop_assert!(names(&folder.join("storage")).len() <= 2, "{:?}", names(&folder.join("storage")));
|
||||
let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage"}));
|
||||
let _ = s.execute("plugin.remove", &json!({"id": "fuzz.storage.other"}));
|
||||
|
||||
@@ -1187,6 +1187,28 @@ fn a_symbol_definition_is_written_only_with_room_for_its_instance() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol definition without room for its group, asked for by an instance in art drawn for an
|
||||
/// object (a stained instance's art), is left out and leaves the writing of that art as it was.
|
||||
#[test]
|
||||
fn a_symbol_definition_without_room_in_drawn_art_is_left_out() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let dot = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::gray(0.5));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Dot".into(), art: Arc::new(dot) });
|
||||
let inner = instance(&mut doc, "Dot", Affine::IDENTITY);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Badge".into(), art: Arc::new(inner) });
|
||||
let mut stained = instance(&mut doc, "Badge", Affine::translate((50.0, 10.0)));
|
||||
stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
doc.insert(Some(layer), usize::MAX, stained).unwrap();
|
||||
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
|
||||
for max in 0..read {
|
||||
let out = export_within(&doc, &opts(), max).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "room for {max} of {read}");
|
||||
let objects = crate::import::objects_read(&out.program).unwrap();
|
||||
assert!(objects <= max, "{objects} objects read with room for {max}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The writer's limit is the reader's, which its warning names.
|
||||
#[test]
|
||||
fn the_object_limit_is_the_readers() {
|
||||
@@ -10563,14 +10585,15 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() {
|
||||
}
|
||||
|
||||
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
|
||||
/// two objects: its text wrap options are written once, whether it has both or only strokes.
|
||||
/// two objects: its text wrap options are written once, whether it has both or only strokes, and
|
||||
/// with its strokes when the region outside leaves nothing of its fills.
|
||||
#[test]
|
||||
fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
|
||||
for fill in [solid(Color::gray(0.5)), Paint::None] {
|
||||
for (fill, left, width) in [(solid(Color::gray(0.5)), 20.0, 2.0), (Paint::None, 20.0, 2.0), (solid(Color::gray(0.5)), 101.0, 4.0)] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)));
|
||||
cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), 2.0).into();
|
||||
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(left, 20.0, left + 60.0, 80.0)));
|
||||
cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), width).into();
|
||||
let cutter = wrapped(cutter, 5.0, true);
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 120.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let inner = group(&mut doc, vec![cutter, member], true);
|
||||
|
||||
@@ -1102,22 +1102,25 @@ impl<'a> Writer<'a> {
|
||||
|
||||
/// A container's members, the first one's outline cutting the others: its fills painted
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
|
||||
/// wrap options are written once: with its fills, or without fills with its strokes.
|
||||
/// wrap options are written once: with its fills, or with its strokes when no fill object is
|
||||
/// written (it has no fills, or the region outside leaves nothing of them).
|
||||
fn clip_contents(&mut self, children: &[Arc<Node>]) {
|
||||
let Some((first, rest)) = children.split_first() else { return };
|
||||
// Nothing to clip by hides the clipped art.
|
||||
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
|
||||
let mut paint = first.clip_paint();
|
||||
if let (Some(_), Some(stroke)) = (&paint.fill, &mut paint.stroke)
|
||||
&& stroke.extras().wrap.is_some()
|
||||
{
|
||||
stroke.extras_mut().wrap = None;
|
||||
}
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(&PathData::from_bezpath(&outline), rule);
|
||||
self.clip = Some(region);
|
||||
if let Some(fill) = &paint.fill {
|
||||
let objects = self.objects;
|
||||
self.node(fill);
|
||||
if self.objects > objects
|
||||
&& let Some(stroke) = &mut paint.stroke
|
||||
&& stroke.extras().wrap.is_some()
|
||||
{
|
||||
stroke.extras_mut().wrap = None;
|
||||
}
|
||||
}
|
||||
for c in rest {
|
||||
self.node(c);
|
||||
|
||||
@@ -233,6 +233,7 @@ impl Writer<'_> {
|
||||
if !self.take_objects(1) {
|
||||
self.defining_symbols.pop();
|
||||
self.keep_since(before);
|
||||
(self.in_look, self.drawn) = (in_look, drawn);
|
||||
return false;
|
||||
}
|
||||
// The art is written in the symbol's space, from the state `0 A` and `0 Xw` set, from the
|
||||
|
||||
@@ -1147,7 +1147,7 @@ impl<'a> Reader<'a> {
|
||||
continue;
|
||||
}
|
||||
let Some(st) = self.styles.get(&name) else { continue };
|
||||
let Some(mut appearance) = appearance_from_art_style(st) else { continue };
|
||||
let Some(mut appearance) = appearance_from_art_style(st, &self.gradients) else { continue };
|
||||
// A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]).
|
||||
if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) {
|
||||
appearance.scale_strokes(s);
|
||||
|
||||
@@ -1323,9 +1323,11 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
|
||||
}
|
||||
|
||||
/// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one
|
||||
/// this reads, or paints with a gradient or a pattern (placed on each object as its drawn look has them).
|
||||
/// this reads, paints with a pattern, or paints with a gradient that names no swatch of `gradients`.
|
||||
/// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]).
|
||||
pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle) -> Option<Appearance> {
|
||||
/// A style keeps only its gradients' names and angles, so each one's gradient, by VectorCraft's own
|
||||
/// rule, is fitted to the bounds of whatever object the style is applied to, at its angle.
|
||||
pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, gradients: &HashMap<String, Gradient>) -> Option<Appearance> {
|
||||
use crate::import::ai::style::StyleItem;
|
||||
if !st.plain {
|
||||
return None;
|
||||
@@ -1341,8 +1343,15 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle)
|
||||
// A graphic style's brush isn't checked against the file's brushes: it is left out.
|
||||
StyleItem::Stroke { brush: Some(_), .. } => return None,
|
||||
StyleItem::Stroke { .. } => stroke_layer(item)?,
|
||||
StyleItem::Gradient { .. } | StyleItem::Pattern { .. } => return None,
|
||||
StyleItem::Gradient { name, angle } => AppearanceItem::Fill(FillLayer::new(named_gradient(name.as_deref()?, *angle, gradients)?)),
|
||||
StyleItem::Pattern { .. } => return None,
|
||||
};
|
||||
// A one-paint style's gradient stroke names its swatch (`style::OnePaint::items`).
|
||||
if let AppearanceItem::Stroke(s) = &mut layer
|
||||
&& let Paint::Gradient(g) = &s.paint
|
||||
{
|
||||
s.paint = named_gradient(g.swatch.as_deref()?, g.angle, gradients)?;
|
||||
}
|
||||
if let Some(look) = st.looks.get(n) {
|
||||
with_look(&mut layer, look);
|
||||
}
|
||||
@@ -1351,6 +1360,14 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle)
|
||||
Some(Appearance { items, effects: st.effects.clone(), contents_index: st.contents_index })
|
||||
}
|
||||
|
||||
/// The gradient of `gradients` named `name` at `angle` degrees, fitted to the bounds of the object it
|
||||
/// paints (`None` when there is no such gradient).
|
||||
fn named_gradient(name: &str, angle: f64, gradients: &HashMap<String, Gradient>) -> Option<Paint> {
|
||||
let mut g = vectorcraft_color::gradient::GradientPaint::new(gradients.get(name)?.clone());
|
||||
g.angle = angle;
|
||||
Some(Paint::Gradient(Box::new(g)))
|
||||
}
|
||||
|
||||
/// What the reader makes of art style `name` in `section` (the text between `%AI9_BeginArtStyles`
|
||||
/// and its end), for writers that check a style before they write it.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -1400,7 +1417,9 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut appearance = appearance_from_art_style(&st)?;
|
||||
// No gradient is taken by name: on an object, one that isn't its own is placed where its drawn
|
||||
// look has it.
|
||||
let mut appearance = appearance_from_art_style(&st, &HashMap::new())?;
|
||||
for (item, brush) in appearance.items.iter_mut().zip(brushes) {
|
||||
if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) {
|
||||
s.brush = Some(brush);
|
||||
|
||||
@@ -216,7 +216,8 @@ pub(super) struct ArtStyle {
|
||||
pub simple_pattern: Option<StyleItem>,
|
||||
/// A style that is one paint: its fill and stroke, bottom first, each there when its
|
||||
/// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or
|
||||
/// stroke whose paint isn't read here (a gradient, a pattern, a color that isn't read) or has
|
||||
/// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient
|
||||
/// instance, a pattern, a color that isn't read) or has
|
||||
/// no `Xd`. `None` for a style with filters, whose paint is [`Self::items`].
|
||||
pub one_paint: Option<Result<Vec<StyleItem>, ()>>,
|
||||
}
|
||||
@@ -313,6 +314,8 @@ struct Filter {
|
||||
gradient_of: Option<(Option<String>, f64)>,
|
||||
/// `(name) … [matrix] p`, and the numbers between the name and the matrix.
|
||||
pattern: Option<(String, Option<[f64; 6]>, Vec<f64>)>,
|
||||
/// Its last fill paint, which replaces those before it.
|
||||
fill_last: LastPaint,
|
||||
/// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and
|
||||
/// plug-in name.
|
||||
plugin_object: Option<(String, String)>,
|
||||
@@ -346,6 +349,7 @@ impl Default for Filter {
|
||||
gradient: false,
|
||||
gradient_of: None,
|
||||
pattern: None,
|
||||
fill_last: LastPaint::None,
|
||||
plugin_object: None,
|
||||
xy: None,
|
||||
xy_group: None,
|
||||
@@ -354,6 +358,15 @@ impl Default for Filter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which paint a filter's paint operators set last.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum LastPaint {
|
||||
None,
|
||||
Color,
|
||||
Gradient,
|
||||
Pattern,
|
||||
}
|
||||
|
||||
/// Most filters read in one style.
|
||||
const MAX_FILTERS: usize = 4096;
|
||||
|
||||
@@ -662,7 +675,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) {
|
||||
| "xz" => {
|
||||
let Some((p, _)) = paint::color_op_in(op, vals, names) else { return };
|
||||
if op.ends_with(|c: char| c.is_ascii_lowercase()) {
|
||||
f.fill = Some(p);
|
||||
(f.fill, f.fill_last) = (Some(p), LastPaint::Color);
|
||||
} else {
|
||||
f.stroke = Some(p);
|
||||
}
|
||||
@@ -719,7 +732,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) {
|
||||
}
|
||||
// `flag (name) x y angle length a b c d tx ty Bg`.
|
||||
"Bg" => {
|
||||
f.gradient = true;
|
||||
(f.gradient, f.fill_last) = (true, LastPaint::Gradient);
|
||||
let at = vals.iter().rposition(|v| matches!(v, V::Str(_)));
|
||||
let name = at.and_then(|i| vals.get(i)).and_then(|v| names.text(v));
|
||||
let n: Vec<f64> = at.map_or(&[][..], |i| vals.get(i + 1..).unwrap_or_default()).iter().filter_map(V::num).collect();
|
||||
@@ -728,7 +741,7 @@ fn paint_op(f: &mut Filter, op: &str, vals: &[V], names: &mut Names) {
|
||||
}
|
||||
"p" => {
|
||||
if let Some(pattern) = pattern_operands(vals, names) {
|
||||
f.pattern = Some(pattern);
|
||||
(f.pattern, f.fill_last) = (Some(pattern), LastPaint::Pattern);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -786,6 +799,11 @@ struct OnePaint {
|
||||
stroke_unread: bool,
|
||||
/// Inside a gradient instance (`flag Bb` … `BB`): whether it paints the stroke (flag 1).
|
||||
instance: Option<bool>,
|
||||
/// The gradient swatch's name and angle of its last fill paint, when that is a gradient
|
||||
/// instance's `Bg`.
|
||||
fill_gradient: Option<(String, f64)>,
|
||||
/// The same for its last stroke paint.
|
||||
stroke_gradient: Option<(String, f64)>,
|
||||
}
|
||||
|
||||
impl OnePaint {
|
||||
@@ -811,9 +829,26 @@ impl OnePaint {
|
||||
_ => {}
|
||||
}
|
||||
paint_op(&mut self.paint, op, vals, names);
|
||||
// A gradient instance's `Bg` names the swatch its fill or stroke paints with; any other
|
||||
// paint of that side replaces it. Outside an instance, which side it paints isn't known.
|
||||
let named = || match (op, &self.paint.gradient_of) {
|
||||
("Bg", Some((Some(name), angle))) => Some((name.clone(), *angle)),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
"Bg" if self.instance == Some(true) => self.stroke_gradient = named(),
|
||||
"Bg" if self.instance == Some(false) => self.fill_gradient = named(),
|
||||
"Bg" => (self.fill_gradient, self.stroke_gradient) = (None, None),
|
||||
"p" | "Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => self.fill_gradient = None,
|
||||
"P" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" => self.stroke_gradient = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Its fill and stroke ([`ArtStyle::one_paint`]).
|
||||
/// Its fill and stroke ([`ArtStyle::one_paint`]). A gradient fill is its [`StyleItem::Gradient`];
|
||||
/// a gradient stroke's paint is a gradient that only names its swatch (`swatch`) at its angle,
|
||||
/// with default stops: `read::ops`' `appearance_from_art_style` gives it the file's gradient of
|
||||
/// that name.
|
||||
fn items(&self) -> Result<Vec<StyleItem>, ()> {
|
||||
let f = &self.paint;
|
||||
if !self.xd {
|
||||
@@ -822,14 +857,22 @@ impl OnePaint {
|
||||
let (stroked, filled) = f.paints;
|
||||
let mut items = vec![];
|
||||
if filled {
|
||||
match &f.fill {
|
||||
Some(p) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())),
|
||||
match (&f.fill, &self.fill_gradient) {
|
||||
(Some(p), _) if !self.fill_unread => items.push(StyleItem::Fill(p.clone())),
|
||||
(_, Some((name, angle))) if self.fill_unread => items.push(StyleItem::Gradient { name: Some(name.clone()), angle: *angle }),
|
||||
_ => return Err(()),
|
||||
}
|
||||
}
|
||||
if stroked {
|
||||
match &f.stroke {
|
||||
Some(p) if !self.stroke_unread => items.push(StyleItem::Stroke {
|
||||
let named = self.stroke_gradient.as_ref().filter(|_| self.stroke_unread).map(|(name, angle)| {
|
||||
Paint::Gradient(Box::new(vectorcraft_color::gradient::GradientPaint {
|
||||
angle: *angle,
|
||||
swatch: Some(name.clone()),
|
||||
..vectorcraft_color::gradient::GradientPaint::new(vectorcraft_color::gradient::Gradient::default())
|
||||
}))
|
||||
});
|
||||
match named.as_ref().or(f.stroke.as_ref().filter(|_| !self.stroke_unread)) {
|
||||
Some(p) => items.push(StyleItem::Stroke {
|
||||
paint: p.clone(),
|
||||
width: f.width,
|
||||
cap: f.cap,
|
||||
@@ -1396,6 +1439,8 @@ fn paint_item(f: &Filter) -> Result<Option<StyleItem>, ()> {
|
||||
match f.name.as_str() {
|
||||
FILL if !f.paints.1 => Ok(None),
|
||||
FILL => match (&f.pattern, &f.gradient_of, &f.fill) {
|
||||
(.., Some(p)) if f.fill_last == LastPaint::Color => Ok(Some(StyleItem::Fill(p.clone()))),
|
||||
(_, Some((name, angle)), _) if f.fill_last == LastPaint::Gradient => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })),
|
||||
(Some((name, matrix, controls)), ..) => Ok(Some(StyleItem::Pattern { name: name.clone(), matrix: *matrix, controls: controls.clone() })),
|
||||
(None, Some((name, angle)), _) => Ok(Some(StyleItem::Gradient { name: name.clone(), angle: *angle })),
|
||||
(None, None, _) if f.gradient => Ok(Some(StyleItem::Gradient { name: None, angle: 0.0 })),
|
||||
|
||||
@@ -471,6 +471,28 @@ fn lettering() -> String {
|
||||
format!("/KnownStyle :\n(Lettering) /Name ,\n/ActiveStyle :\n{root}\n/Execution ;\n /Def ;\n")
|
||||
}
|
||||
|
||||
/// A fill filter's last paint is its fill: a color, a gradient or a pattern replaces whichever of the
|
||||
/// others came before it.
|
||||
#[test]
|
||||
fn a_fill_filter_paints_with_its_last_paint() {
|
||||
let gradient = "0 Bb\n2 (Sky) 0 0 30 1 1 0 0 1 0 0 1 Bg\n0 BB";
|
||||
let pattern = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p";
|
||||
let color = "0 0 0 0 1 0 0 Xa";
|
||||
let items = |paint: String| {
|
||||
let root = compound("Chain Style Filter", &[fill(&paint)]);
|
||||
let data = format!("/KnownStyle :\n(S) /Name ,\n/ActiveStyle :\n{root}\n/Execution ;\n /Def ;\n");
|
||||
art_styles(data.as_bytes()).remove("S").map(|s| s.items).unwrap_or_default()
|
||||
};
|
||||
for before in [gradient, pattern] {
|
||||
assert!(matches!(items(format!("{before}\n{color}")).as_slice(), [StyleItem::Fill(Paint::Solid { .. })]), "{before}");
|
||||
}
|
||||
for before in [color, pattern] {
|
||||
assert_eq!(items(format!("{before}\n{gradient}")), [StyleItem::Gradient { name: Some("Sky".into()), angle: 30.0 }], "{before}");
|
||||
}
|
||||
assert!(matches!(items(format!("{color}\n{pattern}")).as_slice(), [StyleItem::Pattern { .. }]));
|
||||
assert!(matches!(items(format!("{gradient}\n{pattern}")).as_slice(), [StyleItem::Pattern { .. }]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stack_of_fills_with_effects_of_their_own_is_read_as_itself() {
|
||||
// GUARDS: more than one fill, or an effect on a fill, made the style not plain, and type
|
||||
@@ -1544,14 +1566,22 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() {
|
||||
// A gradient instance's flag says which one it paints: a stroke gradient leaves a solid fill read.
|
||||
let fill_and_stroke_gradient = one("0 0 1 0 k\n1 Bb\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 1 Xd\n");
|
||||
assert!(matches!(fill_and_stroke_gradient, Some(Ok(i)) if matches!(i.as_slice(), [StyleItem::Fill(_)])));
|
||||
// Not read: no `Xd`, a gradient or pattern fill, a pattern stroke, a gradient stroke after a solid one, a paint
|
||||
// turned on with no color.
|
||||
// A gradient instance's fill is its swatch at its angle; its stroke, after a solid one too, is a
|
||||
// gradient naming its swatch at its angle, at the stroke's weight.
|
||||
let gradient_fill = one("0 Bb\n2 (Sky) 0 0 30 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n");
|
||||
assert_eq!(gradient_fill, Some(Ok(vec![StyleItem::Gradient { name: Some("Sky".into()), angle: 30.0 }])));
|
||||
let gradient_stroke = one("0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n");
|
||||
let Some(Ok(items)) = &gradient_stroke else { panic!("{gradient_stroke:?}") };
|
||||
let [StyleItem::Stroke { paint: Paint::Gradient(g), width, .. }] = items.as_slice() else { panic!("{items:?}") };
|
||||
assert_eq!((g.swatch.as_deref(), g.angle, g.geom, *width), (Some("Ramp"), 90.0, None, 2.0));
|
||||
// Not read: no `Xd`, a pattern fill, a pattern stroke, a gradient outside a gradient instance, a
|
||||
// paint turned on with no color.
|
||||
for paint in [
|
||||
format!("0 0 1 0 k\n{stroke}"),
|
||||
"0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n0 1 Xd\n".to_string(),
|
||||
"(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(),
|
||||
"(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n1 0 Xd\n".to_string(),
|
||||
"0 R\n0 1 1 0 K\n1 Bb\n0 0 0 0 Bh\n2 (Ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n2 w\n1 0 Xd\n".to_string(),
|
||||
"2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 1 Xd\n".to_string(),
|
||||
"0 Bb\n2 (Sky) 0 0 0 100 1 0 0 1 0 0 Bg\n0 BB\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 1 Xd\n".to_string(),
|
||||
"0 0 1 0 k\n1 1 Xd\n".to_string(),
|
||||
] {
|
||||
assert_eq!(one(&paint), Some(Err(())), "{paint}");
|
||||
|
||||
@@ -279,6 +279,7 @@ fn code_space(cmap: &str) -> Option<CodeSpace> {
|
||||
const CNS_EUC: CodeSpace = &[(b"\x00", b"\x80"), (b"\xa1\xa1", b"\xfe\xfe"), (b"\x8e\xa1\xa1\xa1", b"\x8e\xa3\xfe\xfe")];
|
||||
const KSC_PC: CodeSpace = &[(b"\x00", b"\x84"), (b"\xfe", b"\xff"), (b"\xa1\x41", b"\xfd\xfe")];
|
||||
const UHC: CodeSpace = &[(b"\x00", b"\x80"), (b"\x81\x41", b"\xfe\xfe")];
|
||||
const JOHAB: CodeSpace = &[(b"\x00", b"\x80"), (b"\x84\x41", b"\xd3\xfe"), (b"\xd8\x31", b"\xde\xfe"), (b"\xe0\x31", b"\xf9\xfe")];
|
||||
let stem = match cmap {
|
||||
"H" | "V" => "",
|
||||
_ => cmap.strip_suffix("-H").or_else(|| cmap.strip_suffix("-V"))?,
|
||||
@@ -301,6 +302,7 @@ fn code_space(cmap: &str) -> Option<CodeSpace> {
|
||||
"CNS-EUC" => CNS_EUC,
|
||||
"KSCpc-EUC" => KSC_PC,
|
||||
"KSCms-UHC" => UHC,
|
||||
"KSC-Johab" => JOHAB,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -677,6 +677,10 @@ fn latin_names_ending_in_h_and_cmaps_that_cannot_be_read() {
|
||||
"/Ryumin-Light-GBT-H findfont 20 scalefont setfont <09092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and",
|
||||
// A byte that starts no row-and-cell code is a code of its own, also before a tab: three.
|
||||
"/Ryumin-Light-GBT-H findfont 20 scalefont setfont <21092121> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and",
|
||||
// In the Johab code space each ASCII byte is a one-byte code and a Hangul code takes two
|
||||
// bytes: three codes, across and down.
|
||||
"/Ryumin-Light-KSC-Johab-H findfont 20 scalefont setfont <41428441> stringwidth abs 0.01 lt exch 60 sub abs 0.01 lt and",
|
||||
"/Ryumin-Light-KSC-Johab-V findfont 20 scalefont setfont 10 100 moveto <41428441> show currentpoint 40 sub abs 0.01 lt exch 10 sub abs 0.01 lt and",
|
||||
] {
|
||||
let r = super::tests::read(&format!("{cond} {{ 0 0 10 10 rectfill }} if"));
|
||||
assert!(all(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. })), "{cond}");
|
||||
|
||||
@@ -1324,6 +1324,79 @@ fn the_page_limit_counts_a_repeated_images_samples_once() {
|
||||
assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len());
|
||||
}
|
||||
|
||||
/// Type whose color bitmap glyphs fit under the page limit but whose run fill passes it is left
|
||||
/// out with its glyph image placements: the page is the page without that type. A glyph image
|
||||
/// that other art draws once more is written inline there again, and an image that other art
|
||||
/// draws twice keeps its shared samples.
|
||||
#[test]
|
||||
fn type_taken_back_for_the_page_limit_takes_its_glyph_images_with_it() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
use vectorcraft_text::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font};
|
||||
vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap());
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let type_node = |d: &mut Document, at: Point, text: &str, fill: Paint| {
|
||||
let st = CharStyle { font_family: colour_bitmap_family(false).into(), size: 32.0, fill, ..CharStyle::default() };
|
||||
Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(at, text, st))))
|
||||
};
|
||||
// Six glyph images, then outlines enough for the fill to pass the limit.
|
||||
let target = format!("{}{}", COLOUR_CHAR.to_string().repeat(6), "W".repeat(40));
|
||||
// `shared`: an image drawn twice comes first; `before`: one glyph drawn with the type's image;
|
||||
// `fill`: the type's run fill (`None`: no type). A red rectangle comes last.
|
||||
let build = |shared: bool, before: bool, fill: Option<Paint>| {
|
||||
let mut d = if shared {
|
||||
let mut d = image_doc(&noise(8, 8), 1.0);
|
||||
place_again(&mut d, 0, Affine::translate((40.0, 0.0)));
|
||||
d
|
||||
} else {
|
||||
Document::new(200.0, 200.0)
|
||||
};
|
||||
let mut nodes = vec![];
|
||||
if before {
|
||||
nodes.push(type_node(&mut d, Point::new(20.0, 40.0), &COLOUR_CHAR.to_string(), black.clone()));
|
||||
}
|
||||
if let Some(fill) = fill {
|
||||
nodes.push(type_node(&mut d, Point::new(20.0, 100.0), &target, fill));
|
||||
}
|
||||
nodes.push(red_rect(&mut d));
|
||||
for n in nodes {
|
||||
d.insert(d.default_layer(), usize::MAX, n).unwrap();
|
||||
}
|
||||
d
|
||||
};
|
||||
for shared in [false, true] {
|
||||
for before in [false, true] {
|
||||
let case = format!("shared {shared}, before {before}");
|
||||
let (without, unfilled, filled) =
|
||||
(build(shared, before, None), build(shared, before, Some(Paint::None)), build(shared, before, Some(black.clone())));
|
||||
let o = opts(&filled);
|
||||
let glyph = usize::from(shared);
|
||||
let fits = crate::scene::Scene::new(&unfilled, &o).run();
|
||||
let full = crate::scene::Scene::new(&filled, &o).run();
|
||||
assert!(fits.warnings.is_empty() && full.warnings.is_empty(), "{case}: {:?} {:?}", fits.warnings, full.warnings);
|
||||
assert_eq!(reuses(&fits.body, glyph, o.level), 6 + usize::from(before), "{case}: {}", fits.body);
|
||||
assert_eq!(reuses(&full.body, glyph, o.level), 6 + usize::from(before), "{case}: {}", full.body);
|
||||
let (fits_len, full_len) = (fits.body.len() + fits.setup.len(), full.body.len() + full.setup.len());
|
||||
assert!(full_len > fits_len + 2000, "{case}: {fits_len} {full_len}");
|
||||
let limit = (fits_len + full_len) / 2;
|
||||
// Without its fill the type fits, every glyph image with it.
|
||||
let page = crate::scene::Scene::new(&unfilled, &o).with_max_body(limit).run();
|
||||
assert!(page.warnings.is_empty(), "{case}: {:?}", page.warnings);
|
||||
assert_eq!((page.setup, page.body), (fits.setup, fits.body), "{case}");
|
||||
// With it the type is taken back after its glyph images were placed.
|
||||
let page = crate::scene::Scene::new(&filled, &o).with_max_body(limit).run();
|
||||
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{case}: {:?}", page.warnings);
|
||||
let alone = crate::scene::Scene::new(&without, &o).run();
|
||||
assert!(alone.warnings.is_empty(), "{case}: {:?}", alone.warnings);
|
||||
assert_eq!(reuses(&page.body, glyph, o.level), 0, "{case}: {}", page.body);
|
||||
assert!(!page.setup.contains(&format!("/VCim{glyph} ")), "{case}: {}", page.setup);
|
||||
assert_eq!(page.body.matches("/Width 16 /Height 16").count(), usize::from(before), "{case}: {}", page.body);
|
||||
assert_eq!(reuses(&page.body, 0, o.level), if shared { 2 } else { 0 }, "{case}: {}", page.body);
|
||||
assert_eq!((&page.setup, &page.body), (&alone.setup, &alone.body), "{case}");
|
||||
checked_page(&page.body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A freeform gradient of `points` (x, y and color).
|
||||
fn freeform(points: &[(f64, f64, Color)]) -> Paint {
|
||||
let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() });
|
||||
|
||||
@@ -666,7 +666,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"learn.list",
|
||||
"List Tutorials",
|
||||
"",
|
||||
"{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}",
|
||||
"{} the Learn panel's skills in the order its Skills tab lists them, with the progress its rings, counts and check marks show: {skills: [{id, title, done: number of its tutorials finished, total: number of its tutorials, tutorials: [{id, title, steps: number of steps, finished: bool, completedSteps: [zero-based indexes of the steps marked done, every step once finished]}]}]}",
|
||||
),
|
||||
(
|
||||
"learn.skills",
|
||||
@@ -692,11 +692,17 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} open that tutorial's practice sample as a new untitled document, which becomes the active one, and move the Learn view to the tutorial, as its View more button does; each call opens another copy and open documents stay as they are; a missing, non-string or unknown id is an error and changes nothing; returns {tutorial, index, title} of the new document",
|
||||
),
|
||||
(
|
||||
"learn.markStep",
|
||||
"Mark Tutorial Step",
|
||||
"",
|
||||
"{tutorial: id (see learn.list), step: zero-based step number, complete?: bool} mark a step of a tutorial whose sample learn.openSample opened as done (true, omitted or null) or not done (false), as the check box before the step does; marking does not finish the tutorial; a missing, non-string or unknown id, a missing step or one the tutorial does not have, a complete that is not true or false, a tutorial whose sample was not opened, or a finished tutorial is an error and changes nothing; the preferences keep the marks; returns {tutorial, step, complete}",
|
||||
),
|
||||
(
|
||||
"learn.finish",
|
||||
"Finish Tutorial",
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, as its Finish tutorial button does; finishing it again keeps one entry; a missing, non-string or unknown id, or a tutorial whose sample was not opened, is an error and changes nothing; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}",
|
||||
"{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, with all its steps done, as its Finish tutorial button does; finishing it again keeps one entry, and needs no sample after a restart; a missing, non-string or unknown id, or a tutorial not finished whose sample was not opened, is an error and changes nothing; the preferences keep the tutorials finished; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}",
|
||||
),
|
||||
(
|
||||
"learn.next",
|
||||
@@ -704,6 +710,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} show the Learn panel on the tutorial after a finished one in the same skill, as its Next Up button does, without opening a sample; a missing, non-string or unknown id, a tutorial not finished, or a skill's last tutorial is an error and changes nothing; returns {skill, tutorial, title} of the next tutorial",
|
||||
),
|
||||
(
|
||||
"learn.resetProgress",
|
||||
"Reset Learn Progress",
|
||||
"",
|
||||
"{} clear the Learn panel's progress, every tutorial finished and every step marked done, as Reset progress under the list of skills does; open documents, opened practice samples and the Learn view stay as they are; returns what learn.list returns",
|
||||
),
|
||||
("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"),
|
||||
(
|
||||
"window.workspace",
|
||||
|
||||
@@ -144,7 +144,8 @@ impl Exporter<'_> {
|
||||
self.rgb_in_cmyk.images.insert(key.to_string());
|
||||
}
|
||||
let r = if cmyk_image {
|
||||
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None)
|
||||
let icc = out.cmyk_image_icc(blob);
|
||||
crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref())
|
||||
} else {
|
||||
crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels())
|
||||
};
|
||||
@@ -191,7 +192,8 @@ impl Exporter<'_> {
|
||||
let doc = self.doc;
|
||||
let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| {
|
||||
let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?;
|
||||
let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha));
|
||||
let icc = self.out.cmyk_image_icc(blob);
|
||||
let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), icc.as_deref());
|
||||
if let (Some(w), Some(_)) = (r.warning, &r.image) {
|
||||
self.warn(w);
|
||||
}
|
||||
@@ -313,10 +315,6 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
Some(png)
|
||||
}
|
||||
|
||||
/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image
|
||||
/// it holds is still written.
|
||||
const MAX_EMBED_PIXELS: u64 = 1 << 27;
|
||||
|
||||
/// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged),
|
||||
/// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a
|
||||
/// sample is written at 8 bits ([`png_8_bit`]).
|
||||
@@ -324,7 +322,7 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee
|
||||
// The header's size first: the writer's decoders allocate what it declares, and the encoded
|
||||
// bytes of an image that is far larger than any the app reads may be a few kilobytes.
|
||||
let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions();
|
||||
if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > MAX_EMBED_PIXELS) {
|
||||
if size.is_ok_and(|(w, h)| u64::from(w) * u64::from(h) > crate::images::MAX_EMBED_PIXELS) {
|
||||
return None;
|
||||
}
|
||||
let bytes = blob.bytes.as_ref().clone();
|
||||
|
||||
@@ -271,7 +271,8 @@ impl Writer {
|
||||
PdfError::from(e)
|
||||
})?;
|
||||
if self.cmyk {
|
||||
cmyk_blending(&mut bytes, self.out.tagged);
|
||||
let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten();
|
||||
cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b);
|
||||
}
|
||||
let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only();
|
||||
let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes };
|
||||
@@ -285,12 +286,21 @@ impl Writer {
|
||||
/// its blending space (DeviceRGB, or sRGB when colours are `tagged`), so the group dictionaries
|
||||
/// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the
|
||||
/// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that
|
||||
/// of screen colours, as on screen.
|
||||
fn cmyk_blending(pdf: &mut [u8], tagged: bool) {
|
||||
/// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile`
|
||||
/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other
|
||||
/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB;
|
||||
/// without `profile`, they blend in the first CMYK space.
|
||||
fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) {
|
||||
let masks = luminosity_mask_groups(pdf);
|
||||
let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())];
|
||||
if tagged {
|
||||
spaces.extend(icc_spaces(pdf));
|
||||
let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc));
|
||||
let without = match (profile, device) {
|
||||
(None, _) => Without::FirstCmyk,
|
||||
(Some(_), true) => Without::DeviceCmyk,
|
||||
(Some(_), false) => Without::Rgb,
|
||||
};
|
||||
spaces.extend(icc_spaces(pdf, own, without));
|
||||
}
|
||||
let mut from = 0;
|
||||
while let Some(at) = find(pdf, b"/Group<<", from).map(|i| i + b"/Group".len()) {
|
||||
@@ -303,11 +313,22 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// What tagged groups blend in when the file holds no space of the document's CMYK profile.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Without {
|
||||
/// The first ICC-based CMYK space of the file.
|
||||
FirstCmyk,
|
||||
DeviceCmyk,
|
||||
/// The RGB space they have.
|
||||
Rgb,
|
||||
}
|
||||
|
||||
/// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead,
|
||||
/// as group `/CS` entries (`/CS 3 0 R`); none without a CMYK one.
|
||||
fn icc_spaces(pdf: &[u8]) -> Vec<(String, String)> {
|
||||
/// as group `/CS` entries (`/CS 3 0 R`): the one whose profile is stream `own`, else as `without`
|
||||
/// says; none without a CMYK one.
|
||||
fn icc_spaces(pdf: &[u8], own: Option<u32>, without: Without) -> Vec<(String, String)> {
|
||||
const ICC: &[u8] = b"[/ICCBased ";
|
||||
let (mut rgb, mut cmyk) = (vec![], None);
|
||||
let (mut rgb, mut cmyk, mut own_cmyk) = (vec![], None, None);
|
||||
let mut from = 0;
|
||||
while let Some(at) = find(pdf, ICC, from) {
|
||||
from = at + ICC.len();
|
||||
@@ -319,11 +340,19 @@ fn icc_spaces(pdf: &[u8]) -> Vec<(String, String)> {
|
||||
let Some(head) = find(pdf, format!("\n{stream} 0 obj").as_bytes(), 0) else { continue };
|
||||
let dict = pdf.get(head..find(pdf, b"stream", head).unwrap_or(pdf.len())).unwrap_or_default();
|
||||
if find(dict, b"/N 4", 0).is_some() {
|
||||
if own == Some(stream) {
|
||||
own_cmyk.get_or_insert(format!("/CS {array} 0 R"));
|
||||
}
|
||||
cmyk.get_or_insert(format!("/CS {array} 0 R"));
|
||||
} else if find(dict, b"/N 3", 0).is_some() {
|
||||
rgb.push(format!("/CS {array} 0 R"));
|
||||
}
|
||||
}
|
||||
let cmyk = own_cmyk.or_else(|| match without {
|
||||
Without::FirstCmyk => cmyk,
|
||||
Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()),
|
||||
Without::Rgb => None,
|
||||
});
|
||||
let Some(cmyk) = cmyk else { return vec![] };
|
||||
rgb.into_iter().map(|r| (r, cmyk.clone())).collect()
|
||||
}
|
||||
@@ -385,3 +414,27 @@ pub(super) fn date_time(t: i64) -> krilla::metadata::DateTime {
|
||||
.utc_offset_hour(0)
|
||||
.utc_offset_minute(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Without, icc_spaces};
|
||||
|
||||
/// Objects 1 to 3: an RGB ICC-based space (profile 4), then two CMYK ones (profiles 5, 6).
|
||||
const SPACES: &[u8] = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n2 0 obj\n[/ICCBased 5 0 R]\nendobj\n3 0 obj\n[/ICCBased 6 0 R]\nendobj\n\
|
||||
4 0 obj\n<</N 3/Length 0>>stream\n\nendstream\nendobj\n5 0 obj\n<</N 4/Length 0>>stream\n\nendstream\nendobj\n\
|
||||
6 0 obj\n<</N 4/Length 0>>stream\n\nendstream\nendobj\n";
|
||||
|
||||
#[test]
|
||||
fn groups_blend_in_the_documents_cmyk_space_else_device_cmyk() {
|
||||
let rgb = "/CS 1 0 R".to_string();
|
||||
// The space of the document's profile, wherever it is.
|
||||
for without in [Without::FirstCmyk, Without::DeviceCmyk, Without::Rgb] {
|
||||
assert_eq!(icc_spaces(SPACES, Some(6), without), [(rgb.clone(), "/CS 3 0 R".to_string())], "{without:?}");
|
||||
}
|
||||
// Without it, DeviceCMYK, or RGB where DeviceCMYK isn't allowed, rather than another
|
||||
// profile's space; the first CMYK space when the document's profile isn't known.
|
||||
assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]);
|
||||
assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []);
|
||||
assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]);
|
||||
}
|
||||
}
|
||||
|
||||
+78
-18
@@ -10,7 +10,9 @@
|
||||
//! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is
|
||||
//! when its numbers are kept; the others' ink amounts are resampled, converted when the Output
|
||||
//! settings convert CMYK colours ([`CmykPixels`]) and compressed again. CMYK JPEGs hold Adobe's
|
||||
//! inverted samples, which the PDF writer's Decode array undoes.
|
||||
//! inverted samples, which the PDF writer's Decode array undoes. A CMYK image whose numbers are
|
||||
//! kept carries the CMYK profile it is given ([`cmyk_icc`]), whether it is embedded as it is or
|
||||
//! written again; without one it is untagged, a JPEG's own `ICC_PROFILE` segments included.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
@@ -26,7 +28,8 @@ use vectorcraft_doc::cmyk::jpeg_components;
|
||||
use crate::output::{CmykPixels, Pixels};
|
||||
use crate::{CompressionSettings, Downsample, ImageCodec, JpegQuality, MonoCodec};
|
||||
|
||||
/// Raw 8-bit pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel.
|
||||
/// Raw 8-bit pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, with the
|
||||
/// ICC profile the colour samples are in, if any.
|
||||
#[derive(Clone, Hash)]
|
||||
struct Raw {
|
||||
color: Arc<Vec<u8>>,
|
||||
@@ -34,6 +37,7 @@ struct Raw {
|
||||
width: u32,
|
||||
height: u32,
|
||||
space: ImageColorspace,
|
||||
icc: Option<Arc<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl CustomImage for Raw {
|
||||
@@ -54,7 +58,7 @@ impl CustomImage for Raw {
|
||||
}
|
||||
|
||||
fn icc_profile(&self) -> Option<&[u8]> {
|
||||
None
|
||||
self.icc.as_deref().map(Vec::as_slice)
|
||||
}
|
||||
|
||||
fn color_space(&self) -> ImageColorspace {
|
||||
@@ -79,7 +83,7 @@ fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Op
|
||||
(px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb)
|
||||
};
|
||||
let alpha = px.iter().any(|p| p[3] < 255).then(|| Arc::new(px.iter().map(|p| p[3]).collect()));
|
||||
Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space }, interpolate).ok()
|
||||
Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, icc: None }, interpolate).ok()
|
||||
}
|
||||
|
||||
/// Are all of the RGBA pixels `rgba` grey?
|
||||
@@ -88,9 +92,57 @@ fn neutral(rgba: &[u8]) -> bool {
|
||||
}
|
||||
|
||||
/// Colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) with an optional `alpha`
|
||||
/// channel, written losslessly.
|
||||
fn lossless(samples: Vec<u8>, alpha: Option<Vec<u8>>, space: ImageColorspace, width: u32, height: u32, interpolate: bool) -> Option<Image> {
|
||||
Image::from_custom(Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space }, interpolate).ok()
|
||||
/// channel, written losslessly, tagged with ICC profile `icc` when given.
|
||||
fn lossless(
|
||||
samples: Vec<u8>,
|
||||
alpha: Option<Vec<u8>>,
|
||||
space: ImageColorspace,
|
||||
width: u32,
|
||||
height: u32,
|
||||
interpolate: bool,
|
||||
icc: Option<&[u8]>,
|
||||
) -> Option<Image> {
|
||||
let icc = icc.map(|icc| Arc::new(icc.to_vec()));
|
||||
Image::from_custom(Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, icc }, interpolate).ok()
|
||||
}
|
||||
|
||||
/// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image
|
||||
/// it holds is still written.
|
||||
pub(crate) const MAX_EMBED_PIXELS: u64 = 1 << 27;
|
||||
|
||||
/// The most bytes a CMYK profile carried by an image is written with (16 MiB).
|
||||
const MAX_ICC: usize = 16 << 20;
|
||||
|
||||
/// The CMYK ICC profile image `blob` carries ([`ImageBlob::cmyk_icc_profile`]), when it is one a
|
||||
/// CMYK image can be tagged with: at most [`MAX_ICC`] bytes, the size its header declares, the
|
||||
/// `acsp` signature, an input, display, output or colour space profile of CMYK colours, and a tag
|
||||
/// table whose tags lie within it. `None` for other images and other profiles.
|
||||
pub(crate) fn cmyk_icc(blob: &ImageBlob) -> Option<Vec<u8>> {
|
||||
blob.cmyk_icc_profile().filter(|icc| valid_cmyk_icc(icc))
|
||||
}
|
||||
|
||||
/// Is `icc` a CMYK profile as [`cmyk_icc`] describes?
|
||||
fn valid_cmyk_icc(icc: &[u8]) -> bool {
|
||||
let be = |at: usize| icc.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes);
|
||||
let fits = |at: u32, len: u32| u64::from(at) + u64::from(len) <= icc.len() as u64;
|
||||
if icc.len() > MAX_ICC || be(0).and_then(|n| usize::try_from(n).ok()) != Some(icc.len()) {
|
||||
return false;
|
||||
}
|
||||
let class = icc.get(12..16);
|
||||
if icc.get(36..40) != Some(b"acsp".as_slice())
|
||||
|| icc.get(16..20) != Some(b"CMYK".as_slice())
|
||||
|| ![b"scnr", b"mntr", b"prtr", b"spac"].iter().any(|c| class == Some(c.as_slice()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(count) = be(128) else { return false };
|
||||
if !fits(132, count.saturating_mul(12)) {
|
||||
return false;
|
||||
}
|
||||
(0..count as usize).all(|i| {
|
||||
let at = 132 + i * 12;
|
||||
matches!((be(at + 4), be(at + 8)), (Some(offset), Some(len)) if fits(offset, len))
|
||||
})
|
||||
}
|
||||
|
||||
/// [`from_rgba`] of pixels converted by `pixels` (when given).
|
||||
@@ -114,7 +166,7 @@ pub(crate) fn from_inks(inks: Vec<u8>, alpha: Vec<u8>, width: u32, height: u32,
|
||||
Some(p) => p.convert(&inks),
|
||||
None => (inks, ImageColorspace::Cmyk),
|
||||
};
|
||||
lossless(samples, alpha, space, width, height, interpolate)
|
||||
lossless(samples, alpha, space, width, height, interpolate, None)
|
||||
}
|
||||
|
||||
/// The kinds of images the Compression section has settings for.
|
||||
@@ -291,7 +343,7 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in
|
||||
None if grey => (rgba.pixels().map(|p| p[0]).collect(), ImageColorspace::Luma),
|
||||
None => (rgba.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb),
|
||||
};
|
||||
to_jpeg(&samples, space, width, height, q, interpolate)
|
||||
to_jpeg(&samples, space, width, height, q, interpolate, None)
|
||||
});
|
||||
let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert));
|
||||
Recoded { image, warning: rule.instead }
|
||||
@@ -323,7 +375,8 @@ pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c
|
||||
/// is when its numbers are (`convert` is `None`); otherwise its ink amounts are resampled,
|
||||
/// converted by `convert` and compressed again. With `alpha` (one sample a pixel, see
|
||||
/// [`mask_alpha`]) the image is lossless and carries it as its soft mask; `None` then when its
|
||||
/// inks can't be read.
|
||||
/// inks can't be read. When its numbers are kept, the image is tagged with CMYK profile `icc`
|
||||
/// (see [`cmyk_icc`]), and is untagged without one; converted pixels are never tagged with it.
|
||||
pub(crate) fn recode_cmyk(
|
||||
blob: &ImageBlob,
|
||||
size: (f64, f64),
|
||||
@@ -331,13 +384,20 @@ pub(crate) fn recode_cmyk(
|
||||
interpolate: bool,
|
||||
convert: Option<&CmykPixels>,
|
||||
alpha: Option<Vec<u8>>,
|
||||
icc: Option<&[u8]>,
|
||||
) -> Recoded {
|
||||
let rule = rule(c, Kind::Color);
|
||||
let jpeg = jpeg_components(&blob.bytes).is_some();
|
||||
let icc = icc.filter(|_| convert.is_none());
|
||||
if jpeg && convert.is_none() && alpha.is_none() {
|
||||
let dims = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok());
|
||||
if dims.is_some_and(|d| kept(&rule, d, size, true)) {
|
||||
return Recoded { image: None, warning: rule.instead };
|
||||
if let Some((w, h)) = dims.filter(|d| kept(&rule, *d, size, true)) {
|
||||
// The JPEG data as it is, tagged with `icc` rather than with its own segments; one
|
||||
// larger than [`MAX_EMBED_PIXELS`] is not written.
|
||||
let image = (u64::from(w) * u64::from(h) <= MAX_EMBED_PIXELS)
|
||||
.then(|| Image::from_jpeg_with_icc(blob.bytes.as_ref().clone().into(), icc.map(|i| i.to_vec().into()), interpolate).ok())
|
||||
.flatten();
|
||||
return Recoded { image, warning: rule.instead };
|
||||
}
|
||||
}
|
||||
let Some(inks) = blob.cmyk() else {
|
||||
@@ -360,8 +420,8 @@ pub(crate) fn recode_cmyk(
|
||||
None => (inks, ImageColorspace::Cmyk),
|
||||
};
|
||||
// JPEG needs opaque pixels.
|
||||
let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate));
|
||||
let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate));
|
||||
let image = jpeg_quality(&rule, jpeg).filter(|_| alpha.is_none()).and_then(|q| to_jpeg(&samples, space, width, height, q, interpolate, icc));
|
||||
let image = image.or_else(|| lossless(samples, alpha, space, width, height, interpolate, icc));
|
||||
Recoded { image, warning: rule.instead }
|
||||
}
|
||||
|
||||
@@ -405,9 +465,9 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool)
|
||||
}
|
||||
|
||||
/// Opaque colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) as a JPEG at
|
||||
/// `quality`. CMYK JPEGs hold Adobe's inverted samples, which the PDF writer's Decode array
|
||||
/// undoes.
|
||||
fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, quality: u8, interpolate: bool) -> Option<Image> {
|
||||
/// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples,
|
||||
/// which the PDF writer's Decode array undoes.
|
||||
fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, quality: u8, interpolate: bool, icc: Option<&[u8]>) -> Option<Image> {
|
||||
let mut out = Vec::new();
|
||||
match space {
|
||||
ImageColorspace::Cmyk => {
|
||||
@@ -420,5 +480,5 @@ fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, qual
|
||||
}
|
||||
ImageColorspace::DeviceN => return None,
|
||||
}
|
||||
Image::from_jpeg(out.into(), interpolate).ok()
|
||||
Image::from_jpeg_with_icc(out.into(), icc.map(|i| i.to_vec().into()), interpolate).ok()
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@
|
||||
//! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey
|
||||
//! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4
|
||||
//! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a
|
||||
//! CMYK destination (see [`crate::pdfx`]).
|
||||
//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with
|
||||
//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3
|
||||
//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]).
|
||||
//! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent
|
||||
//! of the catalog with the condition, identifier and registry; Trapped goes in the document
|
||||
//! information (`/False` when an output intent is written untrapped). PDF/A files carry their
|
||||
@@ -59,6 +61,9 @@ pub(crate) struct ColorOut {
|
||||
dest: Option<Dest>,
|
||||
/// Colours are written in ICC-based colour spaces.
|
||||
pub tagged: bool,
|
||||
/// CMYK images that keep their numbers are tagged with the CMYK profile they carry
|
||||
/// ([`Self::cmyk_image_icc`]).
|
||||
image_icc: bool,
|
||||
/// The CMYK profile that tags CMYK colours.
|
||||
cmyk_profile: String,
|
||||
/// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB
|
||||
@@ -105,6 +110,7 @@ impl Default for ColorOut {
|
||||
profile_notes: vec![],
|
||||
dest: None,
|
||||
tagged: false,
|
||||
image_icc: false,
|
||||
cmyk_profile,
|
||||
srgb_note: None,
|
||||
pixels: OnceLock::new(),
|
||||
@@ -240,6 +246,14 @@ impl ColorOut {
|
||||
ProfileInclusion::All | ProfileInclusion::Destination => true,
|
||||
ProfileInclusion::TaggedSource => !doc.color_profiles.is_empty(),
|
||||
});
|
||||
// Source profiles: with `all` and `taggedSource`, and in the files that tag every colour
|
||||
// unless only the destination profile is asked for; never in PDF/X-1a.
|
||||
out.image_icc = !set.standard.cmyk_only()
|
||||
&& match set.output.profiles {
|
||||
ProfileInclusion::All | ProfileInclusion::TaggedSource => true,
|
||||
ProfileInclusion::None => matches!(set.standard, Standard::PdfA2b | Standard::PdfX3 | Standard::PdfX4),
|
||||
ProfileInclusion::Destination => false,
|
||||
};
|
||||
let rgb = match &out.dest {
|
||||
Some(d) if d.model == Model::Rgb => (d.srgb, d.cms.settings().rgb.clone()),
|
||||
_ => (source.rgb_is_srgb(), st.rgb.clone()),
|
||||
@@ -324,6 +338,16 @@ impl ColorOut {
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it
|
||||
/// carries, when its numbers are kept and the Profiles setting or the standard includes source
|
||||
/// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK.
|
||||
pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option<Vec<u8>> {
|
||||
if !self.image_icc || self.cmyk_pixels().is_some() {
|
||||
return None;
|
||||
}
|
||||
crate::images::cmyk_icc(blob)
|
||||
}
|
||||
|
||||
/// How CMYK images' ink amounts are converted; `None` when they keep their numbers (no
|
||||
/// conversion, or to a CMYK destination that keeps them).
|
||||
pub(crate) fn cmyk_pixels(&self) -> Option<&CmykPixels> {
|
||||
@@ -477,7 +501,7 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option<Catalog> {
|
||||
|
||||
/// The object number of the stream of an ICC-based colour space of `pdf` that holds profile `icc`
|
||||
/// (its data as it is, or Flate-compressed); `None` when no colour space uses that profile.
|
||||
fn tagging_stream(pdf: &[u8], xref: &Xref, icc: &[u8]) -> Option<u32> {
|
||||
pub(crate) fn tagging_stream(pdf: &[u8], xref: &Xref, icc: &[u8]) -> Option<u32> {
|
||||
use std::io::Read;
|
||||
const ICC: &[u8] = b"[/ICCBased ";
|
||||
let mut from = 0;
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_color::cms::{self, Cms, Model, ProfileKind};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::inks::{Link, inks, plates, visit_node_colors};
|
||||
use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors};
|
||||
use vectorcraft_doc::overprint::darken_overprints;
|
||||
use vectorcraft_doc::{ColorMode, Document, ImageBlob, Node, NodeKind};
|
||||
|
||||
@@ -101,12 +101,33 @@ impl<'a> Separator<'a> {
|
||||
inks(self.doc, &self.cms, c, link, color.intent).on_plate(plate)
|
||||
}
|
||||
|
||||
/// Recolour `n`'s subtree as plate `plate`: the grey of each colour's coverage, unlinked.
|
||||
/// [`Self::ink`] of a colour that prints process plates `plates` with its spot tint
|
||||
/// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. With
|
||||
/// spots as process, each process plate prints `plates` layered with the spot tint's process
|
||||
/// equivalent, as a separated image's plates layer ([`vectorcraft_doc::separated::Separated::coverage_as`]).
|
||||
fn stop_ink(&self, plate: &str, c: &Color, link: Link, plates: StopPlates) -> f32 {
|
||||
let own = stop_inks(self.doc, &self.cms, c, link, plates, self.set.color.intent);
|
||||
let (Some(_), Some((name, tint))) = (plates, own.spot.as_ref()) else {
|
||||
return self.ink(plate, c, link);
|
||||
};
|
||||
if !self.set.output.spots_to_process {
|
||||
return own.on_plate(plate);
|
||||
}
|
||||
let Some(i) = cms::PROCESS_PLATES.iter().position(|p| *p == plate) else {
|
||||
return 0.0;
|
||||
};
|
||||
let spot = spot_color(self.doc, name).map_or(0.0, |s| self.ink(plate, &s.tinted(*tint), None));
|
||||
1.0 - (1.0 - own.cmyk[i]) * (1.0 - spot)
|
||||
}
|
||||
|
||||
/// Recolour `n`'s subtree as plate `plate`: the grey of each colour's coverage, unlinked and
|
||||
/// without process plates.
|
||||
pub fn node(&self, plate: &str, n: &mut Node) {
|
||||
visit_node_colors(n, &mut |c, swatch, tint| {
|
||||
*c = Color::Gray { k: self.ink(plate, c, swatch.as_deref().map(|s| (s, *tint))) };
|
||||
visit_node_colors(n, &mut |c, swatch, tint, plates| {
|
||||
*c = Color::Gray { k: self.stop_ink(plate, c, swatch.as_deref().map(|s| (s, *tint)), *plates) };
|
||||
*swatch = None;
|
||||
*tint = 1.0;
|
||||
*plates = None;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user