mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 21:42:59 -05:00
Merge pull request #9053 from dotCooCoo/feat/scripts-api-d5-swatches-symbols
Scripts: documents give scripts their swatches, spots, symbols, graphic styles and brushes
This commit is contained in:
17 files changed
+2982
-60
No files matched your search
@@ -28,6 +28,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// file, format and saved state share their data with the open ones until a step changes them.
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let style_trail = s.script_in_run.then(|| s.script_style_trail.clone());
|
||||
// A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record.
|
||||
let swatch_renames = s.swatch_renames.clone();
|
||||
let opens = s.plugin_events_mark();
|
||||
@@ -46,6 +47,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Err(e) => {
|
||||
s.swatch_renames = swatch_renames;
|
||||
roll_back(s, start, &stash);
|
||||
if let Some(mut trail) = style_trail {
|
||||
trail.resources_scanned = s.script_style_trail.resources_scanned;
|
||||
s.script_style_trail = trail;
|
||||
}
|
||||
// The documents the steps opened are closed again: plug-ins are not told of them.
|
||||
s.forget_plugin_opens_since(opens);
|
||||
s.notify_text_tool("batch.rollBack");
|
||||
|
||||
@@ -274,6 +274,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
h.session.borrow_mut().set_replaying(outer);
|
||||
super::dom::forget_removed(h)?;
|
||||
if let Err(e) = r {
|
||||
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
|
||||
return Err(match e {
|
||||
|
||||
@@ -111,6 +111,7 @@ mod print;
|
||||
mod raster_capture;
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT;
|
||||
mod resources;
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
@@ -120,19 +121,35 @@ mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::{PATH_LIST_BUILDS, POINT_LOOKS};
|
||||
|
||||
pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources};
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// Resources a command's steps removed or renamed (a document's uid, the kind and the name), and
|
||||
/// the names the steps compared.
|
||||
type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64);
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
/// ([`variables::before_command`]).
|
||||
/// ([`variables::before_command`]). The resources earlier commands removed stay noted until the
|
||||
/// run next looks up a resource object or [`forget_removed`] runs.
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
|
||||
tracing::before_command(h);
|
||||
variables::before_command(h, id)
|
||||
}
|
||||
|
||||
/// Charges the run for the resource names the last command's steps compared, whether it was kept
|
||||
/// or not, and whether `vc.run` or the object model ran it.
|
||||
pub(super) fn charge_scanned(h: &Host) -> std::result::Result<(), HostError> {
|
||||
let scanned = std::mem::take(&mut h.dom.resources_gone.borrow_mut().1);
|
||||
if scanned > 0 {
|
||||
h.charge_call(scanned)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After each command a script runs ([`variables::after_command`]).
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataSet>)>) {
|
||||
variables::after_command(h, before);
|
||||
@@ -205,7 +222,8 @@ thread_local! {
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// points, the swatches, symbols, styles and brushes the run's objects name, whether a call's own
|
||||
/// savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and
|
||||
/// layers its layers and groups gave, the active artboard of each document, and the tool
|
||||
@@ -237,6 +255,12 @@ pub(super) struct State {
|
||||
/// The item the object model is changing ([`edit_item`]), whose points stay valid through the
|
||||
/// change.
|
||||
editing: Cell<Option<Item>>,
|
||||
/// The resources the steps of kept commands removed or renamed, which the next lookup of a
|
||||
/// resource object or [`forget_removed`] marks stale, and how many names the last command's
|
||||
/// steps compared, which [`charge_scanned`] charges when the command ends.
|
||||
resources_gone: RefCell<GoneResources>,
|
||||
/// The swatches, symbols, styles and brushes the run's objects name ([`resources`]).
|
||||
resources: RefCell<resources::Table>,
|
||||
saving: Cell<bool>,
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
@@ -308,6 +332,9 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return f(h);
|
||||
}
|
||||
flush(h)?;
|
||||
// The removals noted before `f` are applied first, so that a failure drops only the ones its
|
||||
// commands noted.
|
||||
resources::settle_removed(h);
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
@@ -325,11 +352,20 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
// The resources `f`'s commands removed are back with the documents.
|
||||
h.dom.resources_gone.borrow_mut().0.clear();
|
||||
// Style objects are put back with the documents.
|
||||
text::styles::put_back(h, styles);
|
||||
r
|
||||
}
|
||||
|
||||
/// Makes the run's swatch, symbol, style and brush objects whose resource a command removed or
|
||||
/// renamed stale, so a new resource that takes the name later is not theirs, and checks every
|
||||
/// object against the documents after a `vc.run` command. The check is charged to the run.
|
||||
pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> {
|
||||
resources::forget_removed(h)
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
@@ -1057,11 +1093,31 @@ fn ends_run(e: &HostError) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed, and notes
|
||||
/// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands
|
||||
/// removed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
let (taken, scanned) = {
|
||||
let mut s = h.session.borrow_mut();
|
||||
let trail = &mut s.script_style_trail;
|
||||
(std::mem::take(&mut trail.resources_gone), std::mem::take(&mut trail.resources_scanned))
|
||||
};
|
||||
{
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.0.extend(taken);
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// After a command that is not kept: the resource names its steps compared are charged
|
||||
/// ([`charge_scanned`]), and the resources they removed are not marked stale.
|
||||
pub(super) fn keep_scanned(h: &Host) {
|
||||
let scanned = std::mem::take(&mut h.session.borrow_mut().script_style_trail.resources_scanned);
|
||||
let mut gone = h.dom.resources_gone.borrow_mut();
|
||||
gone.1 = gone.1.saturating_add(scanned);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the
|
||||
/// selection cannot be put back, the edit is undone too. The points the run read of the item's
|
||||
/// paths stay valid through the change ([`paths::see_all_points`]).
|
||||
@@ -3431,6 +3487,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
paths::install_enums(realm)?;
|
||||
resources::install_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
@@ -3544,9 +3601,9 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(resources::document_members(l));
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(layers::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.extend(save_open::document_members(l));
|
||||
@@ -3703,13 +3760,16 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = layers::members(c, l);
|
||||
members.extend(variables::item_members(l, c));
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
match *c {
|
||||
"PathItem" => members.extend(paths::path_item_members(l)),
|
||||
"SymbolItem" => members.extend(resources::symbol_item_members(l)),
|
||||
_ => {}
|
||||
}
|
||||
class(c, Some("PageItem"), members, None)
|
||||
}));
|
||||
classes.extend(paths::classes(l));
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(resources::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(layers::classes(l));
|
||||
|
||||
@@ -10,14 +10,16 @@
|
||||
//! Components are checked when a color is assigned to an object, and a value out of range throws a
|
||||
//! `RangeError` with nothing changed.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0,
|
||||
//! and `new SpotColor()` starts with a `tint` of 100;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
//! any other paint gives white. A `SpotColor` (<https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/>)
|
||||
//! can be assigned to a path's `fillColor` and `strokeColor`, not to a swatch's `color`.
|
||||
//! `GradientColor` and `PatternColor` can be read from an object but not assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -27,7 +29,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{Link, current, num, text};
|
||||
|
||||
/// The classes whose objects can be read from a fill or stroke but not assigned yet.
|
||||
/// The classes whose objects [`assigned`] refuses as not available yet. A path's `fillColor` and
|
||||
/// `strokeColor` take a `SpotColor` before [`assigned`] runs; a swatch's or spot's `color` does not.
|
||||
const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"];
|
||||
|
||||
/// The components of each color class, with the value `new` gives them.
|
||||
@@ -121,8 +124,20 @@ fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -
|
||||
}
|
||||
}
|
||||
|
||||
/// The `spot` and the `tint` (0 to 100, 0 when left out) of `d` when it is a `SpotColor`, else
|
||||
/// `None`.
|
||||
pub(super) fn spot_parts(d: &Data) -> std::result::Result<Option<(&Data, f64)>, HostError> {
|
||||
let Data::Object(o) = d else { return Ok(None) };
|
||||
if !matches!(o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v), Some(Data::String(s)) if s == "SpotColor") {
|
||||
return Ok(None);
|
||||
}
|
||||
let tint = component(o, "SpotColor", "tint", 0.0, 100.0)?;
|
||||
let spot = o.iter().find(|(k, _)| k == "spot").map_or(&Data::Undefined, |(_, v)| v);
|
||||
Ok(Some((spot, tint)))
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
fn unit(v: f64, scale: f64) -> f32 {
|
||||
pub(super) fn unit(v: f64, scale: f64) -> f32 {
|
||||
(v / scale) as f32
|
||||
}
|
||||
|
||||
|
||||
@@ -405,10 +405,12 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
// The document as the edit's step keeps it, read after the switch to it, which can measure
|
||||
// its type again.
|
||||
let doc = super::edit_item_with(h, item, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone());
|
||||
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
|
||||
Ok(doc)
|
||||
let doc = keeping_paths(h, item, || {
|
||||
super::edit_item_with(h, item, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone());
|
||||
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
|
||||
Ok(doc)
|
||||
})
|
||||
})?;
|
||||
if let Some((doc, selection)) = doc.zip(kept)
|
||||
&& let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid)
|
||||
@@ -421,10 +423,67 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape
|
||||
/// when it is a member of one, since the paint commands paint that owner in its place.
|
||||
fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times this thread listed a document's paths ([`path_items`]), for the tests.
|
||||
pub(crate) static PATH_LIST_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds,
|
||||
/// removes and reorders no object of its own. When it succeeds, the document made no new object,
|
||||
/// and the path is not inside a Shaper group, the lists of the document's, its layers' and its
|
||||
/// groups' paths ([`path_items`]) stay kept. An edit inside a Shaper group regenerates the group's
|
||||
/// paths, which can drop a path without making a new id.
|
||||
fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| {
|
||||
let s = h.session.borrow();
|
||||
if let Some(st) = s.documents().iter().find(|d| d.uid == item.doc.uid) {
|
||||
run(st);
|
||||
}
|
||||
};
|
||||
let mut kept = None;
|
||||
doc_state(h, &mut |st| {
|
||||
let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some());
|
||||
if !in_shaper {
|
||||
let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc));
|
||||
if listed {
|
||||
kept = Some((st.doc.clone(), st.doc.peek_next_id()));
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = f()?;
|
||||
if let Some((before, next)) = kept {
|
||||
doc_state(h, &mut |st| {
|
||||
if st.doc.peek_next_id() == next {
|
||||
for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) {
|
||||
list.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is
|
||||
/// inside, at any depth, or else its compound path when it is a member of one. The paint setters
|
||||
/// paint that owner ([`edit_paint`]).
|
||||
pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
|
||||
let ancestors = d.ancestry(id).unwrap_or_default();
|
||||
let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest);
|
||||
if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) {
|
||||
return shape;
|
||||
}
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Runs the paint command `id` with `params` on the object whose paint the path shows
|
||||
/// ([`paint_owner`]).
|
||||
fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
let owner = read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).id)?;
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.insert("ids".into(), json!([owner.0]));
|
||||
}
|
||||
edit_path(h, item, id, params)
|
||||
}
|
||||
|
||||
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
|
||||
@@ -462,7 +521,11 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
o.insert("objectOnly".into(), json!(true));
|
||||
}
|
||||
}
|
||||
let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?;
|
||||
let result = if KEEP_PATHS.contains(&id) {
|
||||
keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, ¶ms)))?
|
||||
} else {
|
||||
keeping_paint(h, || edit_item(h, item, id, ¶ms))?
|
||||
};
|
||||
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
|
||||
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
|
||||
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
|
||||
@@ -472,6 +535,10 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The commands [`edit_path`] runs that change only paint, stroke or fill rule, after which the
|
||||
/// document's paths are the ones listed before ([`keeping_paths`]).
|
||||
const KEEP_PATHS: &[&str] = &["paint.setFill", "paint.setStroke", "stroke.set", "object.setOverprint", "path.setFillRule"];
|
||||
|
||||
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
|
||||
/// and gradient and the recent colors as they were before it.
|
||||
fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
@@ -508,6 +575,8 @@ fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std:
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
|
||||
let ids: Rc<Vec<NodeId>> = match container {
|
||||
Some(c) => {
|
||||
@@ -998,9 +1067,15 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("PathPoints", &handle))
|
||||
}
|
||||
|
||||
/// Whether the path of `item` is closed: it has a subpath and every subpath is. Setting `closed` on
|
||||
/// a path with no subpath gives it an empty closed one ([`path_set_closed`]).
|
||||
fn is_closed(h: &super::Host, item: Item) -> std::result::Result<bool, HostError> {
|
||||
read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))
|
||||
}
|
||||
|
||||
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let item = this_path(h, a)?;
|
||||
read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed)))
|
||||
Ok(Data::Bool(is_closed(h, item)?))
|
||||
}
|
||||
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -1116,7 +1191,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::<std::result::Result<_, _>>()?;
|
||||
let f = with_doc(h, item.doc, |_, st| frame(st))?;
|
||||
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
|
||||
let closed = is_closed(h, item)?;
|
||||
let c = h.dom.coords.get();
|
||||
let anchors: Vec<Anchor> =
|
||||
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
|
||||
@@ -1186,7 +1261,7 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option<Color>) -> s
|
||||
Some(c) => json!({"color": colors::param(&c)}),
|
||||
None => json!({"none": true}),
|
||||
};
|
||||
edit_path(h, item, id, params)?;
|
||||
edit_paint(h, item, id, params)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1249,7 +1324,7 @@ fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() };
|
||||
if now != on {
|
||||
let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) };
|
||||
edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1263,14 +1338,37 @@ fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.fill))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.fill)
|
||||
}
|
||||
|
||||
fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(colors::of_paint(&this_look(h, a)?.1.stroke))
|
||||
let (item, look) = this_look(h, a)?;
|
||||
super::resources::paint_color(h, item.doc, &look.stroke)
|
||||
}
|
||||
|
||||
/// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is
|
||||
/// linked to it at that tint already. A `SpotColor` without a `spot`, as a color linked to a global
|
||||
/// process swatch reads, throws: it does not name the swatch it was read from.
|
||||
fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer {
|
||||
if matches!(spot, Data::Undefined) {
|
||||
return Err(HostError::Error("SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet".into()));
|
||||
}
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
let at_tint = |t: &f32| *t == colors::unit(tint, 100.0);
|
||||
let name = super::resources::assigned_spot(h, spot, item.doc)?;
|
||||
let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && at_tint(t));
|
||||
if !same {
|
||||
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer {
|
||||
if let Some((spot, tint)) = colors::spot_parts(arg(a, 1))? {
|
||||
return set_spot_color(h, a, fill, spot, tint);
|
||||
}
|
||||
let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?;
|
||||
let (item, look) = this_look(h, a)?;
|
||||
let now = if fill { &look.fill } else { &look.stroke };
|
||||
@@ -1291,7 +1389,7 @@ fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// Runs `stroke.set` with `params` on the path, unless `same`.
|
||||
fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer {
|
||||
if !same {
|
||||
edit_path(h, item, "stroke.set", params)?;
|
||||
edit_paint(h, item, "stroke.set", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -1489,9 +1587,10 @@ pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
|
||||
}
|
||||
|
||||
/// Sets the stroke weight of the path `item` to `weight` points.
|
||||
/// Sets the stroke weight of the path `item` to `weight` points, on the object whose paint the
|
||||
/// path shows ([`edit_paint`]).
|
||||
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
|
||||
edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
edit_paint(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
}
|
||||
|
||||
// ---- PathPoints ----
|
||||
@@ -1769,11 +1868,12 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Some(p) => p,
|
||||
None => origin?,
|
||||
};
|
||||
let closed = last.is_none() && is_closed(h, item)?;
|
||||
// The kept starts are dropped, so that `counted` is their only copy and grows in place.
|
||||
*h.dom.point_starts.borrow_mut() = None;
|
||||
edit_points(h, item, |subs| match subs.last_mut() {
|
||||
Some(sp) => sp.anchors.push(Anchor::corner(p)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)),
|
||||
None => subs.push(SubPath::new(vec![Anchor::corner(p)], closed)),
|
||||
})?;
|
||||
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
|
||||
let grown = Rc::make_mut(&mut counted);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1406,7 +1406,7 @@ fn note_ids(s: &mut Session) {
|
||||
/// it, for a result that cannot cross to the script.
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host));
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A
|
||||
// query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard.
|
||||
@@ -1439,6 +1439,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
match r {
|
||||
Ok(v) => {
|
||||
note_ids(s);
|
||||
// A command that is not a batch, such as `edit.undo`, notes the resources it removed too.
|
||||
note_resources(s);
|
||||
let (mut objects, mut bytes) = (0, 0);
|
||||
for st in &s.docs {
|
||||
match before.iter().find(|(uid, ..)| *uid == st.uid) {
|
||||
@@ -1458,7 +1460,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
Ok((v, objects, bytes, save))
|
||||
}
|
||||
Err(e) => {
|
||||
s.script_style_trail = StyleTrail::default();
|
||||
s.script_style_trail = StyleTrail { resources_scanned: s.script_style_trail.resources_scanned, ..Default::default() };
|
||||
if let Some(save) = save
|
||||
&& !save.restore(s)
|
||||
{
|
||||
@@ -1483,7 +1485,9 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
command(host, &id, ¶ms)
|
||||
let r = command(host, &id, ¶ms);
|
||||
dom::forget_removed(host)?;
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
|
||||
@@ -1515,6 +1519,12 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
let mut s = session.borrow_mut();
|
||||
(s.copies, step(&mut s, host, id, params))
|
||||
};
|
||||
// The resource names a failed command's steps compared are still charged, before its error is
|
||||
// given.
|
||||
if r.is_err() {
|
||||
dom::keep_scanned(host);
|
||||
dom::charge_scanned(host)?;
|
||||
}
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
@@ -1565,8 +1575,11 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::
|
||||
dom::after_kept_command(host);
|
||||
seen?;
|
||||
} else {
|
||||
dom::keep_scanned(host);
|
||||
session.borrow_mut().script_style_trail = StyleTrail::default();
|
||||
}
|
||||
// The resource names the command's steps compared are charged whoever ran it.
|
||||
dom::charge_scanned(host)?;
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
@@ -1577,19 +1590,28 @@ pub(crate) type StyleLists =
|
||||
/// What the steps of a command a script runs did to the documents' style lists
|
||||
/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step
|
||||
/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the
|
||||
/// documents a step reverted.
|
||||
#[derive(Default)]
|
||||
/// documents a step reverted. It also holds each open document as the last step left it, and the
|
||||
/// swatches, symbols, graphic styles and brushes a step removed or renamed.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct StyleTrail {
|
||||
lists: Vec<StyleLists>,
|
||||
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
|
||||
pub(crate) reverted: Vec<u64>,
|
||||
/// Whether the run holds resource objects, so that the steps note what they remove.
|
||||
watch_resources: bool,
|
||||
docs: Vec<(u64, Arc<crate::Document>)>,
|
||||
pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>,
|
||||
/// The resource names the steps compared, charged to the run with the check that follows.
|
||||
pub(crate) resources_scanned: u64,
|
||||
}
|
||||
|
||||
impl StyleTrail {
|
||||
/// A trail that starts from the documents' style lists now.
|
||||
fn start(s: &Session) -> Self {
|
||||
/// A trail that starts from the documents' style lists now, and from the documents themselves
|
||||
/// when `watch_resources`.
|
||||
fn start(s: &Session, watch_resources: bool) -> Self {
|
||||
let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect();
|
||||
StyleTrail { lists, ..Default::default() }
|
||||
let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() };
|
||||
StyleTrail { lists, docs, watch_resources, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1623,6 +1645,32 @@ pub(crate) fn note_style_lists(s: &mut Session) {
|
||||
}
|
||||
*last = (st.uid, st.reverts, c.clone(), p.clone());
|
||||
}
|
||||
note_resources(s);
|
||||
}
|
||||
|
||||
/// After a step of a batch a script runs, and after each command it runs: notes the swatches,
|
||||
/// symbols, styles and brushes the documents no longer have, when the run holds objects for them
|
||||
/// ([`dom::after_kept_command`]). A document the trail already compared is not compared again.
|
||||
fn note_resources(s: &mut Session) {
|
||||
let trail = &mut s.script_style_trail;
|
||||
if !trail.watch_resources {
|
||||
return;
|
||||
}
|
||||
trail.docs.retain(|(uid, _)| s.docs.iter().any(|d| d.uid == *uid));
|
||||
for st in &s.docs {
|
||||
let Some(last) = trail.docs.iter_mut().find(|(uid, _)| *uid == st.uid) else {
|
||||
trail.docs.push((st.uid, st.doc.clone()));
|
||||
continue;
|
||||
};
|
||||
if !Arc::ptr_eq(&last.1, &st.doc) {
|
||||
let (gone, scanned) = dom::resources_gone(&last.1, &st.doc);
|
||||
trail.resources_scanned = trail.resources_scanned.saturating_add(scanned);
|
||||
for (kind, name) in gone {
|
||||
trail.resources_gone.insert((st.uid, kind, name));
|
||||
}
|
||||
last.1 = st.doc.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]).
|
||||
@@ -3197,6 +3245,8 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the swatch, symbol, style and brush objects a run may hold, in place of 100,000.
|
||||
pub(crate) static TEST_MAX_SLOTS: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
|
||||
@@ -189,6 +189,7 @@ mod script_dom_defaults;
|
||||
mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_resources;
|
||||
mod script_dom_tracing;
|
||||
mod script_dom_transform;
|
||||
mod script_engines;
|
||||
|
||||
@@ -1838,7 +1838,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches is not available yet"));
|
||||
assert!(failure(&mut s, "app.activeDocument.gradients = 1;").contains("Document.gradients is not available yet"));
|
||||
// A deleted item or an earlier run's document is stale first.
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
@@ -3218,7 +3218,7 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
|
||||
#[test]
|
||||
fn unsupported_members_say_so() {
|
||||
let (mut s, _, _) = doc();
|
||||
assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet"));
|
||||
assert!(failure(&mut s, "app.activeDocument.gradients;").contains("Document.gradients is not available yet"));
|
||||
}
|
||||
|
||||
fn layer_names(s: &Session) -> Vec<String> {
|
||||
@@ -5398,7 +5398,7 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('gradients'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
|
||||
@@ -1160,17 +1160,174 @@ fn compound_path_members_read_the_paint_they_are_given() {
|
||||
assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_in_a_group_in_a_compound_shape_read_and_set_the_compound_shapes_paint() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group, b.0]})).unwrap();
|
||||
let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = node(&s, a).appearance.clone();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = null, all = app.activeDocument.pathItems; for (var i = 0; i < all.length; i++) if (all[i].geometricBounds[0] < 50) p = all[i];\
|
||||
vc.log(p.parent.parent.typename); var c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4; vc.log([p.fillColor.red, p.strokeWidth]);",
|
||||
);
|
||||
assert_ne!(out[0], json!("Layer"), "the path is inside a group inside the compound shape");
|
||||
assert_eq!(rounded(&out[1]), json!([200, 4]));
|
||||
let Paint::Solid { color: Color::Rgb { r, .. }, .. } = node(&s, shape).appearance.fill_paint() else {
|
||||
panic!("the compound shape has an RGB fill")
|
||||
};
|
||||
assert!((r - 200.0 / 255.0).abs() < 1e-3, "the compound shape takes the fill, got {r}");
|
||||
assert_eq!(node(&s, a).appearance, before, "the nested path's own paint is left as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_set_on_an_empty_path_holds_until_it_has_points() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems.add(); vc.log(p.closed); p.closed = true; vc.log(p.closed);\
|
||||
p.setEntirePath([[0, 300], [40, 300], [40, 240]]); vc.log(p.closed);\
|
||||
var q = app.activeDocument.pathItems.add(); q.closed = true; q.closed = false; q.setEntirePath([[0, 0], [1, 1]]); vc.log(q.closed);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(false), json!(true), json!(true), json!(false)]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems.add(); p.closed = true; p.pathPoints.add(); vc.log(p.closed);\
|
||||
p.closed = false; p.pathPoints.removeAll(); vc.log(p.closed);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(false)], "pathPoints.add keeps the state, and an opened path does not reopen closed");
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.lock", &json!({"ids": [id.0]})).unwrap();
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints.length); p.closed = false; vc.log(p.closed);");
|
||||
assert_eq!(out, vec![json!(0), json!(false)], "an unchanged assignment on a locked empty path is allowed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap();
|
||||
let before = node(&s, a).appearance.fill_paint();
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.tint]);");
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", 40]));
|
||||
assert!(failure(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").contains("SpotColor is not available yet"));
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint]);");
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 40]));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the spot color the fill has records no step");
|
||||
assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_paints_its_spot_at_its_tint() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink'); c.tint = 50;\
|
||||
p.fillColor = c; p.strokeColor = c; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 50, 50]));
|
||||
let n = node(&s, a);
|
||||
for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] {
|
||||
match paint {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - 0.5).abs() < 1e-6, "{name} at {tint}"),
|
||||
p => panic!("the paint is {p:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_left_without_a_tint_paints_at_its_default() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink');\
|
||||
p.fillColor = c; vc.log([p.fillColor.spot.name, p.fillColor.tint]);\
|
||||
p.strokeColor = {typename: 'SpotColor', spot: d.spots.getByName('Ink')}; vc.log([p.strokeColor.spot.name, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&Value::Array(out)), json!([["Ink", 100], ["Ink", 0]]), "new SpotColor() starts at 100, a color without a tint is 0");
|
||||
let n = node(&s, a);
|
||||
for (paint, want) in [(n.appearance.fill_paint(), 1.0), (n.appearance.stroke_paint(), 0.0)] {
|
||||
match paint {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - want).abs() < 1e-6, "{name} at {tint}"),
|
||||
p => panic!("the paint is {p:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_process_link_read_as_a_spot_color_is_not_assigned() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#3a9a40", "global": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Moss", "color": "#405a20", "global": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Leaf", "tint": 60})).unwrap();
|
||||
let b = rect(&mut s, 30.0, 30.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [b.0], "swatch": "Moss", "tint": 60})).unwrap();
|
||||
let c = rect(&mut s, 60.0, 60.0, 10.0, 10.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap();
|
||||
let paints = |s: &Session| [a, b, c].map(|id| node(s, id).appearance.fill_paint());
|
||||
let before = paints(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems; vc.log([q[2].fillColor.typename, q[2].fillColor.spot === undefined, q[1].fillColor.typename, q[0].fillColor.typename]);",
|
||||
);
|
||||
// `pathItems` lists c (unlinked), b (Moss), a (Leaf) and the document's first rectangle.
|
||||
assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]);
|
||||
for script in [
|
||||
"var q = app.activeDocument.pathItems; q[2].fillColor = q[2].fillColor;",
|
||||
"var q = app.activeDocument.pathItems; q[1].fillColor = q[2].fillColor;",
|
||||
"var q = app.activeDocument.pathItems; q[0].fillColor = q[2].fillColor;",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("global process swatch cannot be assigned yet"), "{script}: {e}");
|
||||
assert_eq!(paints(&s), before, "{script}");
|
||||
assert_eq!(undo_steps(&s), steps, "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_painted_with_registration_reads_and_takes_its_spot() {
|
||||
let (mut s, a) = doc_with_paints();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('[Registration]'); c.tint = 100;\
|
||||
p.strokeColor = c; vc.log([p.strokeColor.typename, p.strokeColor.spot.name, p.strokeColor.tint]);",
|
||||
);
|
||||
assert_eq!(rounded(&out[0]), json!(["SpotColor", "[Registration]", 100]));
|
||||
assert!(node(&s, a).appearance.stroke_paint().is_registration(), "the stroke is linked to Registration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_color_without_a_spot_of_the_document_is_refused() {
|
||||
let (mut s, _) = doc_with_paints();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let layers = |s: &Session| s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect::<Vec<_>>();
|
||||
let before = layers(&s);
|
||||
let steps = undo_steps(&s);
|
||||
for (source, part) in [
|
||||
("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
|
||||
("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"),
|
||||
// `app.documents` lists the active document, the new one, first: the document with `Ink` is
|
||||
// `documents[1]`.
|
||||
("var a = app.documents[1], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"),
|
||||
(
|
||||
"var a = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;",
|
||||
"SpotColor.tint",
|
||||
),
|
||||
(
|
||||
"var a = app.documents[1], b = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); b.pathItems[0].fillColor = c;",
|
||||
"Cross-document",
|
||||
),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
}
|
||||
assert_eq!(layers(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filled_true_on_a_filled_path_runs_no_command() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1349,6 +1506,145 @@ fn looking_for_changed_points_after_each_command_is_charged() {
|
||||
assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_and_point_edits_keep_the_list_of_paths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
for i in 0..50 {
|
||||
rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0);
|
||||
}
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let start = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get());
|
||||
log(
|
||||
&mut s,
|
||||
"var ps = app.activeDocument.pathItems;\
|
||||
for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\
|
||||
ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }",
|
||||
);
|
||||
let built = crate::script::dom::PATH_LIST_BUILDS.with(|n| n.get()) - start;
|
||||
assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits");
|
||||
let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);");
|
||||
assert_eq!(out, vec![json!([50, 51])], "a new path is listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
|
||||
for x in [0.0, 50.0] {
|
||||
rect(&mut s, x, 50.0, 100.0, 100.0);
|
||||
}
|
||||
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let sources = vectorcraft_doc::shaper::SOURCES;
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var ps = app.activeDocument.pathItems, n = ps.length, src = null;\
|
||||
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src = ps[i];\
|
||||
var q = src.pathPoints[0]; q.anchor = [q.anchor[0] + 200, q.anchor[1]]; src.fillColor = new GrayColor(); vc.log(ps.length);"
|
||||
),
|
||||
);
|
||||
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_drops_a_shaper_path_lists_the_paths_again() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap();
|
||||
for x in [0.0, 50.0] {
|
||||
rect(&mut s, x, 50.0, 100.0, 100.0);
|
||||
}
|
||||
s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let sources = vectorcraft_doc::shaper::SOURCES;
|
||||
let before = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
// The paths are listed again after the first edit. The second edit takes the generated fill
|
||||
// away, and a regeneration that makes no path makes no new id.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var ps = app.activeDocument.pathItems, n = ps.length, src = [];\
|
||||
for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src.push(ps[i]);\
|
||||
for (var i = 0; i < src.length; i++) {{ src[i].fillColor = new NoColor(); var m = ps.length; }} vc.log(ps.length);"
|
||||
),
|
||||
);
|
||||
let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);");
|
||||
assert_ne!(before, fresh, "the edit changes how many paths the document has");
|
||||
assert_eq!(out, fresh, "the list after the edit matches a fresh run's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
vc.run('path.setAnchors', {{id: {}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
|
||||
p.pathPoints.removeAll(); vc.log(p.closed);",
|
||||
id.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(false)], "the open points the command gave end the setting");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
vc.run('path.setAnchors', {{id: {0}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\
|
||||
vc.run('path.setAnchors', {{id: {0}, subpaths: []}}); vc.log(p.closed);",
|
||||
id.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(false)], "clearing the points through a command does not restore the setting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_batch_ends_the_empty_path_closed_setting_even_when_it_removes_its_points() {
|
||||
for fail in [false, true] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
|
||||
let failure = if fail { ", {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}" } else { "" };
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true; var failed = false;\
|
||||
try {{ vc.run('command.batch', {{commands: [\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: []}}}}{failure}]}}); }} catch (e) {{ failed = true; }}\
|
||||
vc.log(failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(fail), json!(0), json!(fail)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_failed_dataset_row_keeps_the_empty_path_closed_setting() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; p.closed = true;\
|
||||
var r = vc.run('action.batch', {{source: 'datasets', commands: [\
|
||||
{{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\
|
||||
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
|
||||
vc.log(r.failed); vc.log(p.pathPoints.length); vc.log(p.closed);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!(0), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_are_written_before_the_next_other_member_reads() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -2049,7 +2345,7 @@ fn bad_color_components_throw_and_change_nothing() {
|
||||
("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"),
|
||||
("app.activeDocument.pathItems[0].fillColor = 5;", "color object"),
|
||||
("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"),
|
||||
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "not available yet"),
|
||||
("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
@@ -2500,6 +2796,23 @@ fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
assert_ne!(art(&s), before);
|
||||
}
|
||||
|
||||
/// An empty path in a group on a locked artboard refuses `closed = true`, and keeps allowing an
|
||||
/// assignment of the value it has.
|
||||
#[test]
|
||||
fn closing_an_empty_path_refuses_one_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
let empty = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.group", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let pick = "var d = app.activeDocument, p; for (var i = 0; i < d.pathItems.length; i++) { if (d.pathItems[i].pathPoints.length == 0) p = d.pathItems[i]; }";
|
||||
log(&mut s, &format!("{pick} p.closed = false;"));
|
||||
let e = failure(&mut s, &format!("{pick} p.closed = true;"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", empty.0)), "{e}");
|
||||
assert_eq!(log(&mut s, &format!("{pick} vc.log(p.closed);")), vec![json!(false)]);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
|
||||
assert_eq!(log(&mut s, &format!("{pick} p.closed = true; vc.log(p.closed);")), vec![json!(true)]);
|
||||
}
|
||||
|
||||
fn is_guide(s: &Session, id: NodeId) -> bool {
|
||||
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,842 @@
|
||||
//! The script object model's swatches, color groups, spots, symbols, graphic styles and brushes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt RGB document with one rectangle.
|
||||
fn doc() -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(s, a)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn swatch_names(s: &mut Session) -> Vec<String> {
|
||||
let l = s.execute("swatch.list", &json!({})).unwrap();
|
||||
l["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
/// The document's resources, to show that a failed call changed nothing.
|
||||
fn resources(s: &Session) -> String {
|
||||
let d = &s.active().unwrap().doc;
|
||||
format!("{:?}{:?}{:?}{:?}{:?}", *d.swatches, *d.swatch_groups, *d.graphic_styles, d.symbols, d.layers)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatches_are_live_and_keep_reserved_entries() {
|
||||
let (mut s, _) = doc();
|
||||
let names = swatch_names(&mut s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches; vc.log(w.length); vc.log(w.typename); vc.log(w.parent.typename);\
|
||||
vc.log(w[0].name); vc.log(w[1].name); vc.log(w[1].typename); vc.log(w[w.length] === undefined);\
|
||||
vc.log(w.getByName('Black').color.typename); try { w.getSelected(); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(names.len()),
|
||||
json!("Swatches"),
|
||||
json!("Document"),
|
||||
json!(names[0]),
|
||||
json!("[Registration]"),
|
||||
json!("Swatch"),
|
||||
json!(true),
|
||||
json!("RGBColor"),
|
||||
json!("Swatches.getSelected is not available yet")
|
||||
]
|
||||
);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches, n = w.add(); n.name = 'Script Ink';\
|
||||
var c = new RGBColor(); c.red = 10; c.green = 20; c.blue = 30; n.color = c;\
|
||||
vc.log(w.getByName('Script Ink').color.green); vc.log(n.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(20), json!("Script Ink")]);
|
||||
assert!(swatch_names(&mut s).contains(&"Script Ink".to_string()));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.swatches.removeAll();");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let left = swatch_names(&mut s);
|
||||
assert_eq!(left, vec![names[0].clone(), "[Registration]".to_string()]);
|
||||
for script in ["app.activeDocument.swatches[1].name = 'R';", "app.activeDocument.swatches[0].remove();"] {
|
||||
assert!(failure(&mut s, script).contains("is built in"), "{script}");
|
||||
}
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "app.activeDocument.swatches.removeAll();");
|
||||
assert_eq!(undo_steps(&s), steps, "a removeAll with nothing to remove records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatches_add_saves_a_gradient_fill_as_a_gradient() {
|
||||
let (mut s, _) = doc();
|
||||
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
|
||||
s.execute("paint.setFill", &json!({"gradient": ramp})).unwrap();
|
||||
let out = log(&mut s, "vc.log(app.activeDocument.swatches.add().color.typename);");
|
||||
assert_eq!(out, vec![json!("GradientColor")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_objects_go_stale_after_remove_and_follow_renames() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var w = app.activeDocument.swatches.getByName('Black'); w.name = 'Ink'; vc.log(w.name);\
|
||||
var again = app.activeDocument.swatches.getByName('Ink'); vc.log(again.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Ink"), json!("Ink")]);
|
||||
let cases = [
|
||||
("var w = app.activeDocument.swatches.getByName('Ink'); w.remove(); w.name;", "Stale Swatch"),
|
||||
("var w = app.activeDocument.swatches.getByName('White'); w.remove(); w.typename;", "Stale Swatch"),
|
||||
("var w = app.activeDocument.swatches.getByName('White'); vc.run('swatch.delete', {name: 'White'}); w.color;", "Stale Swatch"),
|
||||
(
|
||||
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('graphicStyle.rename', {name: g.name, to: 'X'}); g.name;",
|
||||
"Stale GraphicStyle",
|
||||
),
|
||||
("var w = app.activeDocument.swatches.getByName('Red'); w.remove(); app.activeDocument.swatches.add().name = 'Red'; w.name;", "Stale Swatch"),
|
||||
(
|
||||
"var w = app.activeDocument.swatches.getByName('Lime'); vc.run('swatch.delete', {name: 'Lime'}); vc.run('swatch.new', {name: 'Lime', color: '#00ff00'}); w.name;",
|
||||
"Stale Swatch",
|
||||
),
|
||||
(
|
||||
"var w = app.activeDocument.swatches.getByName('Yellow'); vc.run('command.batch', {commands: [\
|
||||
{command: 'swatch.delete', params: {name: 'Yellow'}}, {command: 'swatch.new', params: {name: 'Yellow', color: '#ffff00'}}]}); w.name;",
|
||||
"Stale Swatch",
|
||||
),
|
||||
(
|
||||
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('command.batch', {commands: [\
|
||||
{command: 'graphicStyle.rename', params: {name: g.name, to: 'X'}}, {command: 'graphicStyle.rename', params: {name: 'X', to: g.name}}]}); g.name;",
|
||||
"Stale GraphicStyle",
|
||||
),
|
||||
];
|
||||
for (script, message) in cases {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_object_goes_stale_when_a_batch_makes_its_swatch_process_and_back() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
|
||||
let toggle = "vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'Ink', spot: false}},\
|
||||
{command: 'swatch.edit', params: {name: 'Ink', spot: true}}]});";
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.spots.getByName('Ink'); {toggle} p.name;"));
|
||||
assert!(e.contains("Stale Spot"), "{e}");
|
||||
let out = log(&mut s, &format!("var w = app.activeDocument.swatches.getByName('Ink'); {toggle} vc.log(w.name);"));
|
||||
assert_eq!(out, vec![json!("Ink")], "the swatch object stays live");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn action_steps_finalize_resource_removals_before_the_next_step() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let actions = json!([{"set": "Set", "name": "Replace", "steps": [
|
||||
{"command": "action.batch", "params": {"source": "datasets", "commands": [
|
||||
{"command": "swatch.delete", "params": {"name": "Yellow"}},
|
||||
{"command": "swatch.new", "params": {"name": "Yellow", "color": "#ffff00"}}
|
||||
]}},
|
||||
{"command": "select.none"}
|
||||
]}]);
|
||||
let source = "var w = app.activeDocument.swatches.getByName('Yellow'); app.doScript('Replace', 'Set');\
|
||||
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
|
||||
vc.log(app.activeDocument.swatches.getByName('Yellow').name);";
|
||||
let r = s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})).unwrap();
|
||||
let out = r["log"].as_array().unwrap();
|
||||
assert!(out[0].as_str().unwrap().contains("Stale Swatch"), "{r}");
|
||||
assert_eq!(out[1], json!("Yellow"));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_failed_dataset_row_keeps_restored_resource_handles_live() {
|
||||
for change in ["{command: 'swatch.delete', params: {name: 'Yellow'}}", "{command: 'swatch.edit', params: {name: 'Yellow', newName: 'Ink'}}"] {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var w = app.activeDocument.swatches.getByName('Yellow');\
|
||||
var r = vc.run('action.batch', {{source: 'datasets', commands: [{change},\
|
||||
{{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\
|
||||
vc.log(r.failed); vc.log(w.name);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!("Yellow")], "{change}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_spots_is_charged_for_every_swatch_it_looks_at() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..300 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.length;";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("100 listings of 300 process swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_that_fails_is_charged_for_the_swatches_its_steps_compared() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument, w = d.swatches.getByName('P0'); for (var i = 0; i < 30; i++) {\
|
||||
try { vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: i % 2 ? '#112233' : '#445566'}},\
|
||||
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]}); } catch (e) {} }";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("30 failed batches over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
let source = "var w = app.activeDocument.swatches.getByName('P0');\
|
||||
vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: '#112233'}},\
|
||||
{command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]});";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("a failed batch over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "the scan budget error takes precedence over the missing swatch: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_artwork_symbol_class_leaves_the_built_in_symbol() {
|
||||
let (mut s, _) = doc();
|
||||
// A `.js` file runs as ECMAScript 2015, which has the built-in `Symbol`.
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-symbol-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("t.js");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"var d = app.activeDocument, m = d.symbols.add(d.pathItems[0]);\
|
||||
vc.log(typeof Symbol()); vc.log(typeof Symbol.iterator); vc.log(m.typename); vc.log(d.symbols.getByName(m.name).typename);",
|
||||
)
|
||||
.unwrap();
|
||||
let r = s.execute("script.run", &json!({"path": path.to_string_lossy()}));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(r.unwrap()["log"], json!(["symbol", "symbol", "Symbol", "Symbol"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_and_values_are_refused_without_change() {
|
||||
let (mut s, _) = doc();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let long = "x".repeat(1025);
|
||||
let cases = [
|
||||
("app.activeDocument.swatches.getByName('Black').name = 'a\\u0007b';".to_string(), "control characters"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = ' ';".to_string(), "cannot be empty"),
|
||||
(format!("app.activeDocument.swatches.getByName('Black').name = '{long}';"), "longer than 1024 bytes"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = 7;".to_string(), "must be a string"),
|
||||
("app.activeDocument.swatches.getByName('Black').name = 'White';".to_string(), "already exists"),
|
||||
("var d = app.activeDocument, p = d.spots.add(); p.name = 'Black';".to_string(), "a swatch or color group named Black already exists"),
|
||||
(
|
||||
"var d = app.activeDocument; d.swatchGroups.add().name = 'Mine'; d.swatches.getByName('White').name = 'Mine';".to_string(),
|
||||
"a swatch or color group named Mine already exists",
|
||||
),
|
||||
("app.activeDocument.swatches.getByName('Black').color = new NoColor();".to_string(), "cannot be NoColor"),
|
||||
("app.activeDocument.swatches.getByName('Black').color = {typename: 'RGBColor', red: 300};".to_string(), "from 0 to 255"),
|
||||
("app.activeDocument.swatches.getByName('nope');".to_string(), "Not found"),
|
||||
("app.activeDocument.swatches.index({});".to_string(), "name or an index"),
|
||||
("app.activeDocument.symbols.add(app.activeDocument);".to_string(), "not a page item"),
|
||||
("app.activeDocument.symbols.add(app.activeDocument.pageItems[0], 'SymbolRegistrationPoint.NOPE');".to_string(), "SymbolRegistrationPoint"),
|
||||
("app.activeDocument.symbolItems.add(app.activeDocument.swatches[2]);".to_string(), "not a Symbol"),
|
||||
("app.activeDocument.graphicStyles[0].applyTo([app.activeDocument.pageItems[0]]);".to_string(), "one page item"),
|
||||
];
|
||||
for (script, message) in &cases {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_keep_their_kind_and_their_color_space() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.spots.add(); p.name = 'Pea'; p.colorType = ColorModel.SPOT;\
|
||||
var c = new RGBColor(); c.red = 90; c.green = 200; c.blue = 30; p.color = c;\
|
||||
vc.log(d.spots.length); vc.log(p.typename); vc.log(p.colorType); vc.log(p.spotKind); vc.log(p.getInternalColor());\
|
||||
var w = d.swatches.getByName('Pea').color; vc.log(w.typename); vc.log(w.spot.name); vc.log(w.tint);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Spot"),
|
||||
json!("ColorModel.SPOT"),
|
||||
json!("SpotColorKind.SPOTRGB"),
|
||||
json!([90, 200, 30]),
|
||||
json!("SpotColor"),
|
||||
json!("Pea"),
|
||||
json!(100)
|
||||
]
|
||||
);
|
||||
let before = resources(&s);
|
||||
for (script, message) in [
|
||||
("var p = app.activeDocument.spots.getByName('Pea'); p.color = new GrayColor();", "must be an RGBColor, a CMYKColor or a LabColor"),
|
||||
("app.activeDocument.spots.getByName('Pea').colorType = ColorModel.PROCESS;", "stays a spot color"),
|
||||
("app.activeDocument.spots.getByName('Pea').colorType = 3;", "ColorModel value"),
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); var l = new LabColor(); l.l = 50; p.color = l;");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.getByName('Pea').spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]);
|
||||
log(&mut s, "app.activeDocument.spots.removeAll();");
|
||||
assert!(!swatch_names(&mut s).contains(&"Pea".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_takes_a_cmyk_color_in_an_rgb_document() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.spots.add(); p.name = 'Pea'; var c = new CMYKColor(); c.cyan = 35; c.yellow = 50; p.color = c;\
|
||||
var q = app.activeDocument.spots.getByName('Pea'); vc.log(q.color.typename); vc.log([q.color.cyan, q.color.yellow]); vc.log(q.spotKind);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("CMYKColor"), json!([35, 50]), json!("SpotColorKind.SPOTCMYK")]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
let cmyk =
|
||||
matches!(d.swatch("Pea").map(|w| &w.paint), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }));
|
||||
assert!(cmyk, "the spot keeps its CMYK color in the RGB document");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); p.color = p.color;");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the color the spot has records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 80, "m": 40, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": {"c": 60, "m": 0, "y": 90, "k": 10}})).unwrap();
|
||||
let rgb = |s: &Session, name: &str| {
|
||||
matches!(
|
||||
s.active().unwrap().doc.swatch(name).map(|w| &w.paint),
|
||||
Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. })
|
||||
)
|
||||
};
|
||||
let assign = |what: &str| format!("var c = new RGBColor(); c.red = 200; c.green = 60; c.blue = 20; {what}.color = c;");
|
||||
for (what, name) in [("app.activeDocument.spots.getByName('Pea')", "Pea"), ("app.activeDocument.swatches.getByName('Ink')", "Ink")] {
|
||||
if name == "Pea" {
|
||||
log(&mut s, "app.activeDocument.spots.add().name = 'Pea';");
|
||||
}
|
||||
let out = log(&mut s, &format!("{} var q = app.activeDocument.spots.getByName('{name}').color; vc.log([q.typename, q.red]);", assign(what)));
|
||||
assert_eq!(out, vec![json!(["RGBColor", 200])], "{what}");
|
||||
assert!(rgb(&s, name), "{name} keeps its RGB color in the CMYK document");
|
||||
let kind = log(&mut s, &format!("vc.log(app.activeDocument.spots.getByName('{name}').spotKind);"));
|
||||
assert_eq!(kind, vec![json!("SpotColorKind.SPOTRGB")], "{name}");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert_eq!(undo_steps(&s), steps, "assigning {name} the color it has records no step");
|
||||
}
|
||||
let what = "app.activeDocument.swatches.getByName('Leaf')";
|
||||
let paint = |s: &Session| s.active().unwrap().doc.swatch("Leaf").map(|w| w.paint.clone());
|
||||
let before = paint(&s);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert!(!rgb(&s, "Leaf"), "a process swatch stores the RGB color as CMYK in the CMYK document");
|
||||
assert_ne!(paint(&s), before, "the first assignment changes Leaf");
|
||||
assert!(
|
||||
matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. })),
|
||||
"Leaf holds a CMYK color"
|
||||
);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the first assignment records one step");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &assign(what));
|
||||
assert_eq!(undo_steps(&s), steps, "assigning Leaf the RGB color it was given records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_swatch_that_kept_an_rgb_color_takes_it_back_without_a_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Sky", "color": "#3080c0", "keepModel": true})).unwrap();
|
||||
let paint = |s: &Session| s.active().unwrap().doc.swatch("Sky").map(|w| w.paint.clone());
|
||||
let rgb = matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }));
|
||||
assert!(rgb, "the process swatch holds an RGB color in the CMYK document");
|
||||
let before = paint(&s);
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var w = app.activeDocument.swatches.getByName('Sky'); w.color = w.color;");
|
||||
assert_eq!(paint(&s), before, "the swatch keeps its RGB color");
|
||||
assert_eq!(undo_steps(&s), steps, "assigning the swatch its own color records no step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_list_registration_and_keep_it() {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, r = d.spots.getByName('[Registration]'); vc.log(r.typename); vc.log(r.colorType);\
|
||||
vc.log(d.spots[0].name); vc.log(d.spots.length); r.colorType = ColorModel.REGISTRATION;\
|
||||
vc.log(d.swatches.getByName('[Registration]').color.spot.name);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Spot"), json!("ColorModel.REGISTRATION"), json!("[Registration]"), json!(1), json!("[Registration]")]);
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
for script in [
|
||||
"app.activeDocument.spots.getByName('[Registration]').name = 'R';",
|
||||
"app.activeDocument.spots.getByName('[Registration]').remove();",
|
||||
"app.activeDocument.spots.getByName('[Registration]').color = new CMYKColor();",
|
||||
"app.activeDocument.spots.getByName('[Registration]').colorType = ColorModel.SPOT;",
|
||||
] {
|
||||
assert!(failure(&mut s, script).contains("is built in"), "{script}");
|
||||
}
|
||||
log(&mut s, "app.activeDocument.spots.removeAll();");
|
||||
assert_eq!(resources(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps, "removeAll with only Registration left records no step");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.length);"), vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
|
||||
let tint = s.execute("swatch.new", &json!({"tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var c = app.activeDocument.swatches.getByName('{tint}').color; vc.log(c.typename); vc.log(c.spot.name); vc.log(c.tint);"),
|
||||
);
|
||||
assert_eq!(out, vec![json!("SpotColor"), json!("Ink"), json!(40)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_add_converts_the_fill_to_the_document_color_space() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", "keepModel": true})).unwrap();
|
||||
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
|
||||
assert!(rgb, "the current fill is RGB in a CMYK document");
|
||||
let out = log(&mut s, "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename);");
|
||||
assert_eq!(out, vec![json!("SpotColorKind.SPOTCMYK"), json!("CMYKColor")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_add_converts_a_cmyk_or_gray_fill_in_an_rgb_document() {
|
||||
for fill in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"gray": 40})] {
|
||||
let (mut s, _) = doc();
|
||||
s.execute("paint.setFill", &json!({"color": fill})).unwrap();
|
||||
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
|
||||
assert!(!rgb, "the current fill {fill} is not RGB in an RGB document");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename); p.color = p.color; vc.log(p.name == '');",
|
||||
);
|
||||
assert_eq!(out, vec![json!("SpotColorKind.SPOTRGB"), json!("RGBColor"), json!(false)], "{fill}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_groups_hold_solid_swatches_only() {
|
||||
let (mut s, _) = doc();
|
||||
s.execute(
|
||||
"swatch.new",
|
||||
&json!({"name": "Ramp", "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.swatchGroups.add(); g.name = 'Script Group';\
|
||||
g.addSwatch(d.swatches.getByName('Black')); g.addSwatch(d.swatches.getByName('Black'));\
|
||||
var all = g.getAllSwatches(); vc.log(all.length); vc.log(all[0].name); vc.log(d.swatchGroups.getByName('Script Group').typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!("Black"), json!("SwatchGroup")]);
|
||||
let before = resources(&s);
|
||||
for (script, message) in [
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches.getByName('Ramp'));", "solid colors only"),
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches[0]);", "is built in"),
|
||||
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSpot(d.swatches.getByName('Black'));", "not a Spot"),
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains(message), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.swatchGroups.getByName('Script Group'), b = g.getAllSwatches()[0];\
|
||||
g.removeAll(); vc.log(g.getAllSwatches().length); try { b.name; } catch (e) { vc.log(String(e.message)); }\
|
||||
g.remove(); try { g.name; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0), json!("Stale Swatch"), json!("Stale SwatchGroup")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_add_keeps_the_source_and_instances_follow_their_symbol() {
|
||||
let (mut s, a) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, n = d.pageItems.length, sym = d.symbols.add(d.pageItems[0], SymbolRegistrationPoint.SYMBOLTOPLEFTPOINT);\
|
||||
vc.log(d.pageItems.length === n); vc.log(sym.typename); vc.log(d.symbols.length);\
|
||||
sym.name = 'Mark'; var copy = sym.duplicate(); vc.log(copy.name);\
|
||||
var inst = d.symbolItems.add(sym); vc.log(inst.typename); vc.log(inst.symbol.name); vc.log(d.symbolItems.length);\
|
||||
inst.symbol = copy; vc.log(inst.symbol.name); vc.log(d.selection.length === 0);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(true),
|
||||
json!("Symbol"),
|
||||
json!(1),
|
||||
json!("Mark copy"),
|
||||
json!("SymbolItem"),
|
||||
json!("Mark"),
|
||||
json!(1),
|
||||
json!("Mark copy"),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
assert!(s.active().unwrap().doc.node(a).is_some(), "the source art stays");
|
||||
let l = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!(l["symbols"][0]["registration"], json!(0));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.symbolItems.removeAll(); vc.log(d.symbols.length);");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, sym = d.symbols[0]; d.symbols.removeAll(); vc.log(d.symbols.length); try { sym.name; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0), json!("Stale Symbol")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_refuse_objects_of_another_document() {
|
||||
let (mut s, _) = doc();
|
||||
log(&mut s, "var d = app.activeDocument; d.symbols.add(d.pageItems[0]);");
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let before = resources(&s);
|
||||
// `app.documents` lists the active document, the new one, first: the document with the symbol
|
||||
// is `documents[1]`.
|
||||
for script in [
|
||||
"var a = app.documents[1], b = app.documents[0]; b.symbolItems.add(a.symbols[0]);",
|
||||
"var a = app.documents[1], b = app.documents[0]; a.graphicStyles[0].applyTo(b.pageItems[0]);",
|
||||
"var a = app.documents[1], b = app.documents[0]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));",
|
||||
"var a = app.documents[1], b = app.documents[0]; a.symbols.add(b.pageItems[0]);",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("Cross-document"), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphic_styles_apply_replaces_and_merge_adds() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Red"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.graphicStyles.getByName('Red'); vc.log(g.typename); vc.log(d.graphicStyles.typename);\
|
||||
g.applyTo(d.pageItems[0]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("GraphicStyle"), json!("GraphicStyles")]);
|
||||
let id = s.active().unwrap().doc.graphic_style("Red").unwrap().id;
|
||||
let n = s.active().unwrap().doc.node(b).unwrap().clone();
|
||||
assert_eq!(n.extras().graphic_style, Some(id));
|
||||
let fills = n.appearance.items.len();
|
||||
log(&mut s, "var d = app.activeDocument; d.graphicStyles.getByName('Red').mergeTo(d.pageItems[0]);");
|
||||
let n = s.active().unwrap().doc.node(b).unwrap().clone();
|
||||
assert!(n.appearance.items.len() > fills, "merge adds the style's rows");
|
||||
assert_eq!(n.extras().graphic_style, None);
|
||||
let before = resources(&s);
|
||||
for script in [
|
||||
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').name = 'Plain';",
|
||||
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').remove();",
|
||||
] {
|
||||
let e = failure(&mut s, script);
|
||||
assert!(e.contains("is built in"), "{script}: {e}");
|
||||
}
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "app.activeDocument.graphicStyles.removeAll();");
|
||||
let left: Vec<String> = s.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect();
|
||||
assert_eq!(left, vec![crate::doc::DEFAULT_GRAPHIC_STYLE.to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_apply_to_paths_only_and_once() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let first = s.execute("brush.list", &json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var b = app.activeDocument.brushes; vc.log(b.typename); vc.log(b[0].typename); vc.log(b[0].name); vc.log(b.removeAll === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Brushes"), json!("Brush"), json!(first), json!(true)]);
|
||||
let before = resources(&s);
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pageItems[0]);");
|
||||
assert!(e.contains("PathItem only"), "{e}");
|
||||
assert_eq!(resources(&s), before);
|
||||
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
|
||||
let st = s.active().unwrap().doc.node(a).unwrap().appearance.stroke().cloned().unwrap();
|
||||
assert_eq!(st.brush.as_deref(), Some(first.as_str()));
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
|
||||
assert_eq!(undo_steps(&s), steps, "applying the brush a path already draws runs no command");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_refuse_guides_clipping_paths_and_compound_members() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let (m1, m2) = (rect(&mut s, 100.0, 20.0, 30.0, 40.0), rect(&mut s, 150.0, 20.0, 30.0, 40.0));
|
||||
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let (c1, c2) = (rect(&mut s, 200.0, 20.0, 30.0, 40.0), rect(&mut s, 210.0, 30.0, 10.0, 10.0));
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let pick = |test: &str| {
|
||||
format!(
|
||||
"var d = app.activeDocument, p = null; for (var i = 0; i < d.pathItems.length; i++) {{ var q = d.pathItems[i]; if ({test}) p = q; }}\
|
||||
d.brushes[0].applyTo(p);"
|
||||
)
|
||||
};
|
||||
for test in ["q.guides", "q.clipping", "q.parent.typename == 'CompoundPathItem'"] {
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, &pick(test));
|
||||
assert!(e.contains("does not apply to a guide"), "{test}: {e}");
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "{test}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() {
|
||||
let (mut s, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'One'; d.spots.add().name = 'Two'; d.swatchGroups.add().name = 'Three';");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let before = resources(&s);
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'Four'; d.swatches.removeAll(); throw new Error('stop');");
|
||||
assert!(e.contains("stop"), "{e}");
|
||||
assert_eq!(resources(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_that_undo_removed_stays_stale_when_a_new_swatch_takes_its_name() {
|
||||
for make in ["vc.run('swatch.new', {name: n, color: '#ff0000'}); vc.log(true);", "vc.log(d.swatches.add().name == n);"] {
|
||||
let (mut s, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var d = app.activeDocument, k = d.swatches.length, w = d.swatches.add(), n = w.name; app.undo();\
|
||||
vc.log(d.swatches.length == k); {make}\
|
||||
try {{ vc.log(w.name); }} catch (e) {{ vc.log(e.message); }}"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[..2], [json!(true), json!(true)], "{make}: undo removes the swatch, and the new one takes its name");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{make}: {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_objects_made_before_a_revert_are_stale() {
|
||||
let (mut s, _) = doc();
|
||||
let path = std::env::temp_dir().join(format!("vc-resources-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, w = d.swatches.getByName('Black');\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
try { vc.log(w.name); } catch (e) { vc.log(e.message); }\
|
||||
var again = app.activeDocument.swatches.getByName('Black'); vc.log(again.name); vc.log(again === w);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert!(out[0].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{out:?}");
|
||||
assert_eq!(out[1..], [json!("Black"), json!(false)], "a swatch object made after the revert names the reverted swatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_refuse_paths_in_a_compound_shape_at_any_depth() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
|
||||
let (m1, m2, m3) = (rect(&mut s, 10.0, 20.0, 30.0, 40.0), rect(&mut s, 30.0, 30.0, 30.0, 40.0), rect(&mut s, 50.0, 40.0, 30.0, 40.0));
|
||||
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g, m3.0]})).unwrap();
|
||||
s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, n = d.pathItems.length, e = [];\
|
||||
for (var i = 0; i < n; i++) { try { d.brushes[0].applyTo(d.pathItems[i]); e.push('applied'); }\
|
||||
catch (x) { e.push(x.message.indexOf('compound shape') >= 0); } }\
|
||||
vc.log(n); vc.log(e);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(3), json!([true, true, true])], "the grouped members and the direct member are refused");
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_every_swatch_by_index_lists_the_swatches_once() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source =
|
||||
"var w = app.activeDocument.swatches, n = w.length, read = 0; for (var i = 0; i < n; i++) if (w[i]) read++; vc.log(read == n && n > 1000);";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap_or_else(|e| panic!("reading 1000 swatches by index: {e}"));
|
||||
assert_eq!(r["log"], json!([true]));
|
||||
let source = "var w = app.activeDocument.swatches, n = w.length; for (var i = 0; i < n; i++) { w[i]; app.activeDocument.swatches.add(); }";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("reading after each change listed the swatches once: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "a read after a change lists the swatches again and is charged: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_all_is_charged_for_the_records_it_looks_at() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.removeAll();";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("100 removeAll() calls over 1000 process swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
let colors: Vec<String> = (0..500).map(|i| format!("#{:06x}", i * 31)).collect();
|
||||
s.execute("swatch.newGroup", &json!({"name": "Many", "colors": colors})).unwrap();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000)));
|
||||
let r = run(&mut s, "app.activeDocument.swatchGroups.removeAll();");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("removing a group of 500 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "the group's swatches are charged: {e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_resource_past_the_object_limit_is_not_kept() {
|
||||
let (mut s, a) = doc();
|
||||
let before = resources(&s);
|
||||
let steps = undo_steps(&s);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
|
||||
let out = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pathItems[0], k = d.swatches[0], out = [];\
|
||||
var calls = [function () { d.swatches.add(); }, function () { d.spots.add(); }, function () { d.swatchGroups.add(); },\
|
||||
function () { d.symbols.add(p); }];\
|
||||
for (var i = 0; i < calls.length; i++) { try { calls[i](); out.push('made'); } catch (e) { out.push(e.message.indexOf('at most 1 ') >= 0); } }\
|
||||
vc.log(out);",
|
||||
);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
|
||||
assert_eq!(out.unwrap()["log"], json!([[true, true, true, true]]));
|
||||
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "no new resource is kept");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1)));
|
||||
let out = run(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, m = d.symbols.getByName('Mark');\
|
||||
try { m.duplicate(); vc.log('made'); } catch (e) { vc.log(e.message.indexOf('at most 1 ') >= 0); } vc.log(d.symbols.length);",
|
||||
);
|
||||
crate::script::TEST_MAX_SLOTS.with(|m| m.set(None));
|
||||
assert_eq!(out.unwrap()["log"], json!([true, 1]), "the duplicate is not kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_symbol_instance_with_a_large_id_keeps_its_id() {
|
||||
let (mut s, a) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let out = log(&mut s, "var d = app.activeDocument, i = d.symbolItems.add(d.symbols.getByName('Mark')); i.name = 'big'; vc.log(i.name);");
|
||||
assert_eq!(out, vec![json!("big")]);
|
||||
assert_eq!(s.active().unwrap().doc.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_swatch_colors_is_charged_for_the_swatches_each_change_compares() {
|
||||
let (mut s, _) = doc();
|
||||
for i in 0..1000 {
|
||||
s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap();
|
||||
}
|
||||
let source = "var w = app.activeDocument.swatches.getByName('P0'), a = new RGBColor(), b = new RGBColor(); b.red = 200;\
|
||||
for (var i = 0; i < 30; i++) w.color = i % 2 ? a : b;";
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000)));
|
||||
let r = run(&mut s, source);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("30 swatch color edits over 1000 swatches ran: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swatch_color_converts_through_the_profiles_of_its_own_document() {
|
||||
use vectorcraft_color::{Color, cms};
|
||||
let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("edit.assignProfile", &json!({"cmyk": cms::FOGRA51_CMYK})).unwrap();
|
||||
let rgb = Color::rgb(51.0 / 255.0, 128.0 / 255.0, 204.0 / 255.0);
|
||||
let own = {
|
||||
let c = crate::cmd::colormgmt::doc_cms(&s.active().unwrap().doc);
|
||||
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
|
||||
};
|
||||
let working = {
|
||||
let c = cms::working();
|
||||
c.convert(&rgb, cms::Model::Cmyk, c.settings().intent)
|
||||
};
|
||||
assert_ne!(own, working, "the assigned profile converts the color differently");
|
||||
s.execute("swatch.new", &json!({"name": "Sky", "color": serde_json::to_value(working).unwrap()})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
log(
|
||||
&mut s,
|
||||
"var w = null; for (var i = 0; i < app.documents.length; i++) { try { w = app.documents[i].swatches.getByName('Sky'); } catch (e) {} }\
|
||||
var c = new RGBColor(); c.red = 51; c.green = 128; c.blue = 204; w.color = c;",
|
||||
);
|
||||
let sky = s.documents().iter().find_map(|st| st.doc.swatch("Sky").map(|w| w.paint.clone()));
|
||||
let Some(vectorcraft_color::Paint::Solid { color, .. }) = sky else { panic!("Sky is a solid color: {sky:?}") };
|
||||
assert_ne!(color, working, "the swatch takes the color its own document's profile gives");
|
||||
assert_eq!(color, own);
|
||||
}
|
||||
@@ -99,12 +99,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
(
|
||||
"",
|
||||
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
|
||||
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
"activeDocument activeDocument= app Application Artboard Artboards BlendModes Brush Brushes ColorModel CompoundPathItem \
|
||||
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
|
||||
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
|
||||
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
|
||||
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
|
||||
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
|
||||
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
|
||||
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
|
||||
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
|
||||
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
|
||||
View Views ZOrderMethod",
|
||||
),
|
||||
("Application.", "prototype"),
|
||||
(
|
||||
@@ -133,15 +135,15 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
|
||||
"activeLayer activeLayer= artboards brushes characterStyles close compoundPathItems constructor convertCoordinate \
|
||||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||||
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
|
||||
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
|
||||
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
|
||||
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
("Views.prototype.", "constructor index length parent toString typename"),
|
||||
@@ -247,6 +249,35 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
|
||||
rightDirection= selected selected= toString typename",
|
||||
),
|
||||
("Swatches.", "prototype"),
|
||||
("Swatches.prototype.", "add constructor getByName getSelected getSelected= index length parent removeAll typename"),
|
||||
("Swatch.", "prototype"),
|
||||
("Swatch.prototype.", "color color= constructor name name= parent remove typename"),
|
||||
("Spots.", "prototype"),
|
||||
("Spots.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Spot.", "prototype"),
|
||||
("Spot.prototype.", "color color= colorType colorType= constructor getInternalColor name name= parent remove spotKind typename"),
|
||||
("SwatchGroups.", "prototype"),
|
||||
("SwatchGroups.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("SwatchGroup.", "prototype"),
|
||||
("SwatchGroup.prototype.", "addSpot addSwatch constructor getAllSwatches name name= parent remove removeAll typename"),
|
||||
("Symbols.", "prototype"),
|
||||
("Symbols.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Symbol.", "prototype"),
|
||||
("Symbol.prototype.", "constructor duplicate name name= parent remove typename"),
|
||||
("SymbolItems.", "prototype"),
|
||||
("SymbolItems.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("SymbolItem.", "prototype"),
|
||||
("SymbolItem.prototype.", "constructor symbol symbol="),
|
||||
("GraphicStyles.", "prototype"),
|
||||
("GraphicStyles.prototype.", "constructor getByName index length parent removeAll typename"),
|
||||
("GraphicStyle.", "prototype"),
|
||||
("GraphicStyle.prototype.", "applyTo constructor mergeTo name name= parent remove typename"),
|
||||
("Brushes.", "prototype"),
|
||||
("Brushes.prototype.", "constructor getByName index length parent typename"),
|
||||
("Brush.", "prototype"),
|
||||
("Brush.prototype.", "applyTo constructor name parent typename"),
|
||||
("ColorModel.", "PROCESS REGISTRATION SPOT"),
|
||||
("Tags.", "prototype"),
|
||||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Tag.", "prototype"),
|
||||
@@ -273,8 +304,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PolarityValues.", "NEGATIVE POSITIVE"),
|
||||
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
|
||||
("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"),
|
||||
("SpotColorKind.", "SPOTCMYK SPOTLAB SPOTRGB"),
|
||||
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
|
||||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||||
(
|
||||
"SymbolRegistrationPoint.",
|
||||
"SYMBOLBOTTOMLEFTPOINT SYMBOLBOTTOMMIDDLEPOINT SYMBOLBOTTOMRIGHTPOINT SYMBOLCENTERPOINT SYMBOLMIDDLELEFTPOINT \
|
||||
SYMBOLMIDDLERIGHTPOINT SYMBOLTOPLEFTPOINT SYMBOLTOPMIDDLEPOINT SYMBOLTOPRIGHTPOINT",
|
||||
),
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
// The enumerations of saving, exporting and opening.
|
||||
@@ -579,7 +616,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
/// that have no members of their own, the color classes, and the save, export, rasterize and image
|
||||
/// capture option classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
|
||||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
|
||||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor cmykColor \
|
||||
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \
|
||||
ImageCaptureOptions RasterizeOptions \
|
||||
ExportForScreensItemToExport ExportForScreensOptionsJPEG ExportForScreensOptionsPNG24 \
|
||||
|
||||
@@ -633,6 +633,11 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
own: Rc::new(own),
|
||||
members,
|
||||
});
|
||||
// The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype.
|
||||
let global = i.global;
|
||||
if class.name == "Symbol" && i.get_own_property(global, &key(&class.name))?.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,31 @@ fn non_finite_indexer_keys_reach_the_host_unchanged() {
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_named_like_a_built_in_global_leaves_the_built_in() {
|
||||
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let name: HostFunction = Rc::new(|_| Ok(Data::String("art".into())));
|
||||
let class = HostClass {
|
||||
name: "Symbol".into(),
|
||||
parent: None,
|
||||
members: vec![("name".into(), HostMember::Get(name))],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Symbol", &[1.0]))]).unwrap();
|
||||
let source = "[typeof Symbol(), typeof Symbol.iterator, it.name, it instanceof Symbol].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("symbol|symbol|art|false".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_class_replaces_an_existing_global_other_than_symbol() {
|
||||
let mut r = realm(1_000_000);
|
||||
let class = HostClass { name: "Math".into(), parent: None, members: vec![], info: Vec::new(), index: None, construct: None };
|
||||
r.define_host_classes(vec![class], vec![("it".into(), host_ref("Math", &[1.0]))]).unwrap();
|
||||
assert_eq!(r.run("it instanceof Math && it.constructor === Math").unwrap(), JsValue::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_receivers_obey_limits_lowered_after_the_object_was_created() {
|
||||
for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] {
|
||||
|
||||
+59
-1
@@ -3892,7 +3892,12 @@ through `$`:
|
||||
range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest
|
||||
decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it
|
||||
was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a
|
||||
global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
|
||||
global or spot swatch reads as a `SpotColor` with its `tint`, and with its `spot` when the swatch is a spot color or
|
||||
Registration). Assigning a `SpotColor` (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) links the fill or
|
||||
stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100; VectorCraft's own defaults are 100
|
||||
for `new SpotColor()` and 0 for a color object without a `tint`), with `paint.setFill` or `paint.setStroke`. A `SpotColor` read from a color linked to a global process
|
||||
swatch has no `spot` and does not name the swatch, so assigning it, or a `SpotColor` whose `spot` was never set,
|
||||
throws an error that says `SpotColor.spot` must be a Spot, and the path keeps its paint. Assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
|
||||
art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the
|
||||
stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
|
||||
it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error.
|
||||
@@ -3929,6 +3934,59 @@ through `$`:
|
||||
a default throws an error, since new art then takes that object's appearance. `scaleFactor`
|
||||
(https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts lists it as read-only) is always 1, since
|
||||
VectorCraft draws every document at its own size; after an assignment it still reads 1.
|
||||
- A `Document` also has `swatches`, `spots`, `swatchGroups`, `symbols`, `symbolItems`, `graphicStyles` and `brushes`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroups/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItems/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyles/
|
||||
and https://ai-scripting.docsforadobe.dev/jsobjref/Brushes/). Each has `length`, `parent`, `[i]`, `index(key)` and
|
||||
`getByName(name)`; all but `brushes` have `removeAll()`. `swatches.add()` and `spots.add()` run `swatch.new`,
|
||||
`swatchGroups.add()` runs `swatch.newGroup`, `symbols.add(sourceArt, registrationPoint?)` runs `symbol.new` with
|
||||
`keepArt: true` (the default point is `SymbolRegistrationPoint.SYMBOLCENTERPOINT`), and `symbolItems.add(symbol)`
|
||||
runs `symbol.place`. `swatches.getSelected()` throws that it is not available yet. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/)
|
||||
has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); the `color` of a spot swatch or of Registration reads as a
|
||||
`SpotColor` with its `spot` and a `tint` of 100, and a tint of a spot as that `spot` at its `tint`. A `Spot` (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) has
|
||||
`name`, `color`, `colorType`, `spotKind`, `getInternalColor()` and `remove()`. A `SwatchGroup`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/) has `name` (`swatch.renameGroup`), `addSwatch(swatch)`
|
||||
and `addSpot(spot)` (`swatch.move`), `getAllSwatches()`, `remove()` and `removeAll()`. A `Symbol`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Symbol/) has `name` (`symbol.options`), `duplicate()`
|
||||
(`symbol.duplicate`) and `remove()` (`symbol.delete`); in a script engine that a `.js` or `.mjs` script starts,
|
||||
the global `Symbol` stays the language's own (an engine that a `.jsx` script starts keeps the artwork `Symbol` for
|
||||
the scripts that reuse it), and a script reaches artwork symbols through `symbols` and `SymbolItem.symbol`. A `SymbolItem`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/) adds `symbol` to the page item members, which
|
||||
`symbol.replace` changes. A `GraphicStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/) has `name`
|
||||
(`graphicStyle.rename`), `applyTo(item)` and `mergeTo(item)` (`graphicStyle.apply`, with `add: true` for `mergeTo`)
|
||||
and `remove()` (`graphicStyle.delete`). A `Brush` (https://ai-scripting.docsforadobe.dev/jsobjref/Brush/) has a
|
||||
read-only `name` and `applyTo(item)` (`brush.apply`). The enumerations `SymbolRegistrationPoint`, `ColorModel` and
|
||||
`SpotColorKind` hold strings such as `"ColorModel.SPOT"`.
|
||||
VectorCraft's own rules: `swatches` lists None, Registration, the other ungrouped swatches and then each color
|
||||
group's, and `swatchGroups` lists the color groups. `swatches.add()` saves the current fill (a color, gradient or
|
||||
pattern) or black when the fill is None, and `spots.add()` the current fill, converted to the document's color
|
||||
space unless it is Lab, or black when it is not a solid color. None and Registration cannot change or be removed,
|
||||
and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and
|
||||
`graphicStyles.removeAll()` keeps it. A color group takes solid
|
||||
colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches
|
||||
and keeps the group. `spots` lists Registration and the spot colors. A spot's color, set through `Spot.color` or
|
||||
`Swatch.color`, takes an `RGBColor`, a `CMYKColor` or a `LabColor` in a document of either color space, and the spot
|
||||
keeps that color space. This is VectorCraft's own rule: the Spot page says a color in another space than the
|
||||
document's gives an error, and `spots.add()` follows the page by converting the fill. A process swatch's
|
||||
`Swatch.color` stores a new `RGBColor` in a CMYK document as CMYK, through the profiles that document is assigned. A
|
||||
process swatch that holds an RGB color in a CMYK document (one made with `keepModel: true`) and is given that same
|
||||
color back stays RGB, and no undo step is recorded. A spot's `colorType` reads
|
||||
and takes only `ColorModel.SPOT` (`ColorModel.REGISTRATION` for Registration), a gray spot's `spotKind` is
|
||||
`SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the
|
||||
components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns
|
||||
its instances into plain art. `applyTo` and `mergeTo` take one page item of the same document that can be edited,
|
||||
and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path or compound shape, at
|
||||
any depth. `Brush.applyTo` runs no command only when the path already draws that brush with no brush options and
|
||||
that brush is the current one; with another brush current, it runs `brush.apply`, which also makes the brush current.
|
||||
A name is 1 to 1,024 bytes, not blank, with no control characters, and a name a
|
||||
swatch, spot or color group already has throws for any of the three. Renaming a resource through these objects keeps
|
||||
the object. After it is removed, renamed or deleted with `vc.run`, removed by `app.undo()` or `app.redo()`, or its
|
||||
document is reverted, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`, `Stale Symbol`,
|
||||
`Stale GraphicStyle`, `Stale Brush`), also when a later resource takes its name. A run holds at most 100,000 of
|
||||
these objects, and a call that would make one more throws with nothing changed. An object of
|
||||
another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and
|
||||
assigning a `SpotColor` to a swatch's or spot's `color` are not available yet.
|
||||
- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type
|
||||
objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and
|
||||
`removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both
|
||||
|
||||
+1
-1
@@ -210,7 +210,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops and the other classes) and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1132,6 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
|
||||
Reference in new issue
Block a user